test.py 1.34 KB
import cv2


def calculate_hash(image):
    # 缩放图像为8x8像素
    resized = cv2.resize(image, (8, 8), interpolation=cv2.INTER_AREA)
    # 转换为灰度图像
    gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
    # 计算像素平均值
    avg = gray.mean()
    # 将像素与平均值进行比较,生成哈希值
    hash_val = 0
    for row in range(8):
        for col in range(8):
            if gray[row, col] > avg:
                hash_val |= 1 << (8 * row + col)
    return hash_val


def image_similarity(image1, image2):
    hash1 = calculate_hash(image1)
    hash2 = calculate_hash(image2)
    # 计算汉明距离,表示哈希值的差异程度
    hamming_distance = bin(hash1 ^ hash2).count("1")
    # 设置阈值,判断是否重复
    threshold = 10
    if hamming_distance <= threshold:
        return True
    else:
        return False


# 读取两张照片
# image1 = cv2.imread("./3140454f6ae50c86bb7c99c15620623.jpg")
# image2 = cv2.imread("./34a66467deca292c93bfed5d13c2706.jpg")
# image2 = cv2.imread("./f37fb654ce205faaa796d093c44cc28.jpg")

image1 = cv2.imread("./892fad7728dc8b8e7e9ec532cf7771e.png")
image2 = cv2.imread("./892fad7728dc8b8e7e9ec532cf7771e.png")

# 比较照片相似度
is_duplicate = image_similarity(image1, image2)
if is_duplicate:
    print("两张照片重复")
else:
    print("两张照片不重复")