要编写一个Python程序来判断两张图片的不同之处,并在一个新窗口中显示出来,可以使用OpenCV库来实现。下面是一个示例代码:

import cv2
import numpy as np
from tkinter import Tk, Label, Image, PhotoImage

def find_image_difference(image1, image2):
    # 加载图片
    img1 = cv2.imread(image1)
    img2 = cv2.imread(image2)

    # 确保两张图片具有相同的尺寸
    if img1.shape != img2.shape:
        print('Error: Images must have the same dimensions.')
        return

    # 计算两张图片的差异
    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:
        (x, y, w, h) = cv2.boundingRect(contour)
        cv2.rectangle(img1, (x, y), (x + w, y + h), (0, 255, 0), 2)

    # 创建一个新窗口并显示结果
    window = Tk()
    window.title('Image Difference')
    window.geometry('800x600')

    image = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
    image = Image.fromarray(image)
    photo = PhotoImage(image)

    label = Label(window, image=photo)
    label.pack()

    window.mainloop()

# 测试代码
image1 = 'image1.jpg'
image2 = 'image2.jpg'
find_image_difference(image1, image2)

在上述代码中,find_image_difference()函数用于找到两张图片的不同之处,然后创建一个新的Tkinter窗口来显示结果。要运行代码,请确保安装了OpenCV和tkinter库,并将两张要比较的图片路径作为参数传递给find_image_difference()函数。


原文地址: https://www.cveoy.top/t/topic/pFVe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录