Circle detection using Hough transform in OpenCV
Hough transform
A mathematical method called the Hough transform is used in computer vision and image analysis to find basic geometric shapes like circles, lines, and ellipses. The Hough transform primarily represents an image’s lines or curves as points in parameters space. For line and curve detection in images, the Hough transform is an effective tool, especially in situations when more conventional edge detection methods fall short.
Note: You can read more on the following topics by going to their respective links:
Required library
Before we dive into feature matching, it’s important to have OpenCV installed. We can install it using pip:
!pip install opencv-python
Circle detection with cv2.HoughCirlces
In order to detect the circles in the image, OpenCV provides the cv2.HoughCirclces() method. The general syntax of the cv2.HoughCirclces() method with the required parameters is as follows:
cv2.HoughCircles(image, method, dp, minDist, param1, param2, minRadius, maxRadius)
Here are the details of the parameters:
image: Grayscale input imagemethod: The detection method that we'll use to detect the circles (the only implemented method isHOUGH_GRADIENT)dp: Inverse ratio of the accumulator resolution to the image resolutionminDist: The smallest distance between the circles’ centresparam1: Upper threshold for the internal Canny edge detectorparam2: Threshold for center detectionminRadius: Minimum radius of the circlesmaxRadius: Maximum radius of the circles
Note: You’re encouraged to read more about Canny edge detection.
Complete code
Here’s the complete code for circle detection in an image. This is made executable in the “Live demo” section.
import cv2import numpy as npimport matplotlib.pyplot as plt# Read the imageimage = cv2.imread('img1.jpg', cv2.IMREAD_COLOR)# Convert the image to grayscalegray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# Apply Gaussian blur to reduce noise and improve circle detectionblurred = cv2.GaussianBlur(gray, (9, 9), 2)# Use Hough Circle Transform for circle detectioncircles = cv2.HoughCircles(blurred,cv2.HOUGH_GRADIENT,dp=1,minDist=20,param1=50,param2=30,minRadius=50,maxRadius=70 # Adjust maxRadius based on the expected size of the circles)# Convert the (x, y) coordinates and radius of the circles to integersif circles is not None:circles = np.uint16(np.around(circles))for i in circles[0, :]:# Draw the outer circle in redcv2.circle(image, (i[0], i[1]), i[2], (0, 0, 255), 2)# Draw the center of the circlecv2.circle(image, (i[0], i[1]), 2, (0, 0, 255), 3)# Display the result using matplotlib with the updated titleplt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))plt.title('Detected Circles')plt.axis('off')plt.show()
Code explanation
Lines 1–3: We import the required libraries. OpenCV (
cv2) is used for image processing, NumPy (np) for numerical operations, andmatplotlib.pyplot(plt) for visualizing the images.Lines 6–9: We load the image using the
cv2.imread()method and then convert it to grayscale using thecv2.cvtColor()method. Grayscale is used because the Gaussian blur requires a grayscale image as input.Lines 11–12: We use the
cv2.GaussianBlur()method to reduce the noise and to detect the circle more accurately. It uses akernel and a standard deviation of 2. Lines 15–24: Here, we use the
cv2.HoughCircles()method for the preprocessedblurredimage usingcv2.HOUGH_GRADIENTas the detection method. Furthermore, we theminRadiusandmaxRadiusas 50 and 70, respectively, separated by a minimum distance of 20 pixels. The parametersparam1andparam2influence the edge detection and circle center detection thresholds, respectively.Lines 27–33: We process and visualize circles detected in an image by the
cv2.HoughCircles()method by drawing red circles around the detected outlines and optionally marking their centers.Lines 36–39: We use the
plt.imshow()method to show the image and thecv2.cvtColor()to convert the image from the OpenCV BGR format to the RGB format expected bymatplotlib.
Live demo
Run the notebook given in the widget below to execute the code you just saw!
Free Resources