Lleims
Lleims

Reputation: 1353

Understanding HoughCircles in Python OpenCV (cv2)

I'm working with this code, 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()

Probably is so easy but can somebody help me to understand the for loop?

Thanks!

Upvotes: 1

Views: 5726

Answers (2)

alfonso
alfonso

Reputation: 884

Check out this link here with a working example of Hough Circles. https://www.pyimagesearch.com/2014/07/21/detecting-circles-images-using-opencv-hough-circles/

I'm not familiar with them myself, but I did take a Computer Vision class a few semesters ago and found this site very helpful in general.

In the article, he provides some code with comments. It seems like circles is a list of all the circles detected in the image. It appears that a circle is an object containing the coordinates of the circle center along with the radius.

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

About your code, for more details about the value of i, try printing i as well as getting the type, and that should give you a hint.

print i
print type(i)

Upvotes: 1

D Malan
D Malan

Reputation: 11424

Every i in for i in circles[0,:]: is a list representing a circle. i is made up of three values: the x-coordinate of it's center, y-coordinate of it's center and its radius.

If you look at the documentation for cv2.circle you will see how the center and radius was used to draw the circles.

Upvotes: 4

Related Questions