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
Convert lecture videos to slides in one line. Takes an input of a directory containing your lecture videos and outputs a directory containing .PDF files containing the slides of each lecture.

Convert lecture videos to slides in one line. Takes an input of a directory containing your lecture videos and outputs a directory containing .PDF files containing the slides of each lecture.

Sidharth Anand 12 Sep 10, 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
PyAV is a Pythonic binding for the FFmpeg libraries.

PyAV is a Pythonic binding for the FFmpeg libraries. We aim to provide all of the power and control of the underlying library, but manage the gritty details as much as possible.

PyAV 1.8k Jan 01, 2023
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
获取斗鱼&虎牙&哔哩哔哩&抖音&快手等 48 个直播平台的真实流媒体地址(直播源)和弹幕,直播源可在 PotPlayer、flv.js 等播放器中播放。

获取斗鱼&虎牙&哔哩哔哩&抖音&快手等 48 个直播平台的真实流媒体地址(直播源)和弹幕,直播源可在 PotPlayer、flv.js 等播放器中播放。

乌帮图 5.6k Jan 06, 2023
Extracting frames from video and create video using frames

Extracting frames from video and create video using frames This program uses opencv library to extract the frames from video and create video from ext

1 Nov 19, 2021
video streaming userbot (vsu) based on pytgcalls for streaming video trought the telegram video chat group.

VIDEO STREAM USERBOT ✨ an another telegram userbot for streaming video trought the telegram video chat. Environmental Variables 📌 API_ID : Get this v

levina 6 Oct 17, 2021
A Advanced Anime Theme VC Video Player created for playing vidio in the voice chats of Telegram Groups

Yui Vidio Player A Advanced Anime Theme VC Video Player created for playing vidio in the voice chats of Telegram Groups Demo Setting up Add this Bot t

Achu biju 32 Sep 16, 2021
A youtube video link or id to video thumbnail python package.

Youtube-Video-Thumbnail A youtube video link or id to video thumbnail python package. Made with Python3

Fayas Noushad 10 Oct 21, 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
Video Object Segmentation(VOS) From Zero to HeroVideo Object Segmentation(VOS) From Zero to Hero

Video Object Segmentation(VOS) From Zero to Hero! Goal 1:train a two layers cnn model for vos. Finish! see model.py FFNet for more diteal.(2021.9.30)

1 Oct 22, 2021
A python program which converts images and video into excel spreadsheets.

image2excel A program which converts images and video into Excel spreadsheets. Usage examples can be found in examples Videos can take a long time to

Oscar Peace 2 Aug 09, 2021
I have baked a custom integration to control Eufy Security Cameras and access RTSP and P2P stream if possible.

I have baked a custom integration to control Eufy Security Cameras and access RTSP (real time streaming protocol) and P2P (peer to peer) stream if pos

Fuat Akgün 422 Jan 01, 2023
A Python library that simplifies working with video from soccer matches.

Match Video This is a Python library that simplifies working with video from soccer matches. It allows match video to be selected intuitively by perio

Grant Wenzinger 2 Jul 21, 2022
A self-hosted streaming platform with Discord authentication, auto-recording and more!

A self-hosted streaming platform with Discord authentication, auto-recording and more!

John Patrick Glattetre 331 Dec 27, 2022
Uncompress DEFLATE streams in pure Python

stream-deflate Uncompress DEFLATE streams in pure Python. Work in progress. This README serves as a rough design spec. Installation pip install stream

Michal Charemza 7 Oct 13, 2022
Image and video quality assessment

CenseoQoE: 视觉感知画质评价框架 项目介绍 图像/视频在编解码、传输和显示等过程中难免引入不同类型/程度的失真导致图像质量下降。图像/视频质量评价(IVQA)的研究目标是希望模仿人类视觉感知系统, 通过算法评估图片/视频在终端用户的眼中画质主观体验的好坏,目前在视频编解码、画质增强、画质监。

Tencent 133 Dec 20, 2022
A Telegram bot to convert videos into x265/x264 format via ffmpeg.

Video Encoder Bot A Telegram bot to convert videos into x265/x264 format via ffmpeg. Configuration Add values in environment variables or add them in

Adnan Ahmad 82 Jan 03, 2023
A multithreaded view bot for YouTube

Simple program to increase YouTube views written in Python.

Monirul Shawon 906 Jan 09, 2023
This application makes a webrtc video call with jitsi meet signaling

gstreamer-jitsi-meet This application makes a webrtc video call with jitsi meet signaling. Other end can be any jitsi meet app or web app. It doesn't

Linh 7 Apr 26, 2022