You can download this code by clicking the button below.
This code is now available for download.
This code uses OpenCV's HoughCircles function to detect circles in an image. It first converts the image to grayscale and applies Gaussian blur to reduce noise. Then, it uses Hough transform to detect circles and draws the detected circles and their boundaries on the original image.
Technology Stack : OpenCV, NumPy
Code Type : Image processing
Code Difficulty : Intermediate
def find_circle(image):
"""
Find circles in the given image using HoughCircles method from OpenCV.
:param image: The input image where circles will be detected.
:return: None
"""
import cv2
import numpy as np
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply GaussianBlur to reduce noise
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# Detect circles
circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, dp=1.2, minDist=100, param1=50, param2=30, minRadius=10, maxRadius=0)
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 image with detected circles
cv2.imshow("Detected Circles", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Example usage
# find_circle(cv2.imread('path_to_image.jpg'))