我目前正在尝试从python中的图像中获取一个散列,我已经成功地完成了这一工作,它在某种程度上起了作用。
然而,我有这样一个问题: Image1和image2最终具有相同的散列,尽管它们不同。我需要一种更精确更精确的散列方式。
Image1 = Image1
Image2 = Image2
图像的哈希是: faf0761493939381
我目前正在使用from PIL import Image import imagehash
和imagehash.average_hash
代码在这里
import os
from PIL import Image
import imagehash
def checkImage():
for filename in os.listdir('images//'):
hashedImage = imagehash.average_hash(Image.open('images//' + filename))
print(filename, hashedImage)
for filename in os.listdir('checkimage//'):
check_image = imagehash.average_hash(Image.open('checkimage//' + filename))
print(filename, check_image)
if check_image == hashedImage:
print("Same image")
else:
print("Not the same image")
print(hashedImage, check_image)
checkImage()发布于 2020-11-24 20:13:57
尝试使用hashlib。只需打开文件并执行哈希操作。
import hashlib# Simple solution
with open("image.extension", "rb") as f:
hash = hashlib.sha256(f.read()).hexdigest()# General-purpose solution that can process large files
def file_hash(file_path):
# https://stackoverflow.com/questions/22058048/hashing-a-file-in-python
sha256 = hashlib.sha256()
with open(file_path, "rb") as f:
while True:
data = f.read(65536) # arbitrary number to reduce RAM usage
if not data:
break
sha256.update(data)
return sha256.hexdigest()感谢Antonín Hoskovec指出它应该是二进制的(rb),而不是简单的读(r)!
发布于 2020-11-24 20:36:57
默认情况下,imagehash检查图像文件是否几乎相同。您正在比较的文件是,比它们更相似的。如果您想要一种或多或少独特的指纹文件方式,可以使用一种不同的方法,例如使用加密散列算法:
import hashlib
def get_hash(img_path):
# This function will return the `md5` checksum for any input image.
with open(img_path, "rb") as f:
img_hash = hashlib.md5()
while chunk := f.read(8192):
img_hash.update(chunk)
return img_hash.hexdigest()https://stackoverflow.com/questions/64994057
复制相似问题