关键词搜索

源码搜索 ×
×

Python笔记-使用SSIM找两张图不同及使用Opencv显示

发布2021-10-05浏览2580次

详情内容

运行截图如下:

 

这里有几点要注意的:

①对比两张图片的函数SSIM具体是structural_similarity:

          Ⅰ:第一个参数和第二个参数是要对比的两张图片;

          Ⅱ:参数中有个full,默认为True,如果为True会把两张图的相似部分返回,如果为False就不返回了;

          Ⅳ:返回值full为False的时候有2个,一个是mssim浮点型的相似度,1代表2张图一模一样。0代表完全不一样,grad返回两张图片不同的地方类型为ndarray;

②SSIM返回的ndarray里面的值为[0, 1]的float型,而OpenCV的[0, 255]为uint8型,可以通过这样的方式转换:

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

③cv2.threshold函数,设置一个阈值和一个颜色,将传入的图片没有达到这个阈值的,转换为这个颜色。

源码如下:

  1. from skimage.metrics import structural_similarity
  2. import cv2
  3. import numpy as np
  4. if __name__ == '__main__':
  5. before = cv2.imread('./pic/demo1.png')
  6. after = cv2.imread('./pic/demo2.png')
  7. # Convert images to grayscale
  8. before_gray = cv2.cvtColor(before, cv2.COLOR_BGR2GRAY)
  9. after_gray = cv2.cvtColor(after, cv2.COLOR_BGR2GRAY)
  10. # Compute SSIM between two images
  11. (score, diff) = structural_similarity(before_gray, after_gray, full=True)
  12. print("Image similarity", score)
  13. # The diff image contains the actual image differences between the two images
  14. # and is represented as a floating point data type in the range [0,1]
  15. # so we must convert the array to 8-bit unsigned integers in the range
  16. # [0,255] before we can use it with OpenCV
  17. diff = (diff * 255).astype("uint8")
  18. # Threshold the difference image, followed by finding contours to
  19. # obtain the regions of the two input images that differ
  20. thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
  21. contours = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  22. contours = contours[0] if len(contours) == 2 else contours[1]
  23. mask = np.zeros(before.shape, dtype='uint8')
  24. filled_after = after.copy()
  25. for c in contours:
  26. area = cv2.contourArea(c)
  27. if area > 40:
  28. x, y, w, h = cv2.boundingRect(c)
  29. cv2.rectangle(before, (x, y), (x + w, y + h), (36, 255, 12), 2)
  30. cv2.rectangle(after, (x, y), (x + w, y + h), (36, 255, 12), 2)
  31. cv2.drawContours(mask, [c], 0, (0, 255, 0), -1)
  32. cv2.drawContours(filled_after, [c], 0, (0, 255, 0), -1)
  33. cv2.imshow('before', before)
  34. cv2.imshow('after', after)
  35. cv2.imshow('diff', diff)
  36. cv2.imshow('mask', mask)
  37. cv2.imshow('filled after', filled_after)
  38. cv2.waitKey(0)

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载