Python图像哈希

2024-09-26 18:16:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正试图从python中的图像中获取哈希值,我已经成功地做到了这一点,并且它在某种程度上起作用

但是,我有一个问题: Image1和image2最终拥有相同的散列,即使它们不同。我需要一种更精确的散列格式

图像1=Image1

图像2=Image2

图像的哈希为:faf076149381

我目前正在使用from PIL import Imageimport 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()

Tags: from图像imageimportpiloscheckhash
2条回答

默认情况下,^{}检查图像文件是否几乎相同。您正在比较的文件比未比较的文件更相似。如果您想要对文件进行或多或少独特的指纹识别,可以使用不同的方法,例如采用加密哈希算法:

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

尝试使用hashlib。只需打开文件并执行哈希

import hashlib

with open("image.extension", "r") as f:
    hash = hashlib.sha256(f.read()).hexdigest()

相关问题 更多 >

    热门问题