python实现对比两张图片 判断其是否一致 显示差异地方
时间: 2023-08-08 18:05:48 浏览: 149
在Python中,可以使用OpenCV库来实现对比两张图片,判断其是否一致,并显示差异地方。下面是一个简单的示例代码:
```python
import cv2
# 加载两张图片
img1 = cv2.imread('image1.jpg')
img2 = cv2.imread('image2.jpg')
# 将两张图片转换为灰度图
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# 对两张图片进行特征提取和匹配
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(gray1, None)
kp2, des2 = orb.detectAndCompute(gray2, None)
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)
# 计算相似度得分
score = sum([match.distance for match in matches]) / len(matches)
# 如果得分低于某个阈值,则认为两张图片不一致
if score > 30:
print('The two images are not the same')
else:
print('The two images are the same')
# 使用差异检测算法找出两张图片的差异地方
diff = cv2.absdiff(img1, img2)
gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(img1, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 显示差异地方
cv2.imshow('Difference', img1)
cv2.waitKey(0)
```
需要注意的是,这只是一个简单的示例代码,实际上还有很多细节需要考虑,比如如何选择适当的阈值、如何处理旋转和缩放等变换、如何处理光照变化等等。
阅读全文