You can download this code by clicking the button below.
This code is now available for download.
This function uses the HoughCircles function from the OpenCV library to detect circles in an image. First, the image is converted to grayscale, and GaussianBlur is applied to reduce noise. Then, Hough transform is used to detect circles, and the detected circles are drawn on the original image.
Technology Stack : OpenCV, NumPy
Code Type : Image processing
Code Difficulty : Intermediate
def detect_circle(image_path):
import cv2
import numpy as np
# Load the image
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply GaussianBlur to remove noise
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# Use HoughCircles to detect circles
circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, dp=1.2, minDist=100,
param1=50, param2=30, minRadius=10, maxRadius=0)
# Draw circles on the original image
if circles is not None:
circles = np.round(circles[0, :]).astype("int")
for (x, y, r) in circles:
cv2.circle(image, (x, y), r, (0, 255, 0), 4)
cv2.rectangle(image, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
# Display the resulting image
cv2.imshow('Detected Circles', image)
cv2.waitKey(0)
cv2.destroyAllWindows()