简体   繁体   中英

In Python+OpenCV, how do I test cv.CaptureFromFile return value for failure?

I'm using the Python bindings to OpenCV. If I pass a nonexistent (or bad) file to cv.CaptureFromFile(), how do I test the return value for failure? In the C/C++ API, cvCaptureFromFile() returns NULL. In Python, I get: "<Capture (nil)>"

How do I test for "<Capture (nil)>"?

capture = cv.CaptureFromFile( infilename )
# capture != None on failure so this doesn't work.
if capture is None :
    print "Unable to open \"{0}\"".format( infilename )
    sys.exit(1) 

I could use os.stat() but that wouldn't help with cases where the file exists but OpenCV genuinely cannot decode the file (eg, codec error).

Try to read one frame using cv.QueryFrame(capture). if it returns None, it's failed to open the stream.

If you test it as a boolean, it should work. Try this:

capture = cv.CaptureFromFile( infilename )
if not capture:
    print "Unable to open \"{0}\"".format( infilename )
    sys.exit(1) 

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