i am trying to write a code using Python and opencv the code should count the numbers of smaller circles and the numbers of larger circles automatically and also display the separated circles in two different images.
so far i done this code :
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the image
image = cv2.imread(r'c:\Users\user\Downloads\circles.tif', cv2.IMREAD_GRAYSCALE)
# Display the original image
cv2.imshow('Gray Image', image)
cv2.waitKey(0)
# Apply Gaussian blur to the image to reduce noise and improve circle detection
blurred = cv2.medianBlur(image, 3)
# Use HoughCircles to detect circles in the image
circles = cv2.HoughCircles(
blurred,
cv2.HOUGH_GRADIENT,
dp=1,
minDist=50,
param1=400,
param2=12,
minRadius=12,
maxRadius=55
)
# If circles are found, draw them on the image
if circles is not None:
circles = np.uint16(np.around(circles))
# Create separate images for smaller and larger circles
smaller_circles_image = np.zeros_like(image)
larger_circles_image = np.zeros_like(image)
for i in circles[0, :]:
x, y, radius = i[0], i[1], i[2]
# Draw the circle on the original image
cv2.circle(image, (x, y), radius, (0, 255, 0), 2)
# Separate circles based on radius
if radius < 25:
cv2.circle(smaller_circles_image, (x, y), radius, 255, -1)
else:
cv2.circle(larger_circles_image, (x, y), radius, 255, -1)
# Display the original image with circles
cv2.imshow('Circles Detected', image)
cv2.waitKey(0)
# Display the images with separated smaller and larger circles
cv2.imshow('Smaller Circles', smaller_circles_image)
cv2.imshow('Larger Circles', larger_circles_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Count the number of smaller and larger circles
num_smaller_circles = len(circles[0, circles[0, :, 2] < 25])
num_larger_circles = len(circles[0, circles[0, :, 2] >= 25])
print(f'Number of smaller circles: {num_smaller_circles}')
print(f'Number of larger circles: {num_larger_circles}')
else:
print('No circles detected.')
my problem is i can not detect the partial circles one the top and the circle on the right is detected but not accurately. what can i change or add to be able to detect them?
here is the orignal image
Output (screenshot):

