You can download this code by clicking the button below.
This code is now available for download.
This code defines a function named detect_circles that takes an image path as input, uses the HoughCircles function from the OpenCV library to detect circles in the image, and draws the detected circles on the original image.
Technology Stack : The code uses the OpenCV library and the HoughCircles function to detect circles in an image.
Code Type : The type of code
Code Difficulty :
import cv2
import numpy as np
def detect_circles(image_path):
# Load the image in grayscale
gray = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
# Apply GaussianBlur to reduce noise
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# Detect circles using HoughCircles
circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, dp=1.2, minDist=50, param1=50, param2=30, minRadius=10, maxRadius=0)
# Draw the 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)
# Return the image with detected circles
return image