一张一张打开图像,绘制矩形,然后保存在另一个文件夹中

时间:2019-06-24 21:24:35

标签: python opencv

我想打开一个包含多个图像的文件夹,在每个图像中将绘制一个矩形并以相同的原始名称保存,但保存在另一个文件夹中

问题在于图像已创建但被覆盖,我无法自动使用相同名称保存。我想我不能很好地定义for循环。

import cv2
import glob
path = r'dir\*.tif'  # only .tif images
for file in glob.glob(path):
    im = pl_image(file, size= x)
    cv2.rectangle(im,(x1,y1),(x2,y2),(0, 255, 0),2)
    cv2.rectangle(im,(x3,y1),(x4,y2),(0, 255, 0),2)
    cv2.rectangle(im,(x5,y1),(x6,y2),(0, 255, 0),2)
    cv2.rectangle(im,(x7,y1),(x8,y2),(0, 255, 0),2)
    cv2.rectangle(im,(x9,y1),(x10,y2),(0, 255, 0),2)
    cv2.imwrite('%s/%s.JPEG' %  , im) # this line I do not how to define, should be smt like this

此行有效,但不会以原始名称保存

cv2.imwrite(r'other_dir\img.png',im)

1 个答案:

答案 0 :(得分:0)

import cv2
import glob
path = r'dir\*.tif'  # only .tif images
output_folder_path = "/home/output/"
for file in glob.glob(path):
    im = pl_image(file, size= x)
    output_file_name = output_folder_path+file.split("/")[-1]
    cv2.rectangle(im,(x1,y1),(x2,y2),(0, 255, 0),2)
    cv2.rectangle(im,(x3,y1),(x4,y2),(0, 255, 0),2)
    cv2.rectangle(im,(x5,y1),(x6,y2),(0, 255, 0),2)
    cv2.rectangle(im,(x7,y1),(x8,y2),(0, 255, 0),2)
    cv2.rectangle(im,(x9,y1),(x10,y2),(0, 255, 0),2)
    cv2.imwrite(output_file_name, im)

想法是要使用一个变量来存储输出文件夹的标准文件名+现有文件名

相关问题