The Wayback Machine - https://web.archive.org/web/20240702112951/https://www.geeksforgeeks.org/circle-detection-using-opencv-python/
Open In App

Circle Detection using OpenCV | Python

Last Updated : 04 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report
Circle detection finds a variety of uses in biomedical applications, ranging from iris detection to white blood cell segmentation. The technique followed is similar to the one used to detect lines, as discussed in this article. Basics of Circle Detection A circle can be described by the following equation: To detect circles, we may fix a point (x, y). Now, we are required to find 3 parameters: a, b and r. Therefore, the problem is in a 3-dimensional search space. To find possible circles, the algorithm uses a 3-D matrix called the “Accumulator Matrix” to store potential a, b and r values. The value of a (x-coordinate of the center) may range from 1 to rows, b (y-coordinate of the center) may range from 1 to cols, and r may range from 1 to maxRadius = \sqrt{rows^2 + cols^2}. Below are the steps of the algorithm.
  • Initializing the Accumulator Matrix: Initialize a matrix of dimensions rows * cols * maxRadius with zeros.
  • Pre-processing the image: Apply blurring, grayscale and an edge detector on the image. This is done to ensure the circles show as darkened image edges.
  • Looping through the points: Pick a point x_i on the image.
  • Fixing r and looping through a and b: Use a double nested loop to find a value of r, varying a and b in the given ranges.
    for a in range(rows):
        for b in range(cols):
            r = math.sqrt((xi - a)**2 + (yi - b)**2)
            accum_matrix[a][b][r] += 1
    
                        
  • Voting: Pick the points in the accumulator matrix with the maximum value. These are strong points which indicate the existence of a circle with a, b and r parameters. This gives us the Hough space of circles.
  • Finding Circles: Finally, using the above circles as candidate circles, vote according to the image. The maximum voted circle in the accumulator matrix gives us the circle.
The HoughCircles function in OpenCV has the following parameters which can be altered according to the image.
Detection Method: OpenCV has an advanced implementation, HOUGH_GRADIENT, which uses gradient of the edges instead of filling up the entire 3D accumulator matrix, thereby speeding up the process. dp: This is the ratio of the resolution of original image to the accumulator matrix. minDist: This parameter controls the minimum distance between detected circles. Param1: Canny edge detection requires two parameters — minVal and maxVal. Param1 is the higher threshold of the two. The second one is set as Param1/2. Param2: This is the accumulator threshold for the candidate detected circles. By increasing this threshold value, we can ensure that only the best circles, corresponding to larger accumulator values, are returned. minRadius: Minimum circle radius. maxRadius: Maximum circle radius.
Below is the code for finding circles using OpenCV on the above input image.
import cv2
import numpy as np
  
# Read image.
img = cv2.imread('eyes.jpg', cv2.IMREAD_COLOR)
  
# Convert to grayscale.
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  
# Blur using 3 * 3 kernel.
gray_blurred = cv2.blur(gray, (3, 3))
  
# Apply Hough transform on the blurred image.
detected_circles = cv2.HoughCircles(gray_blurred, 
                   cv2.HOUGH_GRADIENT, 1, 20, param1 = 50,
               param2 = 30, minRadius = 1, maxRadius = 40)
  
# Draw circles that are detected.
if detected_circles is not None:
  
    # Convert the circle parameters a, b and r to integers.
    detected_circles = np.uint16(np.around(detected_circles))
  
    for pt in detected_circles[0, :]:
        a, b, r = pt[0], pt[1], pt[2]
  
        # Draw the circumference of the circle.
        cv2.circle(img, (a, b), r, (0, 255, 0), 2)
  
        # Draw a small circle (of radius 1) to show the center.
        cv2.circle(img, (a, b), 1, (0, 0, 255), 3)
        cv2.imshow("Detected Circle", img)
        cv2.waitKey(0)

                    
Output:

Previous Article
Next Article

Similar Reads

Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Python | Corner detection with Harris Corner Detection method using OpenCV
Harris Corner detection algorithm was developed to identify the internal corners of an image. The corners of an image are basically identified as the regions in which there are variations in large intensity of the gradient in all possible dimensions and directions. Corners extracted can be a part of the image features, which can be matched with fea
2 min read
Python | Corner Detection with Shi-Tomasi Corner Detection Method using OpenCV
What is a Corner? A corner can be interpreted as the junction of two edges (where an edge is a sudden change in image brightness). Shi-Tomasi Corner Detection - Shi-Tomasi Corner Detection was published by J.Shi and C.Tomasi in their paper 'Good Features to Track'. Here the basic intuition is that corners can be detected by looking for significant
3 min read
Face detection using Cascade Classifier using OpenCV-Python
In this article, we are going to see how to detect faces using a cascade classifier in OpenCV Python. Face detection has much significance in different fields of today's world. It is a significant step in several applications, face recognition (also used as biometrics), photography (for auto-focus on the face), face analysis (age, gender, emotion r
4 min read
Pedestrian Detection using OpenCV-Python
OpenCV is an open-source library, which is aimed at real-time computer vision. This library is developed by Intel and is cross-platform - it can support Python, C++, Java, etc. Computer Vision is a cutting edge field of Computer Science that aims to enable computers to understand what is being seen in an image. OpenCV is one of the most widely used
3 min read
Multiple Color Detection in Real-Time using Python-OpenCV
For a robot to visualize the environment, along with the object detection, detection of its color in real-time is also very important. Why this is important? : Some Real-world Applications In self-driving car, to detect the traffic signals. Multiple color detection is used in some industrial robots, to performing pick-and-place task in separating d
4 min read
Gun Detection using Python-OpenCV
Gun Detection using Object Detection is a helpful tool to have in your repository. It forms the backbone of many fantastic industrial applications. We can use this project for real threat detection in companies or organizations. Prerequisites: Python OpenCV OpenCV(Open Source Computer Vision Library) is a highly optimized library with a focus on Re
4 min read
Contour Detection with Custom Seeds using Python - OpenCV
This article discusses how we can dynamically detect contours by clicking on the Image and assign different colors to different parts of the image. Contours are a very useful tool for shape analysis and object detection and recognition. This program uses OpenCV, Numpy, and Matplotlib libraries. It also uses a built-in OpenCV Watershed algorithm to
3 min read
Automating Scrolling using Python-Opencv by Color Detection
Prerequisites: OpencvPyAutoGUI It is possible to perform actions without actually giving any input through touchpad or mouse. This article discusses how this can be done using opencv module. Here we will use color detection to scroll screen. When a certain color is detected by the program during execution the screen starts to scroll on its own. App
2 min read
Face and Hand Landmarks Detection using Python - Mediapipe, OpenCV
In this article, we will use mediapipe python library to detect face and hand landmarks. We will be using a Holistic model from mediapipe solutions to detect all the face and hand landmarks. We will be also seeing how we can access different landmarks of the face and hands which can be used for different computer vision applications such as sign la
4 min read
Practice Tags :
three90RightbarBannerImg