Created
November 24, 2022 18:33
-
-
Save ecatanzani/cd9b1ab7437ad3bd951b30304cee4165 to your computer and use it in GitHub Desktop.
ffmpeg video reader - test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import numpy | |
import subprocess as sp | |
def get_video_info(video_file): | |
cap = cv2.VideoCapture(video_file) | |
framerate = cap.get(5) #frame rate | |
# Get resolution of input video | |
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) | |
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) | |
# Release VideoCapture - it was used just for getting video resolution | |
cap.release() | |
return width, height, framerate | |
FFMPEG_BIN = "ffmpeg" # on Linux ans Mac OS | |
buffer_size = 10**8 | |
video_file = '/mnt/Downloads/MOT17-13-SDP-raw.mp4' | |
width, height, framerate = get_video_info(video_file) | |
print(f'[INFO] Video file: {video_file} {width}x{height} - {framerate} FPS') | |
command = [FFMPEG_BIN, | |
'-i', video_file, | |
'-f', 'image2pipe', | |
'-pix_fmt', 'rgb24', | |
'-vcodec', 'rawvideo', '-'] | |
pipe = sp.Popen(command, stdout = sp.PIPE, bufsize=buffer_size) | |
# Read | |
fourcc = cv2.VideoWriter_fourcc(*'mp4v') | |
video = cv2.VideoWriter('video.avi', fourcc, framerate, (width, height)) | |
while True: | |
# read 420*360*3 bytes (= 1 frame) | |
raw_image = pipe.stdout.read(width*height*3) | |
# transform the byte read into a numpy array | |
image = numpy.fromstring(raw_image, dtype='uint8') | |
image = cv2.cvtColor(image.reshape((height,width,3)), cv2.COLOR_BGR2RGB) | |
# Save image to output video stream | |
video.write(image) | |
# throw away the data in the pipe's buffer. | |
pipe.stdout.flush() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment