Circle Detection using OpenCV | Python
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
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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 = .
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 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.
- 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.
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.