天天看點

opencv2、python 比較兩張相同尺寸圖檔,并标注出其差異處

https://www.pyimagesearch.com/2017/06/19/image-difference-with-opencv-and-python/#comment-429138

https://blog.csdn.net/ibaymin/article/details/74936742

從上述兩個網站參考的代碼,

但是實作時出現了報錯,進行了更改并增加了注意點/注釋

opencv findContours()函數解釋:↓

https://blog.csdn.net/hjxu2016/article/details/77833336

from skimage.measure import compare_ssim
import argparse
import imutils
import cv2


#加載兩張圖檔:
#注意,從檔案路徑複制來的斜杠是反的,記得更改,且用英文路徑

imageA = cv2.imread("C:/Users/Estiny/Desktop/text/11.16.jpg") 
imageB = cv2.imread("C:/Users/Estiny/Desktop/text/11.11.jpg")

#将他們轉換為灰階:

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


#計算兩個灰階圖像之間的結構相似度指數:
#不過ssim多用于壓縮圖檔後的失真度比較。。

(score,diff) = compare_ssim(grayA,grayB,full = True)
diff = (diff *255).astype("uint8")



#找到不同點的輪廓以緻于我們可以在被辨別為“不同”的區域周圍放置矩形:

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

#cv2.findContours()函數傳回兩個值,一個是輪廓本身,還有一個是每條輪廓對應的屬性。
#其首先傳回一個list,list中每個元素都是圖像中的一個輪廓

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


"""注意cv版本,下面這一行會出現下列問題:
OpenCV 3 改為cv2.findContours(...)傳回值為image, contours, hierarchy,

OpenCV 2 cv2.findContours(...)和OpenCV 4 的cv2.findContours(...)傳回值為contours, hierarchy。"""

#把contour輪廓儲存在cnts這個list清單裡

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


#找到一系列區域,在區域周圍放置矩形:
"""

cv2.rectangle(imageA,(x,y),(x+w,y+h),(0,0,255),2)  參數解釋

第一個參數:img是原圖

第二個參數:(x,y)是矩陣的左上點坐标

第三個參數:(x+w,y+h)是矩陣的右下點坐标

第四個參數:(0,0,255)是畫線對應的rgb顔色

第五個參數:2是所畫的線的寬度
"""

for c in cnts:                                                                                                                                                                                                                                        
    (x,y,w,h) = cv2.boundingRect(c)                                                                                                                                                                                              
    cv2.rectangle(imageA,(x,y),(x+w,y+h),(0,0,255),2)                                                                                                                                                                         
    cv2.rectangle(imageB,(x,y),(x+w,y+h),(0,0,255),2)




#用cv2.imshow 展現最終對比之後的圖檔, cv2.imwrite 儲存最終的結果圖檔

cv2.imshow("differ",imageB)
cv2.imwrite("differ.png",imageB)
cv2.waitKey(0)
           

繼續閱讀