首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python图像散列

Python图像散列
EN

Stack Overflow用户
提问于 2020-11-24 20:06:50
回答 2查看 6.9K关注 0票数 4

我目前正在尝试从python中的图像中获取一个散列,我已经成功地完成了这一工作,它在某种程度上起了作用。

然而,我有这样一个问题: Image1和image2最终具有相同的散列,尽管它们不同。我需要一种更精确更精确的散列方式。

Image1 = Image1

Image2 = Image2

图像的哈希是: faf0761493939381

我目前正在使用from PIL import Image import imagehash

imagehash.average_hash

代码在这里

代码语言:javascript
复制
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()
EN

回答 2

Stack Overflow用户

发布于 2020-11-24 20:13:57

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

代码语言:javascript
复制
import hashlib
代码语言:javascript
复制
# Simple solution
with open("image.extension", "rb") as f:
    hash = hashlib.sha256(f.read()).hexdigest()
代码语言:javascript
复制
# 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)!

票数 2
EN

Stack Overflow用户

发布于 2020-11-24 20:36:57

默认情况下,imagehash检查图像文件是否几乎相同。您正在比较的文件是,比它们更相似的。如果您想要一种或多或少独特的指纹文件方式,可以使用一种不同的方法,例如使用加密散列算法:

代码语言:javascript
复制
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()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64994057

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档