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')