gpt4 book ai didi

python - 检查某些文件夹中是否有任何图像重复的最高效(比我的更好)的方法?

转载 作者:行者123 更新时间:2023-11-30 22:03:31 25 4
gpt4 key购买 nike

我不确定我这样做是否正确。我已经创建了多个文件的多个“副本”,所有这些文件都应该在某种程度上有所不同(图像增强)。现在,因为可能情况对我不利,所以我想检查任何创建的文件是否与任何其他创建的文件相同。要么我的机会很大,要么我把代码搞砸了。由于文件太多,我无法手动检查它们。也许有比 2 个 for 循环更快的方法。

我有以下代码。

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))

最佳答案

尝试按照建议使用哈希。如果一个像素发生变化,哈希值也会发生变化。

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/

它不受文件名或元数据的影响!将结果放入数据框中,这样很容易获得重复项

关于python - 检查某些文件夹中是否有任何图像重复的最高效(比我的更好)的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53539253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com