I would like to use cv2.HoughCircles to have two circles from my image.
Here is the original image:
I expect to have two circles like this:
But I got this:
I have tried different parameters but I could not find a way to get two circles I expected. Not sure if the edge of circle is not smooth enough for HoughCircles to detect (a lot of matrix to calculate)?
Here is the code I have tried:
import cv2
import numpy as np
# Read image
img = cv2.imread('image_original.png')
hh, ww = img.shape[:2]
# # resize image to 1/4
# img = cv2.resize(img, dsize=(0,0), fx=0.25, fy=0.25)
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Gaussian filter
gray = cv2.GaussianBlur(gray, ksize=(3,3), sigmaX=0, sigmaY=0)
# get canny edges
canny = cv2.Canny(gray, 20, 140)
print(img.shape)
# get Hough circles
min_dist = int(ww/4)
circles = cv2.HoughCircles(canny, cv2.HOUGH_GRADIENT, 280, minDist=min_dist, param1=200, param2=140, minRadius=0, maxRadius=0)
print(circles)
# draw circles
result = img.copy()
for circle in circles[0]:
# draw the circle in the output image
(x,y,r) = circle
x = int(x)
y = int(y)
r = int(r)
cv2.circle(result, (x, y), r, (0, 0, 255), 1)
# save results
cv2.imwrite('image_result.jpg', result)
# show images
cv2.imshow('gray', gray)
cv2.imshow('canny', canny)
cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()


