试着理解一个钥匙

2024-04-24 09:17:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个比较图像文件的代码,以便检查一个目录中的图像是否与另一个目录中的任何图像匹配。我不是比较文件名,而是使用PIL,Python图像库来实际比较图像。在

我的代码返回一个目录名不匹配的列表,这正是我需要的。我有162个图片目录。我的代码成功地检查了71个目录,并按预期返回了所需的输出。然后,从72号目录开始,我得到以下信息:KeyError: 'F:/162 pic sets ready/set72'表示所有剩余的目录。在

这是我不能理解的部分:如果我把这些目录移到另一个位置,我仍然会得到同样的错误,但是如果我把这些目录中的图像复制到另一个空目录中,然后在这些目录上运行代码,我就不会得到错误了。在

from PIL import ImageChops
from PIL import Image
import math, operator
import os

path_images = ('C:/Users/Acer/Desktop/pics/')
list_to_match = []
for images in os.listdir(path_images):
    images_to_match = Image.open(path_images + images)
    list_to_match.append(images_to_match)
path_folders = ('F:/162 pic sets ready/')
d = {}
for dirpath, dirnames, filenames in os.walk(path_folders):
    if 'Thumbs.db' not in filenames:
        d[dirpath] = filenames
dict2 = {k: list(map(lambda x: (k+'/'+x ), v)) for k,v in d.items()}

c = 1
matches = []
folder_images_opened = []
while (c < 163):
    for im in dict2['F:/162 pic sets ready/set%s' % c]:
        test = Image.open(im)
        folder_images_opened.append(test)
    for images_to_find in list_to_match:
        if images_to_find in folder_images_opened:
            matches.append(c)
            print ('Folders where we found a match:', c)
            del folder_images_opened[:]    
    c = c+1
numbers = list(range(1,163))
numbers_filter = [i for i in numbers if i not in matches]
print ('Folders that does not have a match', numbers_filter)

这是完整的回溯:

^{pr2}$

Tags: topath代码in图像import目录for
1条回答
网友
1楼 · 发布于 2024-04-24 09:17:10

你做了两个假设:

  1. 目录F:/162 pic sets ready/set72实际存在,并且
  2. 如果存在,则该目录中没有Thumbs.db文件名。在

如果这两个假设都不成立,那么该路径就不会作为dict2中的键出现。在

您可以先测试密钥是否存在:

while (c < 163):
    dirname = 'F:/162 pic sets ready/set%s' % c
    if dirname not in dict2:
        print('{} does not exist or has a Thumbs.db file'.format(dirname))
        continue
    for im in dict2[dirname]:
        test = Image.open(im)

与其使用while循环并期望所有setx目录按顺序存在,不如遍历dict2的键;甚至可以对键进行排序:

^{pr2}$

我想你只是想跳过Thumbs.db,而不是跳过包含Thumbs.db的目录(一个很大的区别!)。如果是,请在处理文件时测试文件名,而不是在处理目录时:

for im in dict2['F:/162 pic sets ready/set%s' % c]:
    if os.path.basename(im) == 'Thumbs.db':
        continue
    test = Image.open(im)
    folder_images_opened.append(test)

并完全删除if 'Thumbs.db' not in filenames:测试。在

相关问题 更多 >