Search code examples
opencvwebcam

OpenCV program fails sometimes and works other times


I am using an OpenCV program on the 2016 Macbook Pro that requires opening the webcam. I have seen that with the same exact code, sometimes my webcam will open for a second and then end and the program will terminate, even though I haven't clicked the button to terminate.

while(1):
    try:
        ret, frame = cap.read()
        frame = cv2.flip(frame, 1) 
    except:
        pass
    cv2.imshow('mask', mask)
    cv2.imshow('frame', resized)

These are the relevant parts of my code, and I am wondering if there is a problem with the way I start the program.


Solution

  • Quoting the official documentation here:

    Sometimes, cap may not have initialized the capture. In that case, this code shows error. You can check whether it is initialized or not by the method cap.isOpened(). If it is True, OK. Otherwise open it using cap.open().