How to identify circles using OpenCV in Python?

You can achieve circle detection using the OpenCV library by following these steps:

  1. Import the OpenCV library.
import cv2
import numpy as np
  1. Read the image and convert it to grayscale image.
image = cv2.imread('image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  1. Perform image pre-processing, such as using Gaussian blur for noise reduction.
blur = cv2.GaussianBlur(gray, (5, 5), 0)
  1. Detect circles in images using the Hough Circle Transform.
circles = cv2.HoughCircles(blur, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)

Param1 and param2 are parameters of the Hough circle transformation. Depending on the characteristics of the image, it may be necessary to adjust these parameters to achieve better circle detection results.

  1. Traverse the detected circles and draw them on the image.
if circles is not None:
    circles = np.uint16(np.around(circles))
    for circle in circles[0, :]:
        center = (circle[0], circle[1])
        radius = circle[2]
        cv2.circle(image, center, radius, (0, 255, 0), 2)
  1. Display the processed image.
cv2.imshow('Circle Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Here are the basic steps for detecting circles using OpenCV. Depending on the specific characteristics and requirements of the image, you may also need to adjust some parameters and perform additional image processing operations.

bannerAds