【问题标题】:Retrieve Images from different folders从不同的文件夹中检索图像
【发布时间】:2019-12-08 00:25:00
【问题描述】:

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

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

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.x image dimensions


    【解决方案1】:

    这段代码似乎没问题——唯一的问题是如果文件夹结构中的任何文件不是正确的图像文件,你会得到一个未处理的异常,脚本会停下来。

    由于您不是以懒惰的方式阅读图像,因此没有理由使用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}
    

    【讨论】:

    • 感谢您的反馈,但 'img' 目录包含 5000 个子文件夹,我必须遍历它才能获取图像。子目录下的所有文件都是图片。
    • 那么,在那里工作的是什么?它应该像 os.walk 一样工作。
    猜你喜欢
    • 2021-11-03
    • 1970-01-01
    • 2017-10-07
    • 2017-05-06
    • 2017-07-18
    • 2015-05-15
    • 1970-01-01
    • 2012-05-22
    相关资源
    最近更新 更多