1
votes

I tried to detect the external circle of that image

However, no matter how I set the params of the Hough Transform, I can't detect the external circle.

My code is the next:

###############################
#Circle detection
###############################
height, width = image.shape

circles = cv2.HoughCircles(image,cv2.HOUGH_GRADIENT,.3,20,param1=100,param2=100,minRadius=int(min(width,height)/3),maxRadius=int(min(width,height)))

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

cimg=origin

for i in circles[0,:]:
    cv2.circle(cimg,(i[0],i[1]),i[2],(255,0,0),1) #DRAW ALL CIRCLES IN BLUE
    cv2.circle(cimg,(i[0],i[1]),2,(255,0,0),1)


###############################
#FIND HIGHER CIRCLE
###############################
#I go through all the circles and 
#take the one with the greatest radio
max_index=0
max_i=circles[0,max_index,2]
for indx, i in enumerate(circles[0,:]):
    if i[2]>max_i:
        max_i=i[2]
        max_index=indx   #indx of higher circle

circle_max=max_i
x_max=circles[0,max_index,0]
y_max=circles[0,max_index,1]
r_max=circles[0,max_index,2]

cv2.circle(cimg,(x_max,y_max),r_max,(0,0,255),1) #DRAW HIGHER CIRCLE IN RED
cv2.circle(cimg,(x_max,y_max),2,(0,0,255),3)

This code detect a lot of circles, but the external circle never appears.

1
Why bother with Hough - find the outer contour and its width/height give you the centre and diameter.balmy

1 Answers

0
votes

If you want to detect only one circle, this can help you:

import cv2
import numpy as np
from matplotlib import pyplot as plt

name_image = "ImageTest.png"
bgr_img = cv2.imread(name_image)

b,g,r = cv2.split(bgr_img)       # get b,g,r
rgb_img = cv2.merge([r,g,b])     # switch it to rgb
gray_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2GRAY)
img = cv2.medianBlur(gray_img, 5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,7,20,
                            param1=90,param2=2400,minRadius=0,maxRadius=0)

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

for i in circles[0,:]:
    # draw the outer circle
    cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
    # draw the center of the circle
    cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)

plt.subplot(121),plt.imshow(rgb_img)
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(cimg)
plt.title('Hough Transform'), plt.xticks([]), plt.yticks([])
plt.show()

cv2.imwrite(name_image.split(".png")[0] +'_HoughTransform.png', cimg)

enter image description here