hough_circles.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import cv2
  2. import numpy as np
  3. import sys
  4. def onTrackbarChange(max_slider):
  5. cimg = np.copy(img)
  6. p1 = max_slider
  7. p2 = max_slider * 0.4
  8. # Detect circles using HoughCircles transform
  9. circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, cimg.shape[0]/64, param1=p1, param2=p2, minRadius=25, maxRadius=50)
  10. # If at least 1 circle is detected
  11. if circles is not None:
  12. cir_len = circles.shape[1] # store length of circles found
  13. circles = np.uint16(np.around(circles))
  14. for i in circles[0, :]:
  15. # Draw the outer circle
  16. cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)
  17. # Draw the center of the circle
  18. cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)
  19. else:
  20. cir_len = 0 # no circles detected
  21. # Display output image
  22. cv2.imshow('Image', cimg)
  23. # Edge image for debugging
  24. edges = cv2.Canny(gray, p1, p2)
  25. cv2.imshow('Edges', edges)
  26. if __name__ == "__main__":
  27. # Read image
  28. img = cv2.imread(sys.argv[1], 1)
  29. # Convert to gray-scale
  30. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  31. # Create display windows
  32. cv2.namedWindow("Edges")
  33. cv2.namedWindow("Image")
  34. # Trackbar will be used for changing threshold for edge
  35. initThresh = 105
  36. maxThresh = 200
  37. # Create trackbar
  38. cv2.createTrackbar("Threshold", "Image", initThresh, maxThresh, onTrackbarChange)
  39. onTrackbarChange(initThresh)
  40. while True:
  41. key = cv2.waitKey(1)
  42. if key == 27:
  43. break
  44. cv2.destroyAllWindows()