from skimage.metrics import structural_similarity as compare_ssim
import cv2
# 加載兩張圖片並將他們轉換為灰度
imageA = cv2.imread(r"/Users/dcc/Desktop/333.JPG")
imageB = cv2.imread(r"/Users/dcc/Desktop/4444.JPG")
grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)
# 計算兩個灰度圖像之間的結構相似度指數
(score, diff) = compare_ssim(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]
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(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("Modified", imageB)
cv2.imwrite(r"/Users/dcc/Desktop/99999999999.png", imageB)
cv2.waitKey(0)
非原著,網上的比較老了,執行就報錯,所以重新搞了一個版本
