如何使用python检查目录中所有图像的尺寸? [英] How to check dimensions of all images in a directory using python?
问题描述
我需要检查目录中图像的尺寸。目前它有〜700张图像。
我只需要检查大小,如果大小与给定的维度不匹配,它将被移动到另一个文件夹。我如何开始
I need to check the dimensions of images in a directory. Currently it has ~700 images. I just need to check the sizes, and if the size does not match a given dimension, it will be moved to a different folder. How do I get started?
推荐答案
您可以使用 Python Imaging Library (又名PIL)来读取图像标题并查询维度。
You can use the Python Imaging Library (aka PIL) to read the image headers and query the dimensions.
一种方法可以是给自己写一个函数,它使用文件名并返回尺寸(使用PIL)。然后使用 os.path.walk
函数遍历目录中的所有文件,应用此函数。收集结果,您可以构建一个映射字典 filename - >维度
,然后使用列表解析(请参阅 itertools
)过滤掉与所需大小不匹配的那些。
One way to approach it would be to write yourself a function that takes a filename and returns the dimensions (using PIL). Then use the os.path.walk
function to traverse all the files in the directory, applying this function. Collecting the results, you can build a dictionary of mappings filename -> dimensions
, then use a list comprehension (see itertools
) to filter out those that do not match the required size.
这篇关于如何使用python检查目录中所有图像的尺寸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!