如何解决使用opencv检测两个图像之间的差异
我有两张图片,我想让它们之间的区别显而易见。我想为两个图像添加颜色,以便用户可以在一两秒钟内清楚地发现所有差异。
例如,这是两张图片,有些不同: green plate with two holes
red plate with two holes having same dimension as 1st one
yellow plate with two holes minimizing its width
我当前使差异显而易见的方法是创建一个蒙版(两个图像之间的差异),将其着色为红色,然后将其添加到图像中。目的是用深蓝色清楚地标记所有差异。这是我当前的代码:
from skimage.measure import compare_ssim
import cv2
import numpy as np
image1 = cv2.imread('Paint1.png')
image2 = cv2.imread('Paint3.png')
resized1 = cv2.resize(image1,(300,200))
resized2 = cv2.resize(image2,200))
# Convert images to grayscale
gray1 = cv2.cvtColor(resized1,cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(resized2,cv2.COLOR_BGR2GRAY)
# Compute SSIM between two images
(score,diff) = compare_ssim(gray2,gray1,full=True)
print("Image similarity",score*100,"%")
# The diff image contains the actual image differences between the two images
# and is represented as a floating point data type in the range [0,1]
# so we must convert the array to 8-bit unsigned integers in the range
# [0,255] before we can use it with OpenCV
diff = (diff * 255).astype("uint8")
if diff.all() == True:
print("Same images")
else:
print("Not same")
# Threshold the difference image,followed by finding contours to
# obtain the regions of the two input images that differ
thresh = cv2.threshold(diff,255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
contours = cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
mask = np.zeros(resized1.shape,dtype='uint8')
filled_after = resized2.copy()
for c in contours:
area = cv2.contourArea(c)
if area > 40:
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(resized1,(x,y),(x + w,y + h),(0,255),2)
cv2.rectangle(resized2,2)
cv2.drawContours(mask,[c],-1)
cv2.drawContours(filled_after,-1)
cv2.imshow('Output',np.hstack([resized1,resized2]))
cv2.imshow('diff',diff)
cv2.imshow('mask',mask)
cv2.imshow('filled after',filled_after)
cv2.waitKey(0)
比较第一张和第二张图像时:- result of 1st and 2nd images
比较第一张和第三张图片时:-result of 1st and 3rd images
当前代码存在的问题:计算出的蒙版也显示相同图像的差异(请参阅第1和第2个结果,尽管同一图像蒙版显示为蓝色)。(此代码可正确使用两个不同的图片,但不是相同的图片)
预期输出: 3张图像:两张输入图像,但差异突出显示(以可配置的颜色清晰突出显示),第三张图像仅包含差异(遮罩,但对于相同的图像则不显示)显示出任何差异)
我该如何实现?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。