当前位置: 代码网 > it编程>前端脚本>Python > Python如何实现两张图片对比得出相似度

Python如何实现两张图片对比得出相似度

2026年01月21日 Python 我要评论
python两张图片对比得出相似度import numpyimport cv2from pil import imagedef calculate(image1, image2): image1

python两张图片对比得出相似度

import numpy
import cv2
from pil import image


def calculate(image1, image2):
    image1 = cv2.cvtcolor(numpy.asarray(image1), cv2.color_rgb2bgr)
    image2 = cv2.cvtcolor(numpy.asarray(image2), cv2.color_rgb2bgr)
    hist1 = cv2.calchist([image1], [0], none, [256], [0.0, 255.0])
    hist2 = cv2.calchist([image2], [0], none, [256], [0.0, 255.0])
    # 计算直方图的重合度
    degree = 0
    for i in range(len(hist1)):
        if hist1[i] != hist2[i]:
            degree = degree + (1 - abs(hist1[i] - hist2[i]) / max(hist1[i], hist2[i]))
        else:
            degree = degree + 1
    degree = degree / len(hist1)
    return degree


def classify_hist_with_split(image1, image2, size=(256, 256)):
    image1 = image.open(image1)
    image2 = image.open(image2)
    # 将图像resize后,分离为rgb三个通道,再计算每个通道的相似值
    image1 = cv2.cvtcolor(numpy.asarray(image1), cv2.color_rgb2bgr)
    image2 = cv2.cvtcolor(numpy.asarray(image2), cv2.color_rgb2bgr)
    image1 = cv2.resize(image1, size)
    image2 = cv2.resize(image2, size)
    sub_image1 = cv2.split(image1)
    sub_image2 = cv2.split(image2)
    sub_data = 0
    for im1, im2 in zip(sub_image1, sub_image2):
        sub_data += calculate(im1, im2)
    sub_data = sub_data / 3
    return sub_data


if __name__ == '__main__':
    img1_path = r"e:\report\camera_pictures\\2.png"
    img2_path = r"e:\report\camera_pictures\\3.png"
    result1 = classify_hist_with_split(img1_path, img2_path)
    print("相似度为:" + "%.2f%%" % (result1 * 100))

运行结果

d:\python3.8.6\python.exe d:/pythonworkspace/chenbang/test_4.py
相似度为:87.70%

process finished with exit code 0

注意事项

在自动化测试对比图片时,实际场景可能受时间、设备、摄像头影响,可能不准确。

解决方法是循环对比5次,有一次大于80%就break退出循环,每一次对比睡眠1s,如果5次都对比失败了,则图片对比fail

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com