在Python OpenCV(cv2)中理解HoughCircles

时间:2018-05-28 14:34:25

标签: python opencv

我正在使用此代码link code font

import cv2
import numpy as np

img = cv2.imread('opencv_logo.png',0)
img = cv2.medianBlur(img,5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20,
                        param1=50,param2=30,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)

cv2.imshow('detected circles',cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()

可能很容易,但有人可以帮我理解for循环吗?

谢谢!

2 个答案:

答案 0 :(得分:3)

i中的每个for i in circles[0,:]:都是一个代表圆圈的列表。 i由三个值组成:它的中心的x坐标,它的中心的y坐标和半径。

如果查看documentation for cv2.circle,您会看到如何使用中心和半径绘制圆圈。

答案 1 :(得分:1)

使用Hough Circles的工作示例查看此链接。 https://www.pyimagesearch.com/2014/07/21/detecting-circles-images-using-opencv-hough-circles/

我自己并不熟悉,但我确实在几个学期前参加了计算机视觉课程,发现这个网站非常有用。

在文章中,他提供了一些评论代码。似乎circles是图像中检测到的所有圆圈的列表。圆圈似乎是一个包含圆心坐标和半径的对象。

# detect circles in the image
circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, 1.2, 100)

# ensure at least some circles were found
if circles is not None:
    # convert the (x, y) coordinates and radius of the circles to integers
    circles = np.round(circles[0, :]).astype("int")

    # loop over the (x, y) coordinates and radius of the circles
    for (x, y, r) in circles:
        # draw the circle in the output image, then draw a rectangle
        # corresponding to the center of the circle
        cv2.circle(output, (x, y), r, (0, 255, 0), 4)
        cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)

    # show the output image
    cv2.imshow("output", np.hstack([image, output]))
    cv2.waitKey(0)

关于您的代码,有关i的值的更多详细信息,请尝试打印i以及获取类型,这应该会给您一个提示。

print i
print type(i)
相关问题