- 读取两张图片并转换为灰度图像:
import cv2
img1 = cv2.imread('image1.jpg')
img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
img2 = cv2.imread('image2.jpg')
img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
- 通过减法计算两张图片的差异:
diff = cv2.absdiff(img1_gray, img2_gray)
- 使用阈值处理来得到二值图像:
threshold = 30
_, thresh = cv2.threshold(diff, threshold, 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, 0, 255), 2)
- 显示结果:
cv2.imshow('result', img1)
cv2.waitKey(0)