图形识别并对比元素变化的能力还挺强的 opencv-python库-学到什么贡献什么!!

import cv2
import numpy as np

def compare_images(img1_path, img2_path):
    # 读取两张图片(灰度图)
    img1 = cv2.imread(img1_path, cv2.IMREAD_GRAYSCALE)
    img2 = cv2.imread(img2_path, cv2.IMREAD_GRAYSCALE)

    # 确保两张图片尺寸一致
    if img1.shape != img2.shape:
        raise ValueError("两张图片尺寸不一致,无法比较")

    # 计算图像差值
    diff = cv2.absdiff(img1, img2)

    # 设定阈值,提取差异区域
    _, thresh = cv2.threshold(diff, 30, 255, cv2.THRESH_BINARY)

    # 寻找轮廓
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 在原图上绘制差异区域
    img1_color = cv2.cvtColor(img1, cv2.COLOR_GRAY2BGR)
    for contour in contours:
        (x, y, w, h) = cv2.boundingRect(contour)
        cv2.rectangle(img1_color, (x, y), (x + w, y + h), (0, 0, 255), 2)

    # 显示结果
    combined = np.hstack((img1, diff, thresh))
    combined_color = np.hstack((img1_color, cv2.cvtColor(thresh, cv2.COLOR_GRAY2BGR)))

    cv2.imshow('Difference Detection', combined_color)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    # 保存结果(可选)
    cv2.imwrite('difference_result.png', combined_color)

# 使用示例
compare_images('3m.png', '4m.png')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值