Ask Your Question
0

Why can I get contours from a 'thresh' image but not from a 'mask' image when using VideoCapture?

asked 2018-02-08 05:00:02 -0600

masterenol gravatar image
import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while (1):
    _, frame = cap.read()

    gray = cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY)
    ret, thresh = cv2.threshold(gray,50,255,0)

    # Convert BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of blue color in HSV
    lower_blue = np.array([110, 175, 50])
    upper_blue = np.array([130, 255, 255])

    # Threshold the HSV image to get only blue colors
    mask = cv2.inRange(hsv, lower_blue, upper_blue)

    _, contours, hierarchy = cv2.findContours(thresh, 1, 2)
    cnt = contours[0]

    #_, contours, hierarchy = cv2.findContours(mask, 1, 2)
    #cnt = contours[0]
    ## IndexError: list index out of range


    cv2.imshow('frame', frame)
    cv2.imshow('mask', mask)
    cv2.imshow('thresh',thresh)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

I've been able to determine that both 'thresh' and 'mask' are matrices each of 480 rows and 640 columns and each cell contains either a '0' or '255'. Also, 'thresh' and 'mask' are of type 'numpy.ndarray'.

So why is this valid:

_, contours, hierarchy = cv2.findContours(thresh, 1, 2)
cnt = contours[0]

But this is not:

_, contours, hierarchy = cv2.findContours(mask, 1, 2)
cnt = contours[0]
# cnt = contours[0]
# IndexError: list index out of range
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2018-02-08 13:40:59 -0600

Brandon212 gravatar image

You've given this information about the size of the image and whatever, but the real question is: are there contours in the image for findContours to find in the first place. If you were giving it an all black image for example, then of course it's not going to find any contours in that. Have you displayed the image to see if what you're asking it even makes sense?

edit flag offensive delete link more

Comments

I see. So if the 'mask' is an array filled with zeros, then 'contours' would be an empty list making 'contours[0]' result in an error.

I used the following code which seems to help me in the path I wish to take:

_2, contours2, hierarchy2 = cv2.findContours(mask, 1, 2)
try:
cnt2 = contours2[0]
except:
pass

Thanks for your help @Brandon212 !

masterenol gravatar imagemasterenol ( 2018-02-08 15:49:55 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2018-02-08 05:00:02 -0600

Seen: 691 times

Last updated: Feb 08 '18