OpenCV Circle Detection and Visualization

  • Share this:

Code introduction


This code uses the HoughCircles function from the OpenCV library to detect circles in an image and draw them on the original image. It first reads the image, converts it to grayscale, and then applies Gaussian blur to reduce noise. Finally, it uses Hough transform to detect circles and draws circles and rectangles around the detected circles.


Technology Stack : OpenCV library, HoughCircles, grayscale conversion, Gaussian blur, Hough transform

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def detect_circle(image_path):
    # Load the image
    import cv2
    image = cv2.imread(image_path)
    
    # Convert the image to grayscale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    # Apply blur to reduce noise
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    
    # Perform HoughCircles detection
    circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, dp=1.2, minDist=50, param1=50, param2=30, minRadius=10, maxRadius=0)
    
    # Draw the circles on the image
    if circles is not None:
        circles = np.round(circles[0, :]).astype("int")
        for (x, y, r) in circles:
            cv2.circle(image, (x, y), r, (0, 255, 0), 4)
            cv2.rectangle(image, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
    
    # Display the output
    cv2.imshow("Circles Detected", image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()