Python和OpenCV实现图片比对,并标记展示不同

python版本为3.7.7,OpenCV版本为4.2.1,源码如下:

# -*- coding: utf-8 -*-

from skimage.metricsimport structural_similarity

import imutils

import cv2

# 加载两张图片并将他们转换为灰度

imageA = cv2.imread(r"D:\Software\PythonProject\image\11.png")

imageB = cv2.imread(r"D:\Software\PythonProject\image\22.png")

grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)

grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)

# 计算两个灰度图像之间的结构相似度指数

(score,diff) = structural_similarity(grayA,grayB,full =True)

diff = (diff *255).astype("uint8")

print("SSIM:{}".format(score))

#找到不同点的轮廓以致于我们可以在被标识为“不同”的区域周围放置矩形

thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]

cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cnts = cnts[0]if imutils.is_cv2()else cnts[1]

#找到一系列区域,在区域周围放置矩形

for cin cnts:

(x,y,w,h) = cv2.boundingRect(c)

cv2.rectangle(imageA,(x,y),(x+w,y+h),(0,255,0),2)

cv2.rectangle(imageB,(x,y),(x+w,y+h),(0,255,0),2)

#用cv2.imshow 展现最终对比之后的图片, cv2.imwrite 保存最终的结果图片

cv2.imshow("Modified", imageB)

cv2.imwrite(r"D:\Software\PythonProject\image\result.png", imageB)

cv2.waitKey(0)


执行完后会报错,报错信息如下:

Traceback (most recent call last):

  File "D:/Software/PythonProject/yangtest.py", line 24, in

    (x, y, w, h) = cv2.boundingRect(c)

cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgproc\src\shapedescr.cpp:784: error: (-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function 'cv::pointSetBoundingRect'


经过各种查验,发现是OpenCV版本问题,因为当前环境版本过高,所以需将“#找到不同点的轮廓以致于我们可以在被标识为“不同”的区域周围放置矩形”下的代码修改如下:

thresh = cv2.threshold(diff,0,255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]

cnts = cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

cnts = cnts[1]if imutils.is_cv3()else cnts[0]


最终代码如下:

# -*- coding: utf-8 -*-

from skimage.metricsimport structural_similarity

import imutils

import cv2

# 加载两张图片并将他们转换为灰度

imageA = cv2.imread(r"D:\Software\PythonProject\image\11.png")

imageB = cv2.imread(r"D:\Software\PythonProject\image\22.png")

grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)

grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)

# 计算两个灰度图像之间的结构相似度指数

(score,diff) = structural_similarity(grayA,grayB,full =True)

diff = (diff *255).astype("uint8")

print("SSIM:{}".format(score))

#找到不同点的轮廓以致于我们可以在被标识为“不同”的区域周围放置矩形

thresh = cv2.threshold(diff,0,255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]

cnts = cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

cnts = cnts[1]if imutils.is_cv3()else cnts[0]

#找到一系列区域,在区域周围放置矩形

for cin cnts:

(x,y,w,h) = cv2.boundingRect(c)

cv2.rectangle(imageA,(x,y),(x+w,y+h),(0,255,0),2)

cv2.rectangle(imageB,(x,y),(x+w,y+h),(0,255,0),2)

#用cv2.imshow 展现最终对比之后的图片, cv2.imwrite 保存最终的结果图片

cv2.imshow("Modified", imageB)

cv2.imwrite(r"D:\Software\PythonProject\image\result.png", imageB)

cv2.waitKey(0)

你可能感兴趣的:(Python和OpenCV实现图片比对,并标记展示不同)