【Python】OpenCV-图片差异检测与标注
import cv2
import numpy as np
def detect_difference(image1_path, image2_path, output_path):
# 读取图片
image1 = cv2.imread(image1_path, cv2.IMREAD_GRAYSCALE)
image2 = cv2.imread(image2_path, cv2.IMREAD_GRAYSCALE)
# 计算两图片之间的差异
difference = cv2.absdiff(image1, image2)
# 二值化处理,将差异图转换为二值图
_, difference_thresh = cv2.threshold(difference, 127, 255, cv2.THRESH_BINARY)
# 寻找差异区域的轮廓
contours, _ = cv2.findContours(difference_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 标注差异
marked_image = cv2.imread(image1_path)
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(marked_image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 保存标注后的图片
cv2.imwrite(output_path, marked_image)
# 使用示例
detect_difference('image1.jpg', 'image2.jpg', 'difference.jpg')
这段代码首先定义了一个函数detect_difference
,它接受两个图片路径和输出路径作为参数。然后读取这两个图片,计算它们之间的差异,并将差异图转换为二值图。接着它寻找二值图中的轮廓,并在原始图片上标注出差异区域,最后将标注后的图片保存到指定路径。
评论已关闭