I read an mp4 video with Python 3.6.5 and OpenCV 3.4.1 and do some (resource-heavy) calculations with every single frame.
I have the total number for frames (length
) and the current one (count
) of course, so I’d like to give a progress update in my command line, but unfortunately it shows everything only after the whole process is finished.
while cap.isOpened(): ret, frame = cap.read() if ret: # Calculation stuff ... # Print the current status print("Frame %s/%s" % (count, length)) count = count + 1
Unfortunately it only prints ALL after the video file is completely processed. How can I print a “live” status of the current frame?
I use MINGW64 (Windows) as my Console
Answer
At the first look, this is due to the fact that you probably have control flow directives in your code (like break
, continue
, etc.), that prevent the interpreter from reaching the line.
Therefore you should make sure that either you print before these directives, your we can simply print at the top, like:
while cap.isOpened(): ret, frame = cap.read() print("Frame %s/%s" % (count, length)) count += 1 if ret: # Calculation stuff # ... pass
That being said, we can turn this capture procedure into a generator that prints the values, with a nice progress bar, like:
from tqdm import tqdm from cv2 import CAP_PROP_FRAME_COUNT def frame_iter(capture, description): def _itertor(): while capture.grab(): yield capture.retrieve()[1] return tqdm( _iterator(), desc=description, total=int(capture.get(CAP_PROP_FRAME_COUNT)), )
Then we can use it like:
for frame in frame_iter(capture, 'some description'): # process the frame pass
It will display a progress bar like demonstrated in the GitHub repository of tqdm
.