简体   繁体   中英

cv2 doesn't give an error in Python, so can't use it with except block

I'm using cv2 to start the camera in Python. I want it to be flexible, so it does not matter if the user is using a built-in cam or a USB one, it'd work. It would also show an error if the cam wasn't recognized.

This is how far I've written.

try:    
    camera = cv2.VideoCapture(0)
            
except:
    try:
        camera = cv2.VideoCapture(1)
                
    except:
        print("")
        print("There was a problem accessing your camera, please try again")
        print("Exiting now...")
        time.sleep(10)
        exit()

The thing is, cv2 doesn't give a Python error if it does not detect a cam. It just gives the following warning:

[ WARN:0] global /tmp/pip-req-build-ddpkm6fn/opencv/modules/videoio/src/cap_v4l.cpp (893) open VIDEOIO(V4L2:/dev/video2): can't open camera by index

So, the second except block is not executed, which would probably leave my users confused about the warning. How do I make it so that the except block is executed?

Thanks!

Using cv2.VideoCapture( invalid device number ) does not throw exceptions. It constructs a containing an invalid device - if you use it you get exceptions.

Test the constructed object for None and not isOpened() to weed out invalid ones.

import cv2 as cv 

def testDevice(source):
   cap = cv.VideoCapture(source) 
   if cap is None or not cap.isOpened():
       print('Warning: unable to open video source: ', source)

testDevice(0) # no printout
testDevice(1) # prints message

I have taken the answer from - How to correctly check if a camera is available? .

Note : I initially checked the VideoCapture object using the help method provided ie help(camera). help method in python helps to provide all the methods and attributes that are available for the object. It helps in debugging libraries and looking into methods and documentation quickly from console itself.

You can try reading from the capture device just once to get one frame. As you know, there would be another value given when attempting to read a frame, and that value tells us if the read was successful:

camera = cv2.VideoCapture(0)
success, frame = camera.read()
if not success:
    camera = cv2.VideoCapture(1)
    success, frame = camera.read()
    if not success:
        print("")
        print("There was a problem accessing your camera, please try again")
        print("Exiting now...")
        time.sleep(10)
        exit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM