Ffmpeg videostream - High speed video frame access in Python, using FFmpeg and FFshow

Overview

FFmpeg VideoStream

High speed video frame access in Python, using FFmpeg and FFshow

This script requires:

Basic Usage

from ffmpeg_videostream import VideoStream

video = VideoStream("my_video.mp4")
video.open_stream()
while True:
    eof, frame = video.read()
    if eof: break

Methods

VideoStream (path, color, bytes_per_pixel)

  • path : The path to your video file as a string : '/videos/my_video.mp4'
  • color : The pixel format you are requesting from FFmpeg : By default 'yuv420p' (recommended)
  • bytes_per_pixel : The number of bytes (not bits) that your pixel format uses to store a pixel : By default 1.5 (as per 'yuv420p')

Note: By setting color and bytes_per_pixel you can ingest video into any pixel format ffmpeg supports. However, most source files and use cases will benefit by using the default configuration and converting the pixel data to other formats as needed. (See 'Examples')


.config (start_hms, end_hms, crop_rect, output_resolution)

  • start_hms : Read frames starting from this time* in the video : ("seek" equivalent)
  • end_hms : Stop reading frames at this time* in the video
  • crop_rect : Accepts a list / tuple as [x, y, width, height] for cropping the video's input
  • output_resolution : Accepts a list / tuple as [width, height] declaring the final scaling of the video, forcing the output to match this resolution

Note: When crop_rect is set, it overrides the .shape() of the final output resolution. This is only important to note if you were to request the crop in a separate call to .config(), AFTER requesting the output_resolution be changed in a previous call. For example...

video.config(output_resolution=(1280, 720))
video.config(crop_rect=(0,0,720,480))
# Hey, just don't do it that way... huh?

.open_stream (showinfo, loglevel, hide_banner, silence_even_test)

  • showinfo : When True invokes ffmpeg's 'showinfo' filter providing details about each frame as it is read.
  • loglevel : Sets ffmpeg's 'stderr' output to include/exclude certain data being printed to console.
  • hide_banner : Shows/hides ffmpeg's startup banner.
    • Note: Various 'loglevel' settings implicitly silence this banner. When 'showinfo' is invoked no 'loglevel' output will be printed to console.
  • silence_even_test : When True suppresses console warnings that an invalid resolution has been requested.

Note: Invoking 'showinfo' reduces the maximum speed raw frame data can ingest. In most rendering instances the speed reduction is immeasurable due to other blocking processes. But for the raw acquisition of frames it can be significant.


.read ()

Returns an end-of-file boolean flag, followed by a single frame's worth of the raw bytestream from the video. The bytestream data returned is in no way prepared, decoded, or shaped into an array structure. A simple example for converting YUV420p to BGR using numpy and OpenCV is provided:

    eof, frame = video.read()
    arr = np.frombuffer(frame, np.uint8).reshape(video.shape[1] * 1.5, video.shape[0])
    bgr = cv2.cvtColor(arr, cv2.COLOR_YUV2BGR_I420)

Note: The VideoStream class can be initialized to request BGR output directly from ffmpeg, but it is slower to acquire a 24-bit RGB / BGR encoded frame than to acquire the 12-bit YUV pixels and convert them.


.shape () : Returns the final output resolution of the video in a list : [width, height]


.eof () : Boolean indicating whether the end of the file has been reached


.close () : Closes the open stream


.showinfo (key)

current_frame_number = video.showinfo("n")

Note: All requests return None if showinfo=True was not set during open_stream()


.inspect (attrib)

  • Returns a dict() containing all data found in the 'video' stream of ffprobe if no attrib declared.
  • .inspect("something") returns the value of "something" from the dict() or None if not found.

Examples

Timing raw frame access speed

from ffmpeg_videostream import VideoStream
from time import time

video = VideoStream("my_video.mp4")
video.open_stream()
frames = 0

print("\r\nReading VideoStream...")
timer = time()
while True:
    eof, frame = video.read()
    if eof: break
    frames += 1
timer = time() - timer

print(f"\r\nRead {frames} frames at {video.shape()} resolution from '{video.path}' in {round(timer, 3)} seconds.")
print(f"Effective read rate of {round(frames / timer)} frames per second.")

Rendering output to PyGame

from ffmpeg_videostream import VideoStream
import numpy as np
import cv2
import pygame

path = 'my_video.mp4'

video = VideoStream(path)
video.open_stream()

pygame.init()
screen = pygame.display.set_mode(video.shape())

