使用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 (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...