+
95
-

python如何对比两张图片找不同?

python如何对比两张图片找不同?

网友回复

+
15
-

在Python中,可以使用多种方法来对比两张图片并找出不同之处。以下是几种常见的方法:

方法一:使用OpenCV

OpenCV是一个强大的计算机视觉库,可以用来处理图像。以下是一个使用OpenCV的示例代码:

import cv2
import numpy as np

def compare_images(img1_path, img2_path, output_path):
    # 读取图像
    img1 = cv2.imread(img1_path)
    img2 = cv2.imread(img2_path)

    # 确保两张图片大小相同
    if img1.shape != img2.shape:
        raise ValueError("两张图片大小不同")

    # 计算两张图片的差异
    diff = cv2.absdiff(img1, img2)

    # 将差异转换为灰度图像
    gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)

    # 应用阈值以突出差异
    _, thresh = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY)

    # 找到差异的轮廓
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 在原图上绘制轮廓
    for contour in contours:
        if cv2.contourArea(contour) > 100:  # 过滤掉小的差异
            x, y, w, h = cv2.boundingRect(contour)
            cv2.rectangle(img1, (x, y), (x + w, y + h), (0, 255, 0), 2)

    # 保存结果图像
    cv2.imwrite...

点击查看剩余70%

我知道答案,我要回答