Skip to content

Instantly share code, notes, and snippets.

@knowblesse
Created May 3, 2022 04:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save knowblesse/ac0e9055f6c3fdc84f7ae4c6c3bf7f07 to your computer and use it in GitHub Desktop.
Save knowblesse/ac0e9055f6c3fdc84f7ae4c6c3bf7f07 to your computer and use it in GitHub Desktop.
Testing code for sequentially reading a frame from a video.
from time import time
import cv2 as cv
import numpy as np
from pathlib import Path
videoPath = Path('/home/knowblesse/VCF/butter/Sample/TestVideo_Blinking.avi')
# Option 1 : OpenCV calling all frames
cap = cv.VideoCapture(str(videoPath))
startTime = time()
EOF = False
fr = 0
while not EOF:
fr += 1
ret, frame = cap.read()
if not ret:
EOF = True
print(f'Option 1 Time {time() - startTime}')
# Option 2 : ffmpeg methods
import ffmpeg
videoObject = ffmpeg.input(str(videoPath))
probe = ffmpeg.probe(str(videoPath))
info = [stream for stream in probe['streams'] if stream['codec_type'] == 'video']
info = info[0]
height = int(info['height'])
width = int(info['width'])
## Option 2-1 : ffmpeg : Directly reading bgr image from yuv420p video
# Conversion is done inside the ffmpeg side
out = (
ffmpeg
.input(str(videoPath))
.output('pipe:', format='rawvideo', pix_fmt = 'bgr24')
.global_args('-loglevel', 'error', '-hide_banner')
.run_async(pipe_stdout=True)
)
startTime = time()
EOF = False
fr = 0
while not EOF:
fr += 1
frame = out.stdout.read(int(height * width * 3))
if not len(frame):
EOF = True
else:
img = np.frombuffer(frame, np.uint8).reshape([height, width, 3])
print(f'Option 2-1 Time {time() - startTime}')
# Option 2-2 : ffmpeg : Reading yuv420p video and converting from the opencv side
# Credit to roninpawn
out = (
ffmpeg
.input(str(videoPath))
.output('pipe:', format='rawvideo', pix_fmt = 'yuv420p')
.global_args('-loglevel', 'error', '-hide_banner')
.run_async(pipe_stdout=True)
)
startTime = time()
EOF = False
fr = 0
while not EOF:
fr += 1
frame = out.stdout.read(int(height * width * 1.5))
if not len(frame):
EOF = True
else:
img = np.frombuffer(frame, np.uint8).reshape([height*3//2, width])
img = cv.cvtColor(img, cv.COLOR_YUV2BGR_I420)
print(f'Option 2-2 Time {time() - startTime}')
# Option 2-3 : ffmpeg : FFdecoder
# Credit to deffcode
from deffcode import FFdecoder
decoder = FFdecoder(str(videoPath), frame_format="bgr24").formulate()
startTime = time()
fr = 0
for frame in decoder.generateFrame():
fr += 1
img = frame
print(f'Option 2-3 Time {time() - startTime}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment