尝试对 ImageHash 库使用差异哈希时出现 Numpy 错误

Numpy error trying to use difference hashing with the ImageHash library

我正在尝试使用 python ImageHash 库执行差异散列,但一直收到 numpy 错误。

错误:

文件“/Users/testuser/Desktop/test_folder/test_env/lib/python3.8/site-packages/imagehash.py”,第 252 行,dhash 格式 图片 = image.convert("L").resize((hash_size + 1, hash_size), Image.ANTIALIAS) AttributeError: 'numpy.ndarray' 对象没有属性 'convert'

代码:

from PIL import Image
from cv2 import cv2
import imagehash
import numpy as np

def hash_and_compare(image1, image2):
    image1 = image1
    image2 = image2

    # read images
    image1 = cv2.imread(image1)
    image2 = cv2.imread(image2)

    # convert to grayscale
    image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
    image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)

    # resize images
    image1 = cv2.resize(image1, (9, 8))
    image2 = cv2.resize(image2, (9, 8))

    # hash images
    image1_hash = imagehash.dhash(image1)
    image2_hash = imagehash.dhash(image2)

    # compute hamming distance
    distance = image1_hash - image2_hash

    if image1_hash <= 10:
        print(distance)
        print('match')
    else:
        print(distance)
        print('no match')

hash_and_compare('/Users/testuser/Desktop/test_folder/game_name056496.png', '/Users/testuser/Desktop/test_folder/game_name499761.png')

正如 imagehash 库文档中提到的,@image must be a PIL instance.。所以你不能将 numpy 数组设置为 dshash 的输入 function.if 你想用 opencv 做一些预处理,你应该在将它设置为 dhash 之前将它转换成 PIL 数组,像这样:

import numpy as np
from PIL import Image
...
some preprocess
...
# You may need to convert the color.
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
im_pil = Image.fromarray(img)
image1_hash = imagehash.dhash(im_pil)