本文整理匯總了Python中cv2.IMREAD_GRAYSCALE屬性的典型用法代碼示例。如果您正苦於以下問題:Python cv2.IMREAD_GRAYSCALE屬性的具體用法?Python cv2.IMREAD_GRAYSCALE怎麽用?Python cv2.IMREAD_GRAYSCALE使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類cv2
的用法示例。
在下文中一共展示了cv2.IMREAD_GRAYSCALE屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: image
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_GRAYSCALE [as 別名]
def image(self, captcha_str):
"""
Generate a greyscale captcha image representing number string
Parameters
----------
captcha_str: str
string a characters for captcha image
Returns
-------
numpy.ndarray
Generated greyscale image in np.ndarray float type with values normalized to [0, 1]
"""
img = self.captcha.generate(captcha_str)
img = np.fromstring(img.getvalue(), dtype='uint8')
img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (self.h, self.w))
img = img.transpose(1, 0)
img = np.multiply(img, 1 / 255.0)
return img
示例2: get_data
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_GRAYSCALE [as 別名]
def get_data(path, activation):
'''Get the dataset
'''
data = []
image_names = []
for filename in os.listdir(path):
img = cv2.imread(os.path.join(path,filename), cv2.IMREAD_GRAYSCALE)
image_names.append(filename)
if img is not None:
data.append(img)
data = np.asarray(data)
if activation == 'sigmoid':
data = data.astype(np.float32)/(255.0)
elif activation == 'tanh':
data = data.astype(np.float32)/(255.0/2) - 1.0
data = data.reshape((data.shape[0], 1, data.shape[1], data.shape[2]))
np.random.seed(1234)
p = np.random.permutation(data.shape[0])
X = data[p]
return X, image_names
示例3: __init__
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_GRAYSCALE [as 別名]
def __init__(self, files, channel=3, resize=None, shuffle=False):
"""
Args:
files (list): list of file paths.
channel (int): 1 or 3. Will convert grayscale to RGB images if channel==3.
Will produce (h, w, 1) array if channel==1.
resize (tuple): int or (h, w) tuple. If given, resize the image.
"""
assert len(files), "No image files given to ImageFromFile!"
self.files = files
self.channel = int(channel)
assert self.channel in [1, 3], self.channel
self.imread_mode = cv2.IMREAD_GRAYSCALE if self.channel == 1 else cv2.IMREAD_COLOR
if resize is not None:
resize = shape2d(resize)
self.resize = resize
self.shuffle = shuffle
示例4: make_df1_df2
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_GRAYSCALE [as 別名]
def make_df1_df2(self, idx):
"""
Make the deformations
"""
df1 = cv2.imread(os.path.join(self.db_root_dir, self.deformations1[idx]), cv2.IMREAD_GRAYSCALE)
df2 = cv2.imread(os.path.join(self.db_root_dir, self.deformations2[idx]), cv2.IMREAD_GRAYSCALE)
if self.inputRes is not None:
df1 = imresize(df1, self.inputRes, interp='nearest')
df2 = imresize(df2, self.inputRes, interp='nearest')
df1 = np.array(df1, dtype=np.float32)
df1 = df1/np.max([df1.max(), 1e-8])
df2 = np.array(df2, dtype=np.float32)
df2 = df2/np.max([df2.max(), 1e-8])
return df1, df2
示例5: __getitem__
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_GRAYSCALE [as 別名]
def __getitem__(self, index):
datafiles = self.files[index]
image = cv2.imread(datafiles["img"], cv2.IMREAD_COLOR)
label = cv2.imread(datafiles["label"], cv2.IMREAD_GRAYSCALE)
size = image.shape
name = datafiles["name"]
if self.f_scale != 1:
image = cv2.resize(image, None, fx=self.f_scale, fy=self.f_scale, interpolation=cv2.INTER_LINEAR)
label = cv2.resize(label, None, fx=self.f_scale, fy=self.f_scale, interpolation = cv2.INTER_NEAREST)
label[label == 11] = self.ignore_label
image = np.asarray(image, np.float32)
if self.rgb:
image = image[:, :, ::-1] ## BGR -> RGB
image /= 255 ## using pytorch pretrained models
image -= self.mean
image /= self.vars
image = image.transpose((2, 0, 1)) # HWC -> CHW
# print('image.shape:',image.shape)
return image.copy(), label.copy(), np.array(size), name
示例6: load_flow_frames
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_GRAYSCALE [as 別名]
def load_flow_frames(image_dir, vid, start, num):
frames = []
for i in range(start, start+num):
imgx = cv2.imread(os.path.join(image_dir, vid, vid+'-'+str(i).zfill(6)+'x.jpg'), cv2.IMREAD_GRAYSCALE)
imgy = cv2.imread(os.path.join(image_dir, vid, vid+'-'+str(i).zfill(6)+'y.jpg'), cv2.IMREAD_GRAYSCALE)
w,h = imgx.shape
if w < 224 or h < 224:
d = 224.-min(w,h)
sc = 1+d/min(w,h)
imgx = cv2.resize(imgx,dsize=(0,0),fx=sc,fy=sc)
imgy = cv2.resize(imgy,dsize=(0,0),fx=sc,fy=sc)
imgx = (imgx/255.)*2 - 1
imgy = (imgy/255.)*2 - 1
img = np.asarray([imgx, imgy]).transpose([1,2,0])
frames.append(img)
return np.asarray(frames, dtype=np.float32)
示例7: test_solution_close_to_original_implementation
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_GRAYSCALE [as 別名]
def test_solution_close_to_original_implementation(self):
image = cv2.imread('testdata/source.png', cv2.IMREAD_COLOR) / 255.0
scribles = cv2.imread('testdata/scribbles.png', cv2.IMREAD_COLOR) / 255.0
alpha = closed_form_matting.closed_form_matting_with_scribbles(image, scribles)
foreground, background = solve_foreground_background(image, alpha)
matlab_alpha = cv2.imread('testdata/matlab_alpha.png', cv2.IMREAD_GRAYSCALE) / 255.0
matlab_foreground = cv2.imread('testdata/matlab_foreground.png', cv2.IMREAD_COLOR) / 255.0
matlab_background = cv2.imread('testdata/matlab_background.png', cv2.IMREAD_COLOR) / 255.0
sad_alpha = np.mean(np.abs(alpha - matlab_alpha))
sad_foreground = np.mean(np.abs(foreground - matlab_foreground))
sad_background = np.mean(np.abs(background - matlab_background))
self.assertLess(sad_alpha, 1e-2)
self.assertLess(sad_foreground, 1e-2)
self.assertLess(sad_background, 1e-2)
示例8: describeAllJpegsInPath
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_GRAYSCALE [as 別名]
def describeAllJpegsInPath(self, path, batch_size, verbose=False):
''' returns a list of descriptors '''
jpeg_paths = sorted(glob.glob(os.path.join(path, '*.jpg')))
descs = []
for batch_offset in range(0, len(jpeg_paths), batch_size):
images = []
for i in range(batch_offset, batch_offset + batch_size):
if i == len(jpeg_paths):
break
if verbose:
print('%d/%d' % (i, len(jpeg_paths)))
if self.is_grayscale:
image = cv2.imread(jpeg_paths[i], cv2.IMREAD_GRAYSCALE)
images.append(np.expand_dims(
np.expand_dims(image, axis=0), axis=-1))
else:
image = cv2.imread(jpeg_paths[i])
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
images.append(np.expand_dims(image, axis=0))
batch = np.concatenate(images, 0)
descs = descs + list(self.sess.run(
self.net_out, feed_dict={self.tf_batch: batch}))
return descs
示例9: imread_uint
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_GRAYSCALE [as 別名]
def imread_uint(path, n_channels=3):
# input: path
# output: HxWx3(RGB or GGG), or HxWx1 (G)
if n_channels == 1:
img = cv2.imread(path, 0) # cv2.IMREAD_GRAYSCALE
img = np.expand_dims(img, axis=2) # HxWx1
elif n_channels == 3:
img = cv2.imread(path, cv2.IMREAD_UNCHANGED) # BGR or G
if img.ndim == 2:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) # GGG
else:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # RGB
return img
# --------------------------------------------
# matlab's imwrite
# --------------------------------------------
示例10: pred_val_fold
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_GRAYSCALE [as 別名]
def pred_val_fold(model_path, fold):
predictor = Predictor(model_path)
folds_df = pd.read_csv(TRAIN_FOLDS_PATH)
fold_df = folds_df[folds_df.fold == fold]
fold_prediction_dir = join(PREDICTION_DIR, f'fold_{fold}', 'val')
make_dir(fold_prediction_dir)
prob_dict = {'id': [], 'prob': []}
for i, row in fold_df.iterrows():
image = cv2.imread(row.image_path, cv2.IMREAD_GRAYSCALE)
segm, prob = predictor(image)
segm_save_path = join(fold_prediction_dir, row.id + '.png')
cv2.imwrite(segm_save_path, segm)
prob_dict['id'].append(row.id)
prob_dict['prob'].append(prob)
prob_df = pd.DataFrame(prob_dict)
prob_df.to_csv(join(fold_prediction_dir, 'probs.csv'), index=False)
示例11: pred_test_fold
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_GRAYSCALE [as 別名]
def pred_test_fold(model_path, fold):
predictor = Predictor(model_path)
prob_df = pd.read_csv(config.SAMPLE_SUBM_PATH)
prob_df.rename(columns={'rle_mask': 'prob'}, inplace=True)
fold_prediction_dir = join(PREDICTION_DIR, f'fold_{fold}', 'test')
make_dir(fold_prediction_dir)
for i, row in prob_df.iterrows():
image_path = join(config.TEST_DIR, 'images'+IMAGES_NAME, row.id + '.png')
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
segm, prob = predictor(image)
row.prob = prob
segm_save_path = join(fold_prediction_dir, row.id + '.png')
cv2.imwrite(segm_save_path, segm)
prob_df.to_csv(join(fold_prediction_dir, 'probs.csv'), index=False)
示例12: get_samples
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_GRAYSCALE [as 別名]
def get_samples(train_folds_path, folds):
images_lst = []
target_lst = []
depth_lst = []
train_folds_df = pd.read_csv(train_folds_path)
for i, row in train_folds_df.iterrows():
if row.fold not in folds:
continue
image = cv2.imread(row.image_path, cv2.IMREAD_GRAYSCALE)
if image is None:
raise FileNotFoundError(f"Image not found {row.image_path}")
mask = cv2.imread(row.mask_path, cv2.IMREAD_GRAYSCALE)
if mask is None:
raise FileNotFoundError(f"Mask not found {row.mask_path}")
images_lst.append(image)
target_lst.append(mask)
depth_lst.append(row.z)
return images_lst, target_lst, depth_lst
示例13: load_test_image
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_GRAYSCALE [as 別名]
def load_test_image(image_path, img_width, img_height, img_channel):
if img_channel == 1 :
img = cv2.imread(image_path, flags=cv2.IMREAD_GRAYSCALE)
else :
img = cv2.imread(image_path, flags=cv2.IMREAD_COLOR)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.resize(img, dsize=(img_width, img_height))
if img_channel == 1 :
img = np.expand_dims(img, axis=0)
img = np.expand_dims(img, axis=-1)
else :
img = np.expand_dims(img, axis=0)
img = img/127.5 - 1
return img
示例14: main
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_GRAYSCALE [as 別名]
def main():
input_dim = (None, None, num_of_dim)
#DeblurNet = ShortCutNet().DeblurResidualNet(input_dim, 6)
DeblurNet = ShortCutNet().DeblurSHCNet(input_dim, 15)
DeblurNet.summary()
input_blur = Input(shape=(input_dim))
out_deblur = DeblurNet(input_blur)
# Model
model = Model(inputs = input_blur, outputs = out_deblur)
model.summary()
model.load_weights(path_weights, by_name=True)
# test
x = cv2.imread(path_test + name_read, cv2.IMREAD_GRAYSCALE) # Read as gray image
x = x.reshape(x.shape[0], x.shape[1], num_of_dim) / 255.0
pred = model.predict(np.expand_dims(x, axis=0))
pred = pred.reshape(x.shape[0] - kernel_crop, x.shape[1] - kernel_crop, num_of_dim)
cv2.imwrite(path_test + name_save, pred * 255.0)
示例15: _GenerateBatch
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import IMREAD_GRAYSCALE [as 別名]
def _GenerateBatch(self, tmp, path_sharp, path_blur):
'''Generates data of batch_size samples
'''
# Initialization
x_blur = np.zeros([self.batch_size, self.img_rows, self.img_cols, self.num_of_dim], dtype = np.float64)
y_sharp = np.zeros([self.batch_size, self.label_rows, self.label_cols, self.num_of_dim], dtype = np.float64)
y_fake = np.zeros([self.batch_size], dtype = int)
# Generate data
for count_i, name_i in enumerate(tmp):
# Read blurry input images
x = cv2.imread(path_blur + name_i, cv2.IMREAD_GRAYSCALE)
x = x.reshape(self.img_rows, self.img_cols, self.num_of_dim)
x_blur[count_i, :] = x/255.0
# Read sharp labels
x = cv2.imread(path_sharp + name_i, cv2.IMREAD_GRAYSCALE)
x = x.reshape(self.img_rows, self.img_cols, self.num_of_dim)
x = x[self.kernel_crop:(self.img_rows - self.kernel_crop), \
self.kernel_crop:(self.img_cols - self.kernel_crop)]
y_sharp[count_i, :] = x/255.0
return [x_blur, y_sharp], y_fake