0

我正在尝试将高分辨率图像裁剪为更易于管理的东西。我正在尝试读取目录而不是单个图像,并将新裁剪的图像保存在另一个目录中。我想将所有输出图像都设为 .png,就像我在代码中所做的那样。

import cv2

path = './imgs2/P5.png'
img= cv2.imread (path)
imgcropped = img [1:400, 1:400]
cv2.imwrite ('./imgs/P5-cropped', imgcropped)

对此问题的任何帮助表示赞赏。

4

1 回答 1

1

这是我在这种情况下使用的:

import os
import cv2

path = 'path/to/image/dir/'
dest_path = 'path/to/destination/'

for f in os.listdir(path):
    image = cv2.imread(os.path.join(path, f))
    imgcropped = img [1:400, 1:400]
    cv2.imwrite(os.path.join(dest_path, f), imgcropped)

假如说:

  • 中的图像path已经是.png
  • path仅包含您要转换的图像

os.listdir将为您提供原始目录中文件的名称(包括扩展名),您可以使用它imwrite以相同的文件名将图像保存在目标目录中。

于 2021-08-05T10:10:52.990 回答