houghcircles.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/python
  2. '''
  3. This example illustrates how to use cv.HoughCircles() function.
  4. Usage:
  5. houghcircles.py [<image_name>]
  6. image argument defaults to board.jpg
  7. '''
  8. # Python 2/3 compatibility
  9. from __future__ import print_function
  10. import numpy as np
  11. import cv2 as cv
  12. import sys
  13. def main():
  14. try:
  15. fn = sys.argv[1]
  16. except IndexError:
  17. fn = 'board.jpg'
  18. src = cv.imread(cv.samples.findFile(fn))
  19. img = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
  20. img = cv.medianBlur(img, 5)
  21. cimg = src.copy() # numpy function
  22. circles = cv.HoughCircles(img, cv.HOUGH_GRADIENT, 1, 10, np.array([]), 100, 30, 1, 30)
  23. if circles is not None: # Check if circles have been found and only then iterate over these and add them to the image
  24. circles = np.uint16(np.around(circles))
  25. _a, b, _c = circles.shape
  26. for i in range(b):
  27. cv.circle(cimg, (circles[0][i][0], circles[0][i][1]), circles[0][i][2], (0, 0, 255), 3, cv.LINE_AA)
  28. cv.circle(cimg, (circles[0][i][0], circles[0][i][1]), 2, (0, 255, 0), 3, cv.LINE_AA) # draw center of circle
  29. cv.imshow("detected circles", cimg)
  30. cv.imshow("source", src)
  31. cv.waitKey(0)
  32. print('Done')
  33. if __name__ == '__main__':
  34. print(__doc__)
  35. main()
  36. cv.destroyAllWindows()