使用python opencv检测圈子-Hough变换

时间:2019-01-25 19:44:58

标签: python opencv image-processing object-detection hough-transform

我试图检测该image的外部圈子

但是,无论如何设置霍夫变换的参数,我都无法检测到外部圆。

我的代码是下一个:

###############################
#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)

此代码检测到很多圆圈,但是外部圆圈从未出现。

1 个答案:

答案 0 :(得分:0)

如果您只想检测一个圆圈,则可以帮助您:

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