本文整理汇总了Python中cv2.cv2.imread方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.imread方法的具体用法?Python cv2.imread怎么用?Python cv2.imread使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cv2.cv2
的用法示例。
在下文中一共展示了cv2.imread方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: inverse_perspective_map_fvfiles
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imread [as 别名]
def inverse_perspective_map_fvfiles(self, fv_image_src, top_image_path):
"""
Inverse front view images to top view images
:param fv_image_src: source front view images
:param top_image_path: path to store inverse perspective mapped top view images
:return:
"""
if not os.path.isdir(fv_image_src):
raise ValueError('Folder {:s} doesn\'t exist'.format(fv_image_src))
if not os.path.exists(top_image_path):
os.makedirs(top_image_path)
for parents, _, filenames in os.walk(fv_image_src):
for index, filename in enumerate(filenames):
fv_img_id = os.path.join(parents, filename)
fv_img = cv2.imread(fv_img_id, cv2.IMREAD_UNCHANGED)
top_image = self.inverse_perspective_map(image=fv_img)
top_image_save_path = os.path.join(top_image_path, filename.replace('fv', 'top'))
cv2.imwrite(top_image_save_path, top_image)
sys.stdout.write('\r>>Map {:d}/{:d} {:s}'.format(index+1, len(filenames),
os.path.split(top_image_save_path)[1]))
sys.stdout.flush()
sys.stdout.write('\n')
sys.stdout.flush()
return
示例2: __init__
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imread [as 别名]
def __init__(self, path, viewer=None, green_screen=False, factor=0.84):
self.path = path
self.img = cv2.imread(self.path, cv2.IMREAD_COLOR)
if green_screen:
self.img = cv2.medianBlur(self.img, 5)
divFactor = 1 / (self.img.shape[1] / 640)
print(self.img.shape)
print('Resizing with factor', divFactor)
self.img = cv2.resize(self.img, (0, 0), fx=divFactor, fy=divFactor)
cv2.imwrite("/tmp/resized.png", self.img)
remove_background("/tmp/resized.png", factor=factor)
self.img_bw = cv2.imread("/tmp/green_background_removed.png", cv2.IMREAD_GRAYSCALE)
# rescale self.img and self.img_bw to 640
else:
self.img_bw = cv2.imread(self.path, cv2.IMREAD_GRAYSCALE)
self.viewer = viewer
self.green_ = green_screen
self.kernel_ = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
示例3: next_batch
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imread [as 别名]
def next_batch(self, batch_size):
"""
:param batch_size:
:return:
"""
assert self._label_gt_pts.shape[0] == self._label_image_path.shape[0]
idx_start = batch_size * self._next_batch_loop_count
idx_end = batch_size * self._next_batch_loop_count + batch_size
if idx_end > self._label_image_path.shape[0]:
self._random_dataset()
self._next_batch_loop_count = 0
return self.next_batch(batch_size)
else:
gt_img_list = self._label_image_path[idx_start:idx_end]
gt_pts_list = self._label_gt_pts[idx_start:idx_end]
gt_imgs = []
for gt_img_path in gt_img_list:
img = cv2.imread(gt_img_path, cv2.IMREAD_COLOR)
img = cv2.resize(img, (128, 64), interpolation=cv2.INTER_LINEAR)
gt_imgs.append(img)
self._next_batch_loop_count += 1
return gt_imgs, gt_pts_list
示例4: next_batch
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imread [as 别名]
def next_batch(self, batch_size):
"""
:param batch_size:
:return:
"""
assert len(self._gt_label_list) == len(self._gt_img_list)
idx_start = batch_size * self._next_batch_loop_count
idx_end = batch_size * self._next_batch_loop_count + batch_size
if idx_end > len(self._gt_label_list):
self._random_dataset()
self._next_batch_loop_count = 0
return self.next_batch(batch_size)
else:
gt_img_list = self._gt_img_list[idx_start:idx_end]
gt_label_list = self._gt_label_list[idx_start:idx_end]
gt_imgs = []
gt_labels = []
for gt_img_path in gt_img_list:
gt_imgs.append(cv2.imread(gt_img_path, cv2.IMREAD_COLOR))
for gt_label_path in gt_label_list:
label_img = cv2.imread(gt_label_path, cv2.IMREAD_COLOR)
label_binary = np.zeros([label_img.shape[0], label_img.shape[1]], dtype=np.uint8)
idx = np.where((label_img[:, :, :] == [255, 255, 255]).all(axis=2))
label_binary[idx] = 1
gt_labels.append(label_binary)
self._next_batch_loop_count += 1
return gt_imgs, gt_labels
示例5: ensemble_image
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imread [as 别名]
def ensemble_image(params):
file, dirs, ensembling_dir, strategy = params
images = []
for dir in dirs:
file_path = os.path.join(dir, file)
images.append(cv2.imread(file_path, cv2.IMREAD_COLOR))
images = np.array(images)
if strategy == 'average':
ensembled = average_strategy(images)
elif strategy == 'hard_voting':
ensembled = hard_voting(images)
else:
raise ValueError('Unknown ensembling strategy')
cv2.imwrite(os.path.join(ensembling_dir, file), ensembled)
示例6: select_lane_line_top_samples
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imread [as 别名]
def select_lane_line_top_samples():
"""
Select lane line top samples and restore them into 'top_view_lane_line_for_training' folder
:return:
"""
lane_line_fv_samples_dir = ops.join(DVCNN_TRAIN_DATASET_SRC_DIR, 'front_view_lane_line_for_training')
top_samples_dir = ops.join(DVCNN_TRAIN_DATASET_SRC_DIR, 'top_view') # All the top samples are stored here
lane_line_top_sample_dir = ops.join(DVCNN_TRAIN_DATASET_SRC_DIR, 'top_view_lane_line_for_training')
if not ops.isdir(lane_line_fv_samples_dir):
raise ValueError('{:s} doesn\'t exist'.format(lane_line_fv_samples_dir))
if not ops.isdir(top_samples_dir):
raise ValueError('{:s} doesn\'t exist'.format(top_samples_dir))
for parents, _, filenames in os.walk(lane_line_fv_samples_dir):
for index, filename in enumerate(filenames):
top_file_name = ops.join(top_samples_dir, filename.replace('fv', 'top'))
if not ops.isfile(top_file_name):
raise ValueError('{:s} doesn\'t exist'.format(top_file_name))
fv_file_name = ops.join(parents, filename)
top_image = cv2.imread(top_file_name, cv2.IMREAD_UNCHANGED)
fv_image = cv2.imread(fv_file_name, cv2.IMREAD_UNCHANGED)
if top_image is None or fv_image is None:
raise ValueError('Image pair {:s} {:s} is not valid'.format(fv_file_name, top_file_name))
dst_path = ops.join(lane_line_top_sample_dir, filename.replace('fv', 'top'))
shutil.copyfile(top_file_name, dst_path)
sys.stdout.write('\r>>Selecting top lane line samples {:d}/{:d} {:s}'.format(index+1, len(filenames),
filename.replace('fv', 'top')))
sys.stdout.flush()
sys.stdout.write('\n')
sys.stdout.flush()
return
示例7: select_non_lane_line_samples
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imread [as 别名]
def select_non_lane_line_samples():
"""
Select the non lane line samples. The number of the non lane line samples is the same as lane line samples. The non
lane line samples are randomly selected from non lane line dir so you must be sure that non lane line samples are
larger than lane line samples
:return:
"""
lane_line_sample_names = os.listdir(ops.join(DVCNN_TRAIN_DATASET_SRC_DIR, 'front_view_lane_line_for_training'))
lane_line_sample_nums = len(lane_line_sample_names)
select_index = np.random.permutation(lane_line_sample_nums)
non_lane_line_fv_samples_dir = ops.join(DVCNN_TRAIN_DATASET_SRC_DIR, 'front_view_non_lane_line_for_training')
non_lane_line_top_samples_dir = ops.join(DVCNN_TRAIN_DATASET_SRC_DIR, 'top_view_non_lane_line_for_training')
non_lane_line_fv_samples_tmp_dir = ops.join(DVCNN_TRAIN_DATASET_SRC_DIR, 'tmp')
top_samples_dir = ops.join(DVCNN_TRAIN_DATASET_SRC_DIR, 'top_view') # All the top samples are stored here
for parents, _, filenames in os.walk(non_lane_line_fv_samples_dir):
for index, select_id in enumerate(select_index):
fv_filename = ops.join(parents, filenames[select_id])
top_filename = ops.join(top_samples_dir, filenames[select_id].replace('fv', 'top'))
if not ops.isfile(top_filename):
raise ValueError('{:s} doesn\'t exist'.format(top_filename))
fv_image = cv2.imread(fv_filename, cv2.IMREAD_UNCHANGED)
top_image = cv2.imread(top_filename, cv2.IMREAD_UNCHANGED)
if fv_image is None or top_image is None:
raise ValueError('Image pair {:s} {:s} is not valid'.format(fv_filename, top_filename))
top_dst_path = ops.join(non_lane_line_top_samples_dir, filenames[select_id].replace('fv', 'top'))
fv_dst_path = ops.join(non_lane_line_fv_samples_tmp_dir, filenames[select_id])
shutil.copyfile(src=top_filename, dst=top_dst_path)
shutil.copyfile(src=fv_filename, dst=fv_dst_path)
sys.stdout.write('\r>>Selecting non lane line samples {:d}/{:d} '
'{:s}'.format(index+1, lane_line_sample_nums,
filenames[select_id][0:filenames[select_id].find('.')]))
sys.stdout.flush()
sys.stdout.write('\n')
sys.stdout.flush()
return
示例8: crop_top_images
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imread [as 别名]
def crop_top_images(top_image_dir, crop_image_save_dir):
"""
Crop the transformed top images
:param top_image_dir: the dir of inverse perspective transformed imagse
:param crop_image_save_dir:
:return:
"""
if not os.path.exists(top_image_dir):
raise ValueError('{:s} doesn\'t exist'.format(top_image_dir))
if not os.path.exists(crop_image_save_dir):
os.makedirs(crop_image_save_dir)
for parents, dirnames, filenames in os.walk(top_image_dir):
for index, filename in enumerate(filenames):
top_image_filename = os.path.join(parents, filename)
top_image = cv2.imread(top_image_filename, cv2.IMREAD_UNCHANGED)
top_crop_image = crop_image(src=top_image, start_x=START_X, start_y=START_Y, width=CROP_WIDTH,
height=CROP_HEIGHT)
crop_roi_save_path = os.path.join(crop_image_save_dir, filename)
cv2.imwrite(crop_roi_save_path, top_crop_image)
sys.stdout.write('\r>>Map {:d}/{:d} {:s}'.format(index + 1, len(filenames), filename))
sys.stdout.flush()
sys.stdout.write('\n')
sys.stdout.flush()
return
示例9: next_batch
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imread [as 别名]
def next_batch(self, batch_size):
"""
:param batch_size:
:return:
"""
assert len(self._gt_label_binary_list) == len(self._gt_label_instance_list) \
== len(self._gt_img_list)
idx_start = batch_size * self._next_batch_loop_count
idx_end = batch_size * self._next_batch_loop_count + batch_size
if idx_start == 0 and idx_end > len(self._gt_label_binary_list):
raise ValueError('Batch size不能大于样本的总数量')
if idx_end > len(self._gt_label_binary_list):
self._random_dataset()
self._next_batch_loop_count = 0
return self.next_batch(batch_size)
else:
gt_img_list = self._gt_img_list[idx_start:idx_end]
gt_label_binary_list = self._gt_label_binary_list[idx_start:idx_end]
gt_label_instance_list = self._gt_label_instance_list[idx_start:idx_end]
gt_imgs = []
gt_labels_binary = []
gt_labels_instance = []
for gt_img_path in gt_img_list:
gt_img = cv2.imread(gt_img_path, cv2.IMREAD_COLOR)
gt_img = cv2.resize(gt_img, (CFG.TRAIN.IMG_WIDTH, CFG.TRAIN.IMG_HEIGHT))
gt_imgs.append(gt_img)
for gt_label_path in gt_label_binary_list:
label_img = cv2.imread(gt_label_path, cv2.IMREAD_GRAYSCALE)
label_img = label_img / 255
label_binary = cv2.resize(label_img, (CFG.TRAIN.IMG_WIDTH, CFG.TRAIN.IMG_HEIGHT), interpolation=cv2.INTER_NEAREST)
label_binary = np.expand_dims(label_binary, axis=-1)
gt_labels_binary.append(label_binary)
for gt_label_path in gt_label_instance_list:
label_img = cv2.imread(gt_label_path, cv2.IMREAD_UNCHANGED)
label_img = cv2.resize(label_img, (CFG.TRAIN.IMG_WIDTH, CFG.TRAIN.IMG_HEIGHT), interpolation=cv2.INTER_NEAREST)
gt_labels_instance.append(label_img)
self._next_batch_loop_count += 1
return gt_imgs, gt_labels_binary, gt_labels_instance
示例10: extract_and_save_roi_patch
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imread [as 别名]
def extract_and_save_roi_patch(top_image_dir, fv_image_dir, top_view_roi_save_path, front_view_roi_save_path):
"""
extract roi patch from top view image and save the roi patch and its' corresponding front view roi patch
:param top_image_dir: the path where you store the top view image
:param fv_image_dir: the path where you store the front view image
:param top_view_roi_save_path: the path where you store the top view roi patch
:param front_view_roi_save_path: the path where you store the front view roi patch
:return:
"""
__init_folders(top_image_dir=top_image_dir, fv_image_dir=fv_image_dir,
top_rois_dir=top_view_roi_save_path, fv_rois_dir=front_view_roi_save_path)
extractor = RoiExtractor(_cfg=cfg)
res_info = extractor.extract_all(top_image_dir)
transformer = PerspectiveTransformer(_cfg=cfg)
extract_count = 0
for image_id, info in res_info.items():
# read top view image
top_image_id = image_id
top_image = cv2.imread(os.path.join(top_image_dir, top_image_id), cv2.IMREAD_UNCHANGED)
# read front view image
fv_image_id = image_id.replace('top', 'fv')
fv_image = cv2.imread(os.path.join(fv_image_dir, fv_image_id), cv2.IMREAD_UNCHANGED)
# get roi information from top view image
rrect_list = info['rrect']
for index, rrect in enumerate(rrect_list):
rotbox = np.int0(cv2.boxPoints(rrect))
# get the min rect surrounding the rotate rect
top_minrect = __get_rect(rotbox=rotbox)
# get the top roi
top_roi = top_image[top_minrect[1]:top_minrect[3], top_minrect[0]:top_minrect[2], :]
# top view roi save name constructed as xxxx_top_index_ltx_lty_rbx_rby.jpg to reserve the position
# information in the top view image
top_roi_save_id = '{:s}_{:d}.jpg'.format(top_image_id[:-4], index)
top_roi_save_id = os.path.join(top_view_roi_save_path, top_roi_save_id)
cv2.imwrite(top_roi_save_id, top_roi)
for j in range(4):
# remap the rotate rect position from the cropped top view image to the origin top view image which is
# correspond to the front view image. The cropped top view image is cropped from the origin top view
# image at position [START_X, START_Y] with [CROP_WIDTH, CROP_HEIGHT] width and height
rotbox[j] = np.add(rotbox[j], [__START_X, __START_Y])
# remap the position from top view image to front view image
rotbox[j] = transformer.perspective_point(rotbox[j])
# get the min surrounding rect of the rotate rect
fv_minrect = __get_rect(rotbox)
fv_roi = fv_image[fv_minrect[1]:fv_minrect[3], fv_minrect[0]:fv_minrect[2], :]
# fv roi image id was constructed in the same way as top roi image id
fv_roi_save_id = '{:s}_{:d}.jpg'.format(fv_image_id[:-4], index)
fv_roi_save_id = os.path.join(front_view_roi_save_path, fv_roi_save_id)
cv2.imwrite(fv_roi_save_id, fv_roi)
extract_count += 1
sys.stdout.write('\r>>Extracting rois {:d}/{:d} {:s}'.format(extract_count, len(res_info), image_id))
sys.stdout.flush()
sys.stdout.write('\n')
sys.stdout.flush()
return
示例11: predict
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imread [as 别名]
def predict(args):
gpu_manage(args)
### MODELS LOAD ###
print('===> Loading models')
gen = Generator(gpu_ids=args.gpu_ids)
param = torch.load(args.pretrained)
gen.load_state_dict(param)
if args.cuda:
gen = gen.cuda(0)
print ('<=== Model loaded')
print('===> Loading test image')
img = cv2.imread(args.test_filepath, 1).astype(np.float32)
img = img / 255
img = img.transpose(2, 0, 1)
img = img[None]
print ('<=== test image loaded')
with torch.no_grad():
x = torch.from_numpy(img)
if args.cuda:
x = x.cuda()
print('===> Removing the cloud...')
start_time = time.time()
att, out = gen(x)
print('<=== finish! %.3fs cost.' % (time.time()-start_time))
x_ = x.cpu().numpy()[0]
x_rgb = x_ * 255
x_rgb = x_rgb.transpose(1, 2, 0).astype('uint8')
out_ = out.cpu().numpy()[0]
out_rgb = np.clip(out_[:3], 0, 1) * 255
out_rgb = out_rgb.transpose(1, 2, 0).astype('uint8')
att_ = att.cpu().numpy()[0] * 255
att_heatmap = heatmap(att_.astype('uint8'))[0]
att_heatmap = att_heatmap.transpose(1, 2, 0)
allim = np.hstack((x_rgb, out_rgb, att_heatmap))
show(allim)
# plt.figure()
# plt.subplot(1,3,1), plt.title('cloudy image'), plt.imshow(x_rgb), plt.axis('off')
# plt.subplot(1,3,2), plt.title('cloudless image'), plt.imshow(out_rgb), plt.axis('off')
# plt.subplot(1,3,3), plt.title('attention map'), plt.imshow(att_heatmap), plt.axis('off')
# plt.show()