我有一个尺寸列表,例如(120x600& 160x600& 300x250& 300x600& 728x90),并且IM试图检查文件夹中的图像是否具有正确的尺寸。
我尝试了下面的代码,但是我找不到如何设置具有我上面提到的尺寸的列表。
import os
from PIL import Image
folder_images = "c:/photos"
size_images = {} # Use curly braces instead for they're faster
comp_img = [(120,600) ,(160,600) ,(300,250) ,(300,600), (728,90)]
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:
img_dim = img.size
if img_dim in comp_img:
size_images[path_image] = {'Img width': img_dim[0], 'Img heigth': img_dim[1]}
if (img_dim[0], img_dim[1]) in comp_img:
print(size_images)
print("correct")
else:
print("wrong")
尝试以下:
import os
from PIL import Image
folder_images = "c:/photos"
size_images = {} # Use curly braces instead for they're faster
comp_img = [(120,600) ,(160,600) ,(300,250) ,(300,600), (728,90)]
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:
img_dim = img.size
if img_dim in comp_img:
size_images[path_image] = {'Img width': img_dim[0], 'Img heigth': img_dim[1]}
将所有可能的"正确"维度放在列表中。检查尺寸元组是否在预定义的列表中,如果存在,则将图像文件路径保存为键,作为键,其宽度和高度在另一个值为值中。
它应该给出以下输出: size_images = {'path/to/img': {'Img width': 120, 'Img heigth': 600}}
您可以简单地列出一组正确的维度:
correct_dimension = [(120,600), (160,600), (300,250), (300,600), (728,90)]
,然后查看图像维度是否在此列表中:
if (width,height) in correct_dimension:
print("correct")
else:
print("wrong")