From 4ebb6170001641cb76e246aca53e22d3600551bd Mon Sep 17 00:00:00 2001 From: LaurentBerger Date: Wed, 20 Feb 2019 14:38:57 +0100 Subject: [PATCH] Check return value in python tutorial --- .../py_video_display.markdown | 48 +++++++++++-------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/doc/py_tutorials/py_gui/py_video_display/py_video_display.markdown b/doc/py_tutorials/py_gui/py_video_display/py_video_display.markdown index edd369a223dd..9cea2359c7ea 100644 --- a/doc/py_tutorials/py_gui/py_video_display/py_video_display.markdown +++ b/doc/py_tutorials/py_gui/py_video_display/py_video_display.markdown @@ -25,23 +25,27 @@ import numpy as np import cv2 as cv cap = cv.VideoCapture(0) - -while(True): +if not cap.isOpened(): + print("Cannot open camera") + exit() +while True: # Capture frame-by-frame ret, frame = cap.read() + # if frame is read correctly ret is True + if not ret: + print("Can't receive frame (stream end?). Exiting ...") + break # Our operations on the frame come here gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) - # Display the resulting frame - cv.imshow('frame',gray) - if cv.waitKey(1) & 0xFF == ord('q'): + cv.imshow('frame', gray) + if cv.waitKey(1) == ord('q'): break # When everything done, release the capture cap.release() -cv.destroyAllWindows() -@endcode +cv.destroyAllWindows()@endcode `cap.read()` returns a bool (`True`/`False`). If frame is read correctly, it will be `True`. So you can check end of the video by checking this return value. @@ -75,13 +79,17 @@ import cv2 as cv cap = cv.VideoCapture('vtest.avi') -while(cap.isOpened()): +while cap.isOpened(): ret, frame = cap.read() + # if frame is read correctly ret is True + if not ret: + print("Can't receive frame (stream end?). Exiting ...") + break gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) - cv.imshow('frame',gray) - if cv.waitKey(1) & 0xFF == ord('q'): + cv.imshow('frame', gray) + if cv.waitKey(1) == ord('q'): break cap.release() @@ -123,20 +131,20 @@ cap = cv.VideoCapture(0) # Define the codec and create VideoWriter object fourcc = cv.VideoWriter_fourcc(*'XVID') -out = cv.VideoWriter('output.avi',fourcc, 20.0, (640,480)) +out = cv.VideoWriter('output.avi', fourcc, 20.0, (640, 480)) -while(cap.isOpened()): +while cap.isOpened(): ret, frame = cap.read() - if ret==True: - frame = cv.flip(frame,0) + if not ret: + print("Can't receive frame (stream end?). Exiting ...") + break + frame = cv.flip(frame, 0) - # write the flipped frame - out.write(frame) + # write the flipped frame + out.write(frame) - cv.imshow('frame',frame) - if cv.waitKey(1) & 0xFF == ord('q'): - break - else: + cv.imshow('frame', frame) + if cv.waitKey(1) == ord('q'): break # Release everything if job is finished