如何更改文件夹中的所有图像并将更改后的图像保存到另一个文件夹?

How can I change all the images in a folder and save the changed images to another folder?

我的一个文件夹里有很多图片。我需要以相同的方式处理每个图像并将处理后的图像保存到不同的文件夹中。我想象它是这样的:

for i in range(nuber_of_file):
    current_image = cv2.imread("path to file")
    #  transformation
    cv2.imwrite("new path", new_image)

我每次获取文件夹中的文件数和获取新路径时遇到困难。你能告诉我怎么做吗?

您可以使用 os.listdir(dirString) 列出文件夹中的文件。我给你一个文件名列表,你可以像这样过滤它们:

dl = os.listdir(dirString)

imgList = 列表()

imgList.append([f for f in dl if ".JPEG" in f or ".jpg" in f or ".png" in f])

然后你得到完整的路径并像这样读取图像:

img = cv2.imread(os.path.join(dirString, imgList[0]), cv2.IMREAD_COLOR)

马修

您可以使用:

  • glob: 获取你目录下的所有文件
  • rglob: (recursive glob) 获取你的目录和所有子目录下的所有文件

然后你可以用cv2.imread阅读它们。

这里有一个例子:

from pathlib import Path
import cv2


def main():
    destination_path = '/path/to/destination'
    target_path = '/path/to/target'

    format_of_your_images = 'jpg'

    all_the_files = Path(destination_path).rglob(f'*.{format_of_your_images}')

    for f in all_the_files:
        p = cv2.imread(str(f))
        #  transformation
        cv2.imwrite(f'{target_path}/{f.name}', p)


if __name__ == '__main__':
    main()


希望对您有所帮助