# demo示例 import cv2
import numpy as np
from PIL import Image
# 计算平均哈希值
def ahash(image):
# 缩放为8*8
image = cv2.resize(image, (8, 8), interpolation=cv2.INTER_CUBIC)
# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 计算像素平均值
avg = gray.mean()
# 二值化
hash = (gray > avg).astype(np.uint8)
# 转换为整数
hash = hash.flatten().tolist()
hash = int(''.join(map(str, hash)), 2)
return hash
# 计算汉明距离
def hamming_distance(hash1, hash2):
return bin(hash1 ^ hash2).count('1')
# 加载图像
img1 = cv2.imread('image1.jpg')
img2 = cv2.imread('image2.jpg')
# 计算哈希值
hash1 = ahash(img1)
hash2 = ahash(img2)
# 计算汉明距离
distance = hamming_distance(hash1, hash2)
# 判断相似度
if distance |