OpenCV哈里斯(Harris)角点检测的实现

前端之家收集整理的这篇文章主要介绍了OpenCV哈里斯(Harris)角点检测的实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

环境

  1. pip install opencv-python==3.4.2.16
  2.  
  3. pip install opencv-contrib-python==3.4.2.16

理论

克里斯·哈里斯Chris Harris)和迈克·史蒂芬斯(Mike Stephens)在1988年的论文《组合式拐角和边缘检测器》中做了一次尝试找到这些拐角的尝试,所以现在将其称为哈里斯拐角检测器。

函数:cv2.cornerHarris()cv2.cornerSubPix()

示例代码

  1. import cv2
  2. import numpy as np
  3.  
  4. filename = 'molecule.png'
  5. img = cv2.imread(filename)
  6. gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
  7.  
  8. gray = np.float32(gray)
  9. dst = cv2.cornerHarris(gray,2,3,0.04)
  10.  
  11. #result is dilated for marking the corners,not important
  12. dst = cv2.dilate(dst,None)
  13.  
  14. # Threshold for an optimal value,it may vary depending on the image.
  15. img[dst>0.01*dst.max()]=[0,255]
  16.  
  17. cv2.imshow('dst',img)
  18. if cv2.waitKey(0) & 0xff == 27:
  19. cv2.destroyAllWindows()

原图

OpenCV哈里斯(Harris)角点检测的实现


输出

OpenCV哈里斯(Harris)角点检测的实现


SubPixel精度的角落

  1. import cv2
  2. import numpy as np
  3.  
  4. filename = 'molecule.png'
  5. img = cv2.imread(filename)
  6. gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
  7.  
  8. # find Harris corners
  9. gray = np.float32(gray)
  10. dst = cv2.cornerHarris(gray,0.04)
  11. dst = cv2.dilate(dst,None)
  12. ret,dst = cv2.threshold(dst,0.01*dst.max(),255,0)
  13. dst = np.uint8(dst)
  14.  
  15. # find centroids
  16. ret,labels,stats,centroids = cv2.connectedComponentsWithStats(dst)
  17.  
  18. # define the criteria to stop and refine the corners
  19. criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER,100,0.001)
  20. corners = cv2.cornerSubPix(gray,np.float32(centroids),(5,5),(-1,-1),criteria)
  21.  
  22. # Now draw them
  23. res = np.hstack((centroids,corners))
  24. res = np.int0(res)
  25. img[res[:,1],res[:,0]]=[0,255]
  26. img[res[:,3],2]] = [0,0]
  27.  
  28. cv2.imwrite('subpixel5.png',img)

输出

OpenCV哈里斯(Harris)角点检测的实现


参考

https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_feature2d/py_features_harris/py_features_harris.html#harris-corners

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

猜你在找的Python相关文章