Python图像哈希化

8

我目前正在尝试在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()

1
编辑问题以包含代码,而不是代码链接。 - Paul H
好的,抱歉我现在会做这个。 - Logan
你的图像几乎完全相同,并且你正在使用平均哈希算法,对于非常相似的图像将返回相同的结果。你确定你的图像不是太相似了吗?另一个哈希算法是否返回不同的结果? - Random Davis
是的,这就是我所假设的,我来这里是为了确认,并可能获取一些更具体/精确的哈希技术。 - Logan
@Javadeveloper103,你尝试过该库提供的其他哈希类型吗?你需要我们的什么具体帮助?你是否需要这个哈希算法用于特定的应用程序?是否有需要图像哈希以特定格式存在的应用程序或类似的需求?普通的文件哈希算法是否可行? - Random Davis
我已经研究了这个库提供的其他哈希技术,但它们似乎不是我所需要的。我的目标是检查网络迷因,如果它们是相同的图像,则将其从我的文件中删除,因为网络迷因通常使用相同的图像并更改文本,我需要一些非常特定/精确的东西。 - Logan
2个回答

7

尝试使用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://dev59.com/uGEh5IYBdhLWcg3wwlu8

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

3
这样行不通,你需要使用 open("image.extension", "rb") - Antonín Hoskovec

2
默认情况下,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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接