Circle Detection OpenCV Python

Circle Detection OpenCV Python

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.


import cv2 as cv

import numpy as np

from matplotlib import pyplot as plt

Circle Detection OpenCV Algorithm

The first step is common in every OpenCV Detection program, i.e to load the image on which the algorithm is to be applied.

Image is the resized and a colorful copy of that image is stored in another variable. The Image is then converted to the grayscale image as the HoughCircles() function is applied only to the grayscale images.

Then the HoughCircle() function is applied on the grayscale image.

Gray scaled image is then blurred using medianBlur() function.

The HoughCircles() function in the OpenCV library takes many parameters.

  1. The grayscale image on which the circle detection is to be implemented.
  2. Gradient function – cv.HOUGH_GRADIENT
  3. DP value i.e the resolution of the accumulator
  4. minimum distance
  5. Number of circles
  6. parameter 1
  7. parameter 2
  8. Minimum Radius
  9. Maximum Radius

Formula of Circle:

(x-xc)2 + (y-yc)2 = r2HoughCircles() function present in the OpenCV library uses this mathematical formula to detect circles.

def circleDetection():
    img = cv.imread('./img/balls2.jpg')
    img = cv.resize(img, (500, 400))
    output = img.copy()
    gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    blur = cv.medianBlur(gray_img, 5)
    circles = cv.HoughCircles(blur, cv.HOUGH_GRADIENT,
                              1, 100, 10, param1=130, param2=55, minRadius=5, maxRadius=0)

    detected_circles = np.uint16(np.around(circles))

    for (x, y, r) in detected_circles[0, :]:, (x, y), r, (0, 255, 0), 3), (x, y), 2, (255, 0, 0), 3)

    cv.imshow("Original Image", img)
    cv.imshow("Output", output)

Shuffle the values of the HoughCircle() function in order to get the perfect fit for your model.

Circle Detected Image

Circle Detection OpenCV Python
Circle Detection OpenCV Python

Learn about more Python OpenCV projects from github.

Read other blogs to learn about more Python OpenCV Projects like Lane Detection, Line Detection, Image Blending, and so on.


Leave a Reply

Your email address will not be published. Required fields are marked *