检查某些文件夹中是否有重复图像的最有效(优于我的方法)?

时间:2018-11-29 12:37:33

标签: python python-3.x image numpy

我不确定我是否做得正确。 我已经创建了多个文件的“复制”副本,所有文件都应在某种程度上有所不同(图像增强)。 现在,因为也许是不利于我的事情,所以我想检查是否已创建的文件与其他已创建的文件相等。要么是我的麻烦,要么是我弄糟了代码。因为有很多文件,所以我无法手动检查它们。也许会有比2更快的循环方式。

我有以下代码。

import sys
import os
import glob
import numpy
import time
import datetime


start_time = time.time()
print(datetime.datetime.now().time())

img_dir = sys.argv[1] 
data_path = os.path.join(img_dir,'*g')
files = glob.glob(data_path)
something_went_wrong = False

for f1 in files:
    for f2 in files:
        if f1 != f2:
            if open(f1,"rb").read() == open(f2,"rb").read():
                something_went_wrong = True
                print(f1)
                print(f2)
                print("---")

print(something_went_wrong)
print("--- %s seconds ---" % (time.time() - start_time))

3 个答案:

答案 0 :(得分:1)

只需尝试按照建议使用哈希即可。如果一个像素改变了,哈希值也会改变。

import hashlib
def hash_file(filename):
   # use sha1 or sha256 or other hashing algorithm
   h = hashlib.sha1()

   # open file and read it in chunked
   with open(filename,'rb') as file:
       chunk = 0
       while chunk != b'':
           chunk = file.read(1024)
           h.update(chunk)

   # return string
   return h.hexdigest()

https://www.pythoncentral.io/hashing-files-with-python/

它不受文件名或元数据的影响!将结果放在一个数据框中,这比获得重复数据更容易

答案 1 :(得分:1)

此方法结合使用哈希函数和文件列表的字典,并结合每个列表出现次数的计数-与其他方法相比略有扩展。

大概是在讨论不同文件夹中的重复文件名,这意味着我将以略有不同的方式将首字母file_list放在一起,但这是我解决此问题的基础(取决于glob.glob返回的内容)

import hashlib


file_list = []

def test_hash(filename_to_test1, filename_to_test2):
    """
    """
    filename_seq = filename_to_test1, filename_to_test2
    output = []
    for fname in filename_seq:
        with open(fname, "rb") as opened_file:
            file_data = opened_file.readlines()
            file_data_as_string = b"".join(file_data)
            _hash = hashlib.sha256()
            _hash.update(file_data_as_string)
            output.append(_hash.hexdigest())
    if output[0] == output[1]:
        print "File match"
    else:
        print "Mismatch between file and reference value"

possible_duplicates = {}
for idx, fname in enumerate(file_list):
    if fname in possible_duplicates:
        possible_duplicates[fname].append(idx)
    elif fname not in possible_duplicates:
        possible_duplicates[fname] = [idx]

for fname in possible_duplicates:
    if len(possible_duplicates[fname]) > 1:
        for idx, list_item in enumerate(possible_duplicates[fname]):
            test_hash(possible_duplicates[fname][0], possible_duplicates[fname][idx])

答案 2 :(得分:1)

如评论中所述,按大小分组可以节省时间:

import os
from collections import defaultdict
def fin_dup(dir):
    files=defaultdict(set)
    res=[]
    for fn in os.listdir(dir):
        if os.path.isfile(fn):
            files[os.stat(fn).st_size].add(fn) # groups files by size

    for size,s in sorted(files.items(),key=lambda x : x[0],reverse=True): #big first 
        while s:
            fn0=s.pop()
            s0={fn0}
            for fn in s:
                if open(fn0,'rb').read() == open(fn,'rb').read(): s0.add(fn)
            s -= s0
            if len(s0) > 1: res.append(s0)
    return res

此功能只需不到1秒的时间即可扫描包含1000个文件的目录并查找79个重复项。散列文件仅需10秒。