python-3.x - 从不同的文件夹中检索图像
问题描述
我有一个大文件夹,里面有子文件夹,我想从所有这些文件夹中检索图像。我该怎么做?其次,如果我想获得所有这些图像的尺寸,我该怎么做?
我已经用一个文件夹试过了,它工作正常。但我想为多个文件夹做这件事。我从此代码中读取一个文件夹的图像尺寸。
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}
解决方案
这段代码似乎很好——唯一的问题是,如果文件夹结构中的任何文件不是正确的图像文件,您将得到一个未处理的异常并且脚本将停止。
由于您不是以懒惰的方式阅读图像,因此没有理由使用该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}
推荐阅读
- mysql - 错误 1045 (28000): 用户 'rails_user'@'localhost' 的访问被拒绝(使用密码:是)
- r - R——无法安装“tidyverse”包
- python - 如何在python中正确使用断言?
- go - 即使在初始化之后变量也是 nil
- flutter - Flutter:如何禁用向下拖动以关闭 showModalBottomSheet
- r - JSON import in data.table not working in R (RStudio)
- java - 为什么elasticsearch官网提供的Java Api搜索模板有问题?
- sql-server - 如何找出 CLR 函数的底层内容
- python - 需要从 JSON 响应中提取信息?
- python - 我无法使用 CV 将我的 RGB 颜色更改为 python 中的灰度图像