So i purposely put a file in the cv2.VideoCapture() that doesn't exist in my computer to test the try-catch system i've put into my code but for some reason it still gives off the same error it gives when i didn't put a try-catch into my code. how do i fix this??
code:
import numpy as np
import cv2
try:
cap = cv2.VideoCapture('trial.mkv')
while (cap.isOpened()):
ret, frame = cap.read()
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
except:
print("no file found")
error:
[ERROR:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-cff9bdsm\opencv\modules\videoio\src\cap.cpp (142) cv::VideoCapture::open VIDEOIO(CV_IMAGES): raised OpenCV exception:
OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-cff9bdsm\opencv\modules\videoio\src\cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): trial.mkv in function 'cv::icvExtractPattern'
When an error is caught by the try/except
statement and stderr
msg is still printed it just means that the library is simply sending all the error messages to the stderr
.
OpenCV
library was known to have this problems and there are ways around it. You should read the detailed answers here - OpenCv error and How to stop OpenCV error message from printing in Python
I definitely agree @AzyCrw4282 but I also point-out two issues on your code, therefore I'm writing as an answer.
except cv2.error as error
to catch the error: except cv2.error as error: print("[Error]: {}".format(error))
Result:
[Error]: OpenCV(4.0.0) /Users/opencv/modules/highgui/src/window.cpp:350: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow' Process finished with exit code 0
Even if I give an invalid video file:
OpenCV: Couldn't read video stream from file "trial.mkv" Process finished with exit code 0
Actually try-catch
block is working if you use except cv2.error as error
.
Issue #2: Please always check frame
For instance: If you want to stop the application use:
if frame is None break
or
ret, frame = cap.read() if ret: cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break
if frame returns then display
Full code:
import cv2
try:
cap = cv2.VideoCapture('dread.mp4')
while cap.isOpened():
ret, frame = cap.read()
if ret:
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
except cv2.error as error:
print("[Error]: {}".format(error))
cap.release()
cv2.destroyAllWindows()
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.