houghcircles.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/usr/bin/python
  2. '''
  3. This example illustrates how to use cv2.HoughCircles() function.
  4. Usage:
  5. houghcircles.py [<image_name>]
  6. image argument defaults to ../data/board.jpg
  7. '''
  8. # Python 2/3 compatibility
  9. from __future__ import print_function
  10. import cv2
  11. import numpy as np
  12. import sys
  13. if __name__ == '__main__':
  14. print(__doc__)
  15. try:
  16. fn = sys.argv[1]
  17. except IndexError:
  18. fn = "../data/board.jpg"
  19. src = cv2.imread(fn, 1)
  20. img = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
  21. img = cv2.medianBlur(img, 5)
  22. cimg = src.copy() # numpy function
  23. circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 10, np.array([]), 100, 30, 1, 30)
  24. a, b, c = circles.shape
  25. for i in range(b):
  26. cv2.circle(cimg, (circles[0][i][0], circles[0][i][1]), circles[0][i][2], (0, 0, 255), 3, cv2.LINE_AA)
  27. cv2.circle(cimg, (circles[0][i][0], circles[0][i][1]), 2, (0, 255, 0), 3, cv2.LINE_AA) # draw center of circle
  28. cv2.imshow("source", src)
  29. cv2.imshow("detected circles", cimg)
  30. cv2.waitKey(0)