1 | initial version |
Circles can be detected in OpenCV using the HoughCircles function. This function uses the Hough transform to detect circles in images based on their edge information.
Here's an example of how to use the HoughCircles function to detect circles in an image:
import cv2
import numpy as np
# Load image
img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
# Blur image to reduce noise and improve circle detection
img = cv2.medianBlur(img, 5)
# Detect circles using Hough transform
circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)
# Draw circles on original image
if circles is not None:
circles = np.round(circles[0, :]).astype("int")
for (x, y, r) in circles:
cv2.circle(img, (x, y), r, (0, 255, 0), 2)
cv2.circle(img, (x, y), 2, (0, 0, 255), 3)
# Display result
cv2.imshow('Detected Circles', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
In this example, the HoughCircles function is called with several parameters:
The circles are then drawn on the original image using the cv2.circle function. The resulting image shows the detected circles in green.