hough_circle.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import sys
  2. import cv2 as cv
  3. import numpy as np
  4. def main(argv):
  5. ## [load]
  6. default_file = 'smarties.png'
  7. filename = argv[0] if len(argv) > 0 else default_file
  8. # Loads an image
  9. src = cv.imread(cv.samples.findFile(filename), cv.IMREAD_COLOR)
  10. # Check if image is loaded fine
  11. if src is None:
  12. print ('Error opening image!')
  13. print ('Usage: hough_circle.py [image_name -- default ' + default_file + '] \n')
  14. return -1
  15. ## [load]
  16. ## [convert_to_gray]
  17. # Convert it to gray
  18. gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
  19. ## [convert_to_gray]
  20. ## [reduce_noise]
  21. # Reduce the noise to avoid false circle detection
  22. gray = cv.medianBlur(gray, 5)
  23. ## [reduce_noise]
  24. ## [houghcircles]
  25. rows = gray.shape[0]
  26. circles = cv.HoughCircles(gray, cv.HOUGH_GRADIENT, 1, rows / 8,
  27. param1=100, param2=30,
  28. minRadius=1, maxRadius=30)
  29. ## [houghcircles]
  30. ## [draw]
  31. if circles is not None:
  32. circles = np.uint16(np.around(circles))
  33. for i in circles[0, :]:
  34. center = (i[0], i[1])
  35. # circle center
  36. cv.circle(src, center, 1, (0, 100, 100), 3)
  37. # circle outline
  38. radius = i[2]
  39. cv.circle(src, center, radius, (255, 0, 255), 3)
  40. ## [draw]
  41. ## [display]
  42. cv.imshow("detected circles", src)
  43. cv.waitKey(0)
  44. ## [display]
  45. return 0
  46. if __name__ == "__main__":
  47. main(sys.argv[1:])