while True:
    eof, frame = video.read()
    # Shape bytestream into YUV 4:2:0 numpy array, then use OpenCV to convert from YUV to BGR.
    arr = np.frombuffer(frame, np.uint8).reshape(video.shape()[1] * 3//2, video.shape()[0])
    img = cv2.cvtColor(arr, cv2.COLOR_YUV2BGR_I420)

    img = pygame.image.frombuffer(img, video.shape(), "BGR")
    screen.blit(img, (0, 0))    # Copy img onto the screen at coordinates: x=0, y=0
    pygame.display.update()
    pygame.event.pump()     # Makes pygame's window draggable / non-blocking.
    if eof:
        break
Video stream image stacking -- live version

video stream image stacking v2 -- live version A very simple streamed video image stacking code! Version 2.1 left mouse click to select a small region

Chakravarthy Mathiazhagan 1 Jan 03, 2022
Python based script to operate FFMPEG.

FMPConvert Python based script to operate FFMPEG. Ver 1.0 -- 2022.02.08 Feature ✅ Maximum compatibility: Third-party dependency libraries unused ✅ Che

cybern000b 1 Feb 28, 2022
Tweet stream in OBS browser source

OBS-Twitter-Stream OBSなどの配信ソフトのブラウザソースで特定のキーワードを含んだツイートを表示します 使い方 使い方については以下のwikiを御覧ください https://github.com/CubeZeero/OBS-Twitter-Stream/wiki ダウンロード W

Cube 23 Dec 18, 2022
Jio TV Server - Watch TV right from your laptop

Jio-PyServer Jio TV - Python Server Watch TV right from your laptop! Requirements: Python 3.X Internet Access A Jio Account Known Issues: Channel Stre

Elvis Tony 11 Apr 05, 2022
All the code in these repos was created and explained by HashLips on the main YouTube channel.

Welcome to HashLips 👄 All the code in these repos was created and explained by HashLips on the main YouTube channel. To find out more please visit: ?

HashLips 6.7k Jan 06, 2023
Ffmpeg videostream - High speed video frame access in Python, using FFmpeg and FFshow

FFmpeg VideoStream High speed video frame access in Python, using FFmpeg and FFshow This script requires: Karl Kroening's 'ffmpeg-python' library. (ht

3 Sep 29, 2022
Become a virtual character with just your webcam!

Become a virtual character with just your webcam!

Rich 300 Jan 03, 2023
A pure python media player that can be used in AI media API development.

A pure python media player that can be used in AI media API development.

YDOOK 1 Dec 04, 2021
Terminal-Video-Player - A program that can display video in the terminal using ascii characters

Terminal-Video-Player - A program that can display video in the terminal using ascii characters

15 Nov 10, 2022
This is a tool for making a every day video if you take a picture of you everyday

Face-Everyday-Maker-Studio Description This project is a tool for making a everyday video, which is timelapse video or slides video, of images but for

John A Betancourt G 9 Sep 06, 2022
High-performance cross-platform Video Processing Python framework powerpacked with unique trailblazing features :fire:

Releases | Gears | Documentation | Installation | License VidGear is a High-Performance Video Processing Python Library that provides an easy-to-use,

Abhishek Thakur 2.6k Dec 28, 2022
基于BililiveRecorder 的集群录播客户端

高度自动化的录播服务端! 一、项目介绍 1、介绍 这是NGlive的录播服务器集群的客户端部分实现代码,它可以自动化的进行录制-压制-上传-通知,同时流程高度可自定义,并且可以任意受中心服务器的调度,有一定的错误修复能力。可以保证长期稳定的运行。 2、基本功能 这个客户端集 录制、转码压制、上传为一

NGWORKS 7 Jul 10, 2022
Python application that can be used to generate video thumbnail for mp4 and mkv file types.

Thumbnail Generator 🎬 What is This This is a Python application that can be used to generate video thumbnail for mp4 and mkv file types. Installation

Tharindu N. 13 Jan 03, 2023
Add the dislike count back to my YouTube videos via a comment containing that information.

YouTube Dislikes Forrest Knight Python Version 3.0+ Only use if you know what the code actually does. I'm not responsible for your use of this code in

Forrest Knight 155 Dec 19, 2022
A tool to fuck a video/audio quality using FFmpeg

Media quality fucker A tool to fuck a video/audio quality using FFmpeg How to use Download the source Download Python Extract FFmpeg Put what you want

Maizena 8 Jan 25, 2022
Spotify playlist video generator

This program creates a video version of your Spotify playlist by using the Spotify API and YouTube-dl.

0 Mar 03, 2022
Rembg Video Virtual Green Screen Edition

Rembg Virtual Greenscreen Edition is a tool to create a green screen matte for videos

Tim Scarfe 217 Jan 06, 2023
Media player custom component which works with MQTT.

Media player custom component which works with MQTT. I designed this to specifically work with a ESP32 which i used to control a speakercraft amp.

2 Feb 10, 2022
Automatic video generator for local news

Automatic video generator for local news

Gabriel Monteiro 2 Jan 11, 2022
Python retagging utility for mkv files using mkvmerge.

pyretag A python script to retag mkv files. Setting Up pip install pyfiglet pip install rich Move the mkv files to input folder.

25 Dec 04, 2022