Naima Tasnim
Naima Tasnim

Reputation: 5

TypeError: 'NoneType' object is not subscriptable for circle detection with opencv

I'm trying to detect circles from my webcam input and draw over the detected objects using this code:

circles = cv2.HoughCircles(roi_gray2, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)

for i in circles[0,:]:
    cv2.circle(roi_color2, tuple(i[0]), tuple(i[1]), (255,255,255), 1)

it leads to this error:

    for i in circles[0,:]:
TypeError: 'NoneType' object is not subscriptable

I'm guessing it runs into this error when the object 'circles' is empty. So I want the for loop to run only when there are elements in the 'circles' object. How do I do this?

Upvotes: 0

Views: 994

Answers (2)

HansHirse
HansHirse

Reputation: 18925

The actual error comes from the tuple() function which expects an iterable. Since you're passing a single value i[0], this function call fails with the given error message. At this point, it doesn't matter, whether circles has proper values or is just None.

So, the first step is, as also stated in Gulzar's answer, to check whether circles is None. But, this doesn't solve the actual error coming from the tuple() call. Therefore, check the OpenCV documentation on circle: The center needs to be a tuple of two int values, and radius a single int value. So, just get rid of the tuple() calls and set up the tuple manually:

if circles is not None:
    for i in circles[0, :]:
        cv2.circle(roi_color2, (int(i[0]), int(i[1])), int(i[2]), (255,255,255), 1)
----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.5
OpenCV:      4.4.0
----------------------------------------

Upvotes: 0

Gulzar
Gulzar

Reputation: 27994

circles = cv2.HoughCircles(roi_gray2, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)

if circles is not None:
    for i in circles[0,:]:
        cv2.circle(roi_color2, tuple(i[0]), tuple(i[1]), (255,255,255), 1)

Is a workaround like you requested.


However, it would make MUCH more sense to avoid this situation altogether.
Ask yourself why circles is None in the first place.

I am assuming there is a previous problem with roi_gray2 that causes cv2.HoughCircles to fail.

Since you didn't provide full code or details, I can't say, but I would check this if I were you, instead of checking for None before the loop. You are just avoiding a consequence rather than the problem itself.

This None test will repeat throughhout your code, instead of solving the origin.

Upvotes: 1

Related Questions