本文整理汇总了Python中cv2.cv2.imwrite方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.imwrite方法的具体用法?Python cv2.imwrite怎么用?Python cv2.imwrite使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cv2.cv2
的用法示例。
在下文中一共展示了cv2.imwrite方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: inverse_perspective_map_fvfiles
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imwrite [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 imwrite [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: save_image_range
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imwrite [as 别名]
def save_image_range(video_str, stage_str, frame_range,
tl, br, step_size, annot_dir, image_dir):
# Get the name (number) of the last file in each directory.
image_count = get_dir_count(image_dir)
annot_count = get_dir_count(annot_dir)
frame_range_diff = (frame_range[1] - frame_range[0])/step_size + 1
print("Saving %d frames of %s" % (frame_range_diff, stage_str))
save_num = 0
capture = cv2.VideoCapture(video_str)
start_time = time.time()
for frame_num in range(frame_range[0], frame_range[1], step_size):
capture.set(cv2.CAP_PROP_POS_FRAMES, frame_num)
_, frame = capture.read()
image_num = image_count + save_num + 1
annot_num = annot_count + save_num + 1
save_num += 1
img_name = "%06d" % image_num
img_location = "%s/%s.png" % (image_dir, img_name)
cv2.imwrite(img_location, frame)
write_xml(frame.shape, image_num, annot_num,
stage_str, tl, br, annot_dir, image_dir)
capture.release()
total_time = time.time() - start_time
print("Total Time: {:.1f}s".format(total_time))
print("Average FPS: {:.1f}".format(frame_range_diff/total_time))
# Get the name (number) of the last file in each save directory. This
# is required to save the annotations and images numerically increasing.
示例4: ensemble_image
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imwrite [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)
示例5: crop_top_images
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imwrite [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
示例6: show_contours
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imwrite [as 别名]
def show_contours(contours, imgRef):
""" Helper used for matplotlib contours display """
whiteImg = np.zeros(imgRef.shape)
cv2.drawContours(whiteImg, contours, -1, (255, 0, 0), 1, maxLevel=1)
show_image(whiteImg)
cv2.imwrite("/tmp/cont.png", whiteImg)
示例7: extract_and_save_roi_patch
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imwrite [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
示例8: export_pieces
# 需要导入模块: from cv2 import cv2 [as 别名]
# 或者: from cv2.cv2 import imwrite [as 别名]
def export_pieces(self, path_contour, path_colored, name_contour=None, name_colored=None, display=True, display_border=False):
"""
Export the contours and the colored image
:param path_contour: Path used to export contours
:param path_colored: Path used to export the colored image
:return: the best edge found in the bloc
"""
minX, minY = float('inf'), float('inf')
maxX, maxY = -float('inf'), -float('inf')
for piece in self.pieces_:
for p in piece.img_piece_:
x, y = p.pos
minX, minY = min(minX, x), min(minY, y)
maxX, maxY = max(maxX, x), max(maxY, y)
colored_img = np.zeros((maxX - minX, maxY - minY, 3))
border_img = np.zeros((maxX - minX, maxY - minY, 3))
for piece in self.pieces_:
for p in piece.img_piece_:
p.apply(colored_img, dx=-minX, dy=-minY)
# Contours
for e in piece.edges_:
for y, x in e.shape:
y, x = y - minY, x - minX
if 0 <= y < border_img.shape[1] and 0 <= x < border_img.shape[0]:
rgb = (0, 0, 0)
if e.type == TypeEdge.HOLE:
rgb = (102, 178, 255)
if e.type == TypeEdge.HEAD:
rgb = (255, 255, 102)
if e.type == TypeEdge.UNDEFINED:
rgb = (255, 0, 0)
if e.connected:
rgb = (0, 255, 0)
border_img[x, y, 0] = rgb[2]
border_img[x, y, 1] = rgb[1]
border_img[x, y, 2] = rgb[0]
cv2.imwrite(path_contour, border_img)
cv2.imwrite(path_colored, colored_img)
if self.viewer and display:
if display_border:
self.viewer.addImage(name_contour, path_contour, display=False)
self.viewer.addImage(name_colored, path_colored)