Skip to main content
 首页 » 编程设计

python之检查目录中的文件是否相同

2025年05月04日9zhwl

我有一个包含 5000 多张 jpeg/png 等图像的文件夹。如何检查是否有任何图像相同。这些图像是通过网络抓取收集的,并已按顺序重命名,因此我无法比较文件名。

我目前正在检查哈希值是否相同,但这是一个非常漫长的过程。我目前正在使用:

def sameIm(file_name1,file_name2): 
    hash = imagehash.average_hash(Image.open(path + file_name1)) 
    otherhash = imagehash.average_hash(Image.open(path + file_name2)) 
 
    return (hash == otherhash) 

然后嵌套循环。将 1 张图片与 5000 多张其他图片进行比较大约需要 5 分钟,因此将每张图片与每张图片进行比较需要几天的时间来计算。

在 python 中有更快的方法吗?我在考虑并行处理,但这仍然需要很长时间吗?

或者是否有另一种更快的比较文件的方法?

谢谢

请您参考如下方法:

确实有一种更快的方法:

import collections 
import glob 
import os 
 
 
def dupDetector(dirpath, ext): 
    hashes = collections.defaultdict(list) 
    for fpath in glob.glob(os.path.join(dirpath, "*.{}".format(ext))): 
        h = imagehash.average_hash(Image.open(fpath)) 
        hashes[h].append(fpath) 
 
    for h,fpaths in hashes.items(): 
        if len(fpaths) == 1: 
            print(fpaths[0], "is one of a kind") 
            continue 
        print("The following files are duplicates of each other (with the hash {}): \n\t{}".format(h, '\n\t'.join(fpaths))) 

使用以文件哈希为键的字典可以进行 O(1) 次查找,这意味着您无需进行成对比较。因此,您从二次运行时间变为线性运行时间(耶!)