# Circle Detection OpenCV Python Read it later

5/5 - (1 vote)

Similar to some previous posts, where we learned about edge detection, line detection, blob detection, lane detection, and so on. We are going to circle detection in OpenCV python in this OpenCV blog.

In the OpenCV Line Detection blog, we saw the function of the Hough lines which helped us detect lines in a picture, similar in this circle detection, we will use the function of Hough Circles. I would suggest you read the Line Detection OpenCV blog first, and then come to this blog to better understand it.

## Circle detection using Hough transform OpenCV

The Hough transform is a popular technique for circle detection. It works by transforming the image into a parameter space, where each point represents a possible circle center. The technique then searches for the best parameters to define a circle that fits the image.

The OpenCV library provides a function called HoughCircles that implements the Hough transform for circle detection. The function takes the input image, the detection method, the inverse ratio of the resolution, the minimum and maximum radius of the circles, and the threshold value as parameters.

Here is the syntax of the function:

``cv2.HoughCircles(image, method, dp, minDist[, circles[, param1[, param2[, minRadius[, maxRadius]]]]])``
• image: the input image
• method: the detection method, currently only cv2.HOUGH_GRADIENT is supported
• dp: inverse ratio of the resolution
• minDist: minimum distance between the centers of the detected circles
• circles: output vector of found circles
• param1: the higher threshold of the two passed to the Canny edge detector
• param2: accumulator threshold for the circle centers at the detection stage

Hough Circle Transform algorithm works by scanning the image for all possible circles that meet certain criteria, such as a minimum radius or a specific color range. To use this algorithm in OpenCV, you need to follow these steps:

1. Read the image using OpenCV’s `imread()` function.
2. Convert the image to grayscale using OpenCV’s `cvtColor()` function.
3. Apply Gaussian Blur to the grayscale image to remove any noise using OpenCV’s `GaussianBlur()` function.
4. Use the `HoughCircles()` function to detect circles in the image.

Here is an example code that demonstrates how to use the Hough Circle Transform to detect circles in an image:

``````import cv2
import numpy as np

# Blur image
img = cv2.GaussianBlur(img, (5, 5), 0)

# Apply Hough Circle Transform

# Convert the (x, y) coordinates and radius of the circles to integers
circles = np.round(circles[0, :]).astype("int")

# Draw circles on the original image
for (x, y, r) in circles:
cv2.circle(img, (x, y), r, (0, 255, 0), 2)

# Display the image
cv2.imshow("Detected Circles", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
``````

In this example, we first load an image called circles.jpg and convert it to grayscale. We then apply a median blur to reduce noise in the image. We create a copy of the grayscale image and convert it to the BGR color space to draw the detected circles in color.

We then use the HoughCircles function to detect the circles in the image. We pass the grayscale image, the detection method, an inverse ratio of 1 (which means the resolution of the image is not changed), a minimum distance of 20 between the centers of the circles, a threshold value of 50 for the

Canny edge detector, an accumulator threshold of 30, and a minimum and maximum radius of 0. The function returns an array of circles, which we convert to integers using np.uint16 and round using np.around.

We then loop through the detected circles and draw them on the color image. We draw the outer circle using cv2.circle and the center using cv2.circle with a radius of 2 and color (0,0,255). Finally, we display the image using cv2.imshow.

## Circle detection using contours

Another way to detect circles in an image is to use contours. A contour is a curve joining all the continuous points (along the boundary), having the same color or intensity. We can use the findContours function in OpenCV to find the contours in an image.

Here is an example of using findContours to detect circles in an image:

``````import cv2
import numpy as np

img = cv2.medianBlur(img,5)

ret,thresh = cv2.threshold(img,127,255,0)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
center = (int(x),int(y))

cv2.imshow('detected circles',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
``````

In this example, we first load an image called circles.jpg and convert it to grayscale. We then apply a median blur to reduce noise in the image. We apply a threshold using cv2.threshold, which converts the grayscale image to a binary image. The threshold value of 127 is used to separate the circles from the background.

We then use cv2.findContours to find the contours in the binary image. We pass the binary image, the retrieval mode (cv2.RETR_EXTERNAL), and the approximation method (cv2.CHAIN_APPROX_SIMPLE). The function returns a list of contours and a hierarchy.

We loop through the contours and use cv2.minEnclosingCircle to find the center and radius of each circle. We then draw the circles using cv2.circle with a radius of 2 and color (0,255,0). Finally, we display the image using cv2.imshow.

## Circle detection using SimpleBlobDetector

Another way to detect circles in images is to use the SimpleBlobDetector algorithm, which detects blobs (or regions of interest) in images. This algorithm works by scanning the image for blobs that meet certain criteria, such as a minimum size, circularity, and convexity. To use this algorithm in OpenCV, you need to follow these steps:

2. Convert the image to grayscale using OpenCV’s cvtColor() function.
3. Create a SimpleBlobDetector object using the cv2.SimpleBlobDetector_create() function.
4. Use the detect() function of the SimpleBlobDetector object to detect blobs in the image.
5. Draw circles on the original image using the detected blob centers and radii.

Here is an example code that demonstrates how to use the SimpleBlobDetector algorithm to detect circles in an image:

``````import cv2
import numpy as np

# Convert the image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Create a SimpleBlobDetector object
detector = cv2.SimpleBlobDetector_create()

# Detect blobs in the image
keypoints = detector.detect(gray)

# Draw circles on the original image
for keypoint in keypoints:
x = int(keypoint.pt)
y = int(keypoint.pt)
r = int(keypoint.size / 2)
cv2.circle(img, (x, y), r, (0, 255, 0), 2)

# Display the image
cv2.imshow("Detected Circles", img)
cv2.waitKey(0)
cv2.destroyAllWindows()``````

In the above code, we first load the image using the `imread()` function and then convert it to grayscale using the `cvtColor()` function. We then create a `SimpleBlobDetector` object using the `SimpleBlobDetector_create()` function and use the detect() function to detect blobs in the image.

Once the blobs are detected, we draw circles on the original image using the centers and radii of the detected blobs. Finally, we display the image using the `imshow()` function.