使用python opencv检测圆圈 - 霍夫变换

问题描述 投票:1回答:1

我试图检测那个image的外部圆圈

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

我的代码是下一个:

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

此代码检测到很多圈子,但外部圈子永远不会出现。

python opencv image-processing object-detection hough-transform
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.