代码:

import os
import filecmp

# 提示词
# 你好,帮我用python写一个方法,我用的是windows系统,方法要求如下:
# 1.对比GXpdfpicturexdifA1.jpg 和G:Npdfpicturexdif2.jpg 两张图片的不同
# 2.在G\pdf\pictur ediff1jpg中标出不同,并另存为G\pdf\picturevdif1_difference.jpg
import cv2
import numpy as np
import os


def compare_images(img1_path, img2_path, output_path):
    """
    比较两张图片的差异并在第一张图片上标记,保存结果

    参数:
        img1_path: 第一张图片路径 (作为基准图)
        img2_path: 第二张图片路径 (作为对比图)
        output_path: 差异标记图的保存路径
    """
    # 读取图片
    img1 = cv2.imread(img1_path)
    img2 = cv2.imread(img2_path)

    if img1 is None or img2 is None:
        raise FileNotFoundError("无法读取图片,请检查路径是否正确")

    # 统一图片尺寸(取较小尺寸)
    height = min(img1.shape[0], img2.shape[0])
    width = min(img1.shape[1], img2.shape[1])
    img1 = cv2.resize(img1, (width, height))
    img2 = cv2.resize(img2, (width, height))

    # 计算差异
    gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
    gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
    diff = cv2.absdiff(gray1, gray2)

    # 二值化处理
    _, thresh = cv2.threshold(diff, 30, 255, cv2.THRESH_BINARY)

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

    # 在原图上标记差异
    result = img1.copy()
    for contour in contours:
        if cv2.contourArea(contour) > 50:  # 过滤小差异
            x, y, w, h = cv2.boundingRect(contour)
            cv2.rectangle(result, (x, y), (x + w, y + h), (0, 0, 255), 2)  # 红色矩形框

    # 确保输出目录存在
    os.makedirs(os.path.dirname(output_path), exist_ok=True)

    # 保存结果
    cv2.imwrite(output_path, result)
    print(f"差异标记图已保存至: {output_path}")


# 使用示例
if __name__ == "__main__":
    img1_path = r"C:\Users\admin\Pictures\diffA.png"  # 注意修正路径分隔符
    img2_path = r"C:\Users\admin\Pictures\diffB.png"
    output_path = r"C:\Users\admin\Pictures\diffAB.png"

    compare_images(img1_path, img2_path, output_path)

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