circle.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import cv2
  2. import numpy as np
  3. # define a video capture object
  4. vid = cv2.VideoCapture(0)
  5. while(True):
  6. # Capture the video frame
  7. # by frame
  8. ret, frame = vid.read()
  9. # Convert to grayscale.
  10. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  11. # Blur using 3 * 3 kernel.
  12. gray_blurred = cv2.blur(gray, (3, 3))
  13. # Apply Hough transform on the blurred image.
  14. detected_circles = cv2.HoughCircles(gray_blurred,
  15. cv2.HOUGH_GRADIENT, 1, 1000, param1 = 60,
  16. param2 = 30, minRadius = 100, maxRadius = 200)
  17. # Draw circles that are detected.
  18. if detected_circles is not None:
  19. # Convert the circle parameters a, b and r to integers.
  20. detected_circles = np.uint16(np.around(detected_circles))
  21. for pt in detected_circles[0, :]:
  22. a, b, r = pt[0], pt[1], pt[2]
  23. # Draw the circumference of the circle.
  24. cv2.circle(frame, (a, b), r, (0, 255, 0), 2)
  25. # Draw a small circle (of radius 1) to show the center.
  26. cv2.circle(frame, (a, b), 1, (0, 0, 255), 3)
  27. # Display the resulting frame
  28. cv2.imshow('frame', frame)
  29. # the 'q' button is set as the
  30. # quitting button you may use any
  31. # desired button of your choice
  32. if cv2.waitKey(1) & 0xFF == ord('q'):
  33. break
  34. # After the loop release the cap object
  35. vid.release()
  36. # Destroy all the windows
  37. cv2.destroyAllWindows()