首页 > 解决方案 > 从不同的文件夹中检索图像

问题描述

我有一个大文件夹,里面有子文件夹,我想从所有这些文件夹中检索图像。我该怎么做?其次,如果我想获得所有这些图像的尺寸,我该怎么做?

我已经用一个文件夹试过了,它工作正常。但我想为多个文件夹做这件事。我从此代码中读取一个文件夹的图像尺寸。

folder_images = "D:/DeepFashion/Category and Attribute Prediction/img/img"
size_images = dict()

for dirpath, _, filenames in os.walk(folder_images):
    for path_image in filenames:
        image = os.path.abspath(os.path.join(dirpath, path_image))
        with Image.open(image) as img:
            width, heigth = img.size
            size_images[path_image] = {'width': width, 'heigth': heigth}

标签: python-3.ximagedimensions

解决方案


这段代码似乎很好——唯一的问题是,如果文件夹结构中的任何文件不是正确的图像文件,您将得到一个未处理的异常并且脚本将停止。

由于您不是以懒惰的方式阅读图像,因此没有理由使用该with命令来获取图像 - 只需将您的代码更改为:

folder_images = "D:/DeepFashion/Category and Attribute Prediction/img/img"
size_images = dict()

for dirpath, _, filenames in os.walk(folder_images):
    for path_image in filenames:
        image = os.path.abspath(os.path.join(dirpath, path_image))
        try:
           img = Image.open(image)
        except OSError:
           print("Not an image file: ", image)

        width, heigth = img.size
        size_images[path_image] = {'width': width, 'heigth': heigth}

推荐阅读