脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python opencv实现图像配准与比较

python opencv实现图像配准与比较

2021-09-04 00:26ericohe Python

这篇文章主要为大家详细介绍了python opencv实现图像配准与比较,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了python opencv实现图像配准与比较的具体代码,供大家参考,具体内容如下

代码

  1. from skimage import io
  2. import cv2 as cv
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5.  
  6. img_path1 = '2_HE_maxarea.png'
  7. img_path2 = '2_IHC_maxarea.png'
  8.  
  9. img1 = io.imread(img_path1)
  10. img2 = io.imread(img_path2)
  11. img1 = np.uint8(img1)
  12. img2 = np.uint8(img2)
  13.  
  14. # find the keypoints and descriptors with ORB
  15. orb = cv.ORB_create()
  16. kp1, des1 = orb.detectAndCompute(img1,None)
  17. kp2, des2 = orb.detectAndCompute(img2,None)
  18.  
  19. # def get_good_match(des1,des2):
  20. # bf = cv.BFMatcher()
  21. # matches = bf.knnMatch(des1, des2, k=2)
  22. # good = []
  23. # for m, n in matches:
  24. # if m.distance < 0.75 * n.distance:
  25. # good.append(m)
  26. # return good,matches
  27. # goodMatch,matches = get_good_match(des1,des2)
  28. # img3 = cv.drawMatchesKnn(img1,kp1,img2,kp2,matches[:20],None,flags=2)
  29.  
  30. # create BFMatcher object
  31. bf = cv.BFMatcher(cv.NORM_HAMMING, crossCheck=True)
  32. # Match descriptors.
  33. matches = bf.match(des1,des2)
  34. # Sort them in the order of their distance.
  35. matches = sorted(matches, key = lambda x:x.distance)
  36. # Draw first 20 matches.
  37. img3 = cv.drawMatches(img1,kp1,img2,kp2,matches[:20],None, flags=2)
  38.  
  39. goodMatch = matches[:20]
  40. if len(goodMatch) > 4:
  41. ptsA= np.float32([kp1[m.queryIdx].pt for m in goodMatch]).reshape(-1, 1, 2)
  42. ptsB = np.float32([kp2[m.trainIdx].pt for m in goodMatch]).reshape(-1, 1, 2)
  43. ransacReprojThreshold = 4
  44. H, status =cv.findHomography(ptsA,ptsB,cv.RANSAC,ransacReprojThreshold);
  45. #其中H为求得的单应性矩阵矩阵
  46. #status则返回一个列表来表征匹配成功的特征点。
  47. #ptsA,ptsB为关键点
  48. #cv2.RANSAC, ransacReprojThreshold这两个参数与RANSAC有关
  49. imgOut = cv.warpPerspective(img2, H, (img1.shape[1],img1.shape[0]),flags=cv.INTER_LINEAR + cv.WARP_INVERSE_MAP)
  50.  
  51. # 叠加配准变换图与基准图
  52. rate = 0.5
  53. overlapping = cv.addWeighted(img1, rate, imgOut, 1-rate, 0)
  54. io.imsave('HE_2_IHC.png', overlapping)
  55. err = cv.absdiff(img1,imgOut)
  56.  
  57. # 显示对比
  58. plt.subplot(221)
  59. plt.title('orb')
  60. plt.imshow(img3)
  61.  
  62. plt.subplot(222)
  63. plt.title('imgOut')
  64. plt.imshow(imgOut)
  65.  
  66. plt.subplot(223)
  67. plt.title('overlapping')
  68. plt.imshow(overlapping)
  69.  
  70. plt.subplot(224)
  71. plt.title('diff')
  72. plt.imshow(err)
  73.  
  74. plt.show()

结果:

python opencv实现图像配准与比较

python opencv实现图像配准与比较

python opencv实现图像配准与比较

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

原文链接:https://blog.csdn.net/Ericohe/article/details/113755837

延伸 · 阅读

精彩推荐