Check out all FFdecoder API's basic recipes here âž¶ to better understand these usage examples.
After going through following Usage Examples, Checkout more of its advanced configurations here âž¶
FFGear requires the deffcode library
FFGear API MUST have the deffcode library installed, along with a valid FFmpeg executable. Any failure in detection will raise ImportError/RuntimeError immediately.
# import required librariesfromvidgear.gearsimportFFGearimportcv2# open any valid video file with FFGearstream=FFGear(source="myvideo.mp4").start()# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# Show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
FFGear API directly supports any network stream URL that FFmpeg supports, including HTTP(s), RTSP/RTP, RTMP, and more.
Handling stalled network sources (New in v0.3.7)
A network source can stall forever (e.g. a killed UDP sender). Use read(timeout=seconds) to raise TimeoutError instead of waiting indefinitely for the next frame; stop() then safely tears down the stalled FFmpeg pipeline. After stop(), FFmpeg's exit code is available as stream.returncode(and its stderr tail as stream.stderr_tail with the -capture_stderr option). The source framerate is available as stream.framerate.
# import required librariesfromvidgear.gearsimportFFGearimportcv2# open an HTTP streamstream=FFGear(source="https://example.com/live/stream.mp4",logging=True).start()# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# Show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
This example assumes you already have an RTSP server running at the specified address.
# import required librariesfromvidgear.gearsimportFFGearimportcv2# force TCP transport for RTSPoptions={"-rtsp_transport":"tcp"}# [WARNING] replace with your actual RTSP addressstream=FFGear(source="rtsp://localhost:8554/mystream",logging=True,**options).start()# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# Show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
A HLS master playlist(.m3u8) usually carries several renditions of the same video at different resolutions, which FFmpeg exposes as embedded video streams of one input. Select the rendition explicitly with FFdecoder's -default_stream_indexes parameter.
Behaviour change with deffcode>=0.3.0(New in v0.3.8)
Without a selection, FFGear now decodes the first rendition in playlist order (often the lowest quality) and logs a warning, instead of the one FFmpeg picks automatically (usually the highest resolution).
Renditions are counted in playlist order: (1, 0) selects the second video stream (FFmpeg's 0:v:1), and source_video_streams metadata gives their number.
# import required librariesfromvidgear.gearsimportFFGearfromdeffcodeimportSourcerimportcv2# [WARNING] replace with your actual HLS master playlist URLsource="https://example.com/master.m3u8"# list each rendition's resolutionsourcer=Sourcer(source)count=sourcer.probe_stream().retrieve_metadata()["source_video_streams"]forindexinrange(count):metadata=sourcer.probe_stream(default_stream_indexes=(index,0)).retrieve_metadata()print(index,metadata["source_video_resolution"])# select the second rendition (applies `-map 0:v:1` automatically)options={"-default_stream_indexes":(1,0)}# open the selected renditionstream=FFGear(source=source,logging=True,**options).start()# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# Show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
FFGear internally implements the yt_dlp backend for seamlessly pipelining live video-frames and metadata from various streaming services like YouTube, Twitch, PeerTube, and many more âž¶. Enable it by setting stream_mode=True.
Supported Streaming Websites
The complete list of all supported Streaming Websites URLs can be found here âž¶
Accessing Stream Metadata
FFGear exposes a ytv_metadata attribute for accessing the stream's metadata as a JSON-like dict:
fromvidgear.gearsimportFFGearstream=FFGear(source="https://youtu.be/QDia3e12czc",stream_mode=True,logging=True).start()# access video metadatavideo_metadata=stream.ytv_metadataprint(video_metadata.keys())print(video_metadata["title"])
AV1 Dependency in FFmpeg
Most of the time, YouTube defaults to the AV1 video format. Therefore, you need an FFmpeg build that includes libdav1d for software AV1 decoding, which requires it to be compiled using the flag: --enable-libdav1d.
Check if you already have it: Run this command in your terminal or command prompt:
ffmpeg-decoders|grepdav1d
If you see V....D libdav1d, the library is installed and ready to use.
# import required librariesfromvidgear.gearsimportFFGearimportcv2# set desired quality as 720p and video decoder as `libdav1d`options={"STREAM_RESOLUTION":"720p","-vcodec":"libdav1d"}# Add YouTube Video URL as source and enable Stream Modestream=FFGear(source="https://youtu.be/QDia3e12czc",stream_mode=True,logging=True,**options).start()# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# Show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
If the Twitch user is offline, FFGear will throw ValueError.
# import required librariesfromvidgear.gearsimportFFGearimportcv2# set desired quality as 720poptions={"STREAM_RESOLUTION":"720p"}# Add Twitch stream URL as source and enable Stream Modestream=FFGear(source="https://www.twitch.tv/shroud",stream_mode=True,logging=True,**options).start()# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# Show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
# import required librariesfromvidgear.gearsimportFFGearimportcv2# set desired quality as 480poptions={"STREAM_RESOLUTION":"480p"}# Add PeerTube stream URL as source and enable Stream Modestream=FFGear(source="https://peertube.tv/w/q4GM7HcfUnqeBAj3urTUCv",stream_mode=True,logging=True,**options).start()# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# Show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
FFGear supports decoding frames in any FFmpeg pixel format via the frame_format parameter.
Use ffmpeg -pix_fmts terminal command to list all supported pixel formats.
Performance Mode — Faster Decoding via YUV420p
Ingesting frames as 12-bit YUV 4:2:0 instead of 24-bit BGR halves the bytes moving through the FFmpeg pipe. Enable -enforce_cv_patch to auto-convert yuv420p, nv12 and nv21 frames to BGR inside FFGear for seamless OpenCV compatibility. Other YUV pixel formats (4:2:2, 4:4:4, 10-bit) are returned as stacked planes.
# import required librariesfromvidgear.gearsimportFFGearimportcv2# IMPORTANT: enable OpenCV patch for YUV420p framesoptions={"-enforce_cv_patch":True}# stream YUV420p framesstream=FFGear(source="myvideo.mp4",frame_format="yuv420p",logging=True,**options).start()# loop overwhileTrue:# read OpenCV compatible YUV420p framesframe=stream.read()# check for frame if NoneTypeifframeisNone:break# {do something with frame here}# show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
# import required librariesfromvidgear.gearsimportFFGearimportcv2# stream grayscale framesstream=FFGear(source="myvideo.mp4",frame_format="gray",logging=True).start()# loop overwhileTrue:# read grayscale framesframe=stream.read()# check for frame if NonetypeifframeisNone:break# Show output windowcv2.imshow("Grayscale Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
Fastest RAW-to-Grayscale via -extract_luma
Every YUV/NV bytestream stores the Luma (Y) plane uncompressed at the top of each frame. The exclusive -extract_luma boolean attribute makes FFGear slice that Y-plane directly and hand back a 2D (H, W) grayscale ndarray — no colorspace conversion in FFmpeg, no cv2.cvtColor in Python. This is strictly faster than frame_format="gray", which still asks FFmpeg to do a yuv→gray conversion on every frame.
Combined with the reduced pipe-bytes of YUV 4:2:0 ingest, this is the fastest grayscale pipeline the API can produce.
# import required librariesfromvidgear.gearsimportFFGearimportcv2# enable direct Luma (Y-plane) extractionoptions={"-extract_luma":True}# stream Grayscale via YUV framesstream=FFGear(source="myvideo.mp4",frame_format="yuv420p",logging=True,**options).start()# loop overwhileTrue:# read grayscale framesframe=stream.read()# check for frame if NoneTypeifframeisNone:break# {do something with Luma (Y-plane) extracted grayscale frame here}# NOTE: If you do not need previewing frames, comment following lines# show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
Using DeFFcode's Sourcer API, you can easily use its enumerate_devices property object to enumerate all probed Camera Devices (connected to your system) as dictionary object with device indexes as keys and device names as their respective values:
# import the necessary packagesfromdeffcodeimportSourcerimportjson# streamsourcer=Sourcer("0").probe_stream()# enumerate probed devices as Dictionary object(`dict`)print(sourcer.enumerate_devices)# enumerate probed devices as JSON string(`json.dump`)print(json.dumps(sourcer.enumerate_devices,indent=2))
After running above python code, the resultant Terminal Output will look something as following on Windows machine:
FFGear API supports camera devices by index, just like OpenCV. Under the hood it uses platform-specific FFmpeg demuxers to capture the device feed by specifying its matching index value either as integer or string of integer type to its source parameter.
Requirement for Index based Camera Device Capturing in FFGear API
MUST have appropriate FFmpeg binaries, Drivers, and Softwares installed:
Internally, FFGear APIs achieves Index based Camera Device Capturing by employing some specific FFmpeg demuxers on different platforms(OSes). These platform specific demuxers are as follows:
Important: Kindly make sure your FFmpeg binaries support these platform specific demuxers as well as system have the appropriate video drivers and related softwares installed.
The source parameter value MUST be exactly the probed Camera Device index(Use DeFFcode's Sourcer APIenumerate_devices to list them).
The source_demuxer parameter value MUST be either None(also means empty) or "auto".
In this example we stream BGR24 video frames from Integrated Camera at index 0 on a Windows Machine:
Important Facts related to Camera Device Indexing
Camera Device indexes are 0-indexed. So the first device is at 0, second is at 1, so on. So if the there are n devices, the last device is at n-1.
Camera Device indexes can be of either integer(e.g. 0,1, etc.) or string of integer(e.g. "0","1", etc.)type.
Camera Device indexes can be negative(e.g. -1,-2, etc.), this means you can also start indexing from the end.
# import required librariesfromvidgear.gearsimportFFGearimportcv2# stream with "0" index source for BGR24 outputstream=FFGear(source="0",frame_format="bgr24",logging=True,).start()# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# Show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
# import required librariesfromvidgear.gearsimportFFGearimportcv2# define the Video Filter definition# horizontally flip and scale to half its original sizeoptions={"-vf":"hflip,scale=w=iw/2:h=ih/2"}stream=FFGear(source="myvideo.mp4",frame_format="bgr24",logging=True,**options).start()# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# Show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
Some sources carry several embedded video streams in a single input (such as an .mkv with two video tracks, or an HLS playlist with several renditions). By default, FFGear decodes the first video stream (skipping cover art) and logs a warning, instead of the one FFmpeg would pick automatically(default disposition, otherwise the highest resolution).
In this example we will decode only the second video stream of a source with FFdecoder's -default_stream_indexes parameter. To keep it runnable anywhere, the source is a lavfi graph that produces one input with two video streams(red 320x240 and blue 160x120). A file path such as foo.mkv works the same way.
New in v0.3.8
Stream selection requires deffcode>=0.3.0. Sources whose first video stream is cover art (attached picture) now decode their real video stream too, instead of raising RuntimeError.
Stream indexes are per type: 1 means the second video stream (same as FFmpeg's 0:v:1 specifier), not the absolute Stream #0:1. So audio streams placed before the video ones don't shift it.
A plain -map 0:v:1, or a -filter_complex using only [0:v:1](e.g. [0:v:1]hflip), selects the stream too. See DeFFcode's recipe âž¶ for more details.
# import required librariesfromvidgear.gearsimportFFGearimportcv2# one input with two embedded video streams (or use e.g. "foo.mkv")source="color=c=red:s=320x240:r=25:d=5[out0];color=c=blue:s=160x120:r=30:d=5[out1]"# select second video stream (`-map 0:v:1` is applied automatically)options={"-default_stream_indexes":(1,0)}# open the selected streamstream=FFGear(source=source,source_demuxer="lavfi",logging=True,**options).start()# FFdecoder metadata is available as a dictprint(stream.metadata["source_video_streams"])# 2print(stream.metadata["source_video_resolution"])# [160, 120]# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# Show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
Â
Using FFGear with Anamorphic, HDR and Rotated Videos¶
Some sources store non-square pixels(anamorphic DVD, HDV or broadcast video, e.g. 1440x1080 shown as 1920x1080) or HDR video (PQ/HLG transfer). FFGear decodes their pixels as stored, so frames look squeezed or washed out, and FFdecoder logs a warning about each (even with logging=False).
In this example we will check a video file (say foo.mkv) for both, using DeFFcode's Sourcer API source_video_sar and source_video_color_transfer metadata, and add the matching FFmpeg filters through the -vf parameter:
New in v0.3.8
These metadata keys and warnings require deffcode>=0.3.0. The same metadata is also available as a dict from FFGear's metadata attribute after initialization (retained after stop()).
Tone-mapping uses the zscale filter, so it needs FFmpeg built with libzimg(included in most static builds).
Color metadata is \"\" when the source doesn't tag it, and some FFmpeg versions report unknown(also \"\") for tags other versions print.
Portrait / rotated videos
Sources flagged as rotated by ±90° (e.g. phone portrait videos) are decoded upright, with width and height swapped (a 1280x720 source rotated by 90° gives (1280, 720, 3) frames). To get frames in their coded orientation instead, disable FFmpeg's auto-rotation with -noautorotate(not -autorotate 0):
# import required librariesfromvidgear.gearsimportFFGearfromdeffcodeimportSourcerimportcv2# probe source metadatametadata=Sourcer("foo.mkv").probe_stream().retrieve_metadata()filters=[]# tone-map HDR (PQ or HLG) to SDR BT.709ifmetadata["source_video_color_transfer"]in("smpte2084","arib-std-b67"):filters.append("zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,""tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv")# stretch non-square pixels to display aspect ratio (e.g. 1440x1080 to 1920x1080)ifmetadata["source_video_sar"]!=[1,1]:filters.append("scale=iw*sar:ih,setsar=1")options={"-vf":",".join(filters)}iffilterselse{}# open stream with the matching filtersstream=FFGear(source="foo.mkv",logging=True,**options).start()# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# Show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
FFGear supports Image Sequences such as Sequential(img%03d.png) and Glob pattern(*.png) in real-time.
Extracting Image Sequences from a video
You can use following FFmpeg command to extract sequences of images from a video file foo.mp4:
$ffmpeg-ifoo.mp4/path/to/image-%03d.png
The default framerate is 25 fps, therefore this command will extract 25 images/sec from the video file, and save them as sequences of images (starting from image-000.png, image-001.png, image-002.png up to image-999.png).
If there are more than 1000 frames then the last image will be overwritten with the remaining frames leaving only the last frame.
The default images width and height is same as the video.
How to start with specific number image?
You can use -start_number FFmpeg parameter if you want to start with specific number image:
# define `-start_number` such as `5`options={"-ffprefixes":["-start_number","5"]}# initialize and formulate the stream with define parametersstream=FFGear(source="/absolute/path/to/image-%03d.png",logging=True,**options).formulate()
Ensure source points to an absolute image sequence folder path
Furthermore, Use the exact filename pattern (for example, image-%03d.png) that was used when extracting the images. An incorrect or relative pattern may cause the FFGear API to raise a RuntimeError.
# import required librariesfromvidgear.gearsimportFFGearimportcv2stream=FFGear(source="/absolute/path/to/image-%03d.png",frame_format="bgr24",logging=True).start()# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# Show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
Bash-style globbing (* represents any number of any characters) is useful if your images are sequential but not necessarily in a numerically sequential order.
Ensure source points to an absolute image sequence folder path
The glob pattern may not be available on Windows FFmpeg builds.
# import required librariesfromvidgear.gearsimportFFGearimportcv2# define `-pattern_type glob` for accepting glob pattern via ffprefixesoptions={"-ffprefixes":["-pattern_type","glob"]}stream=FFGear(source="/absolute/path/to/*.png",# Glob patternframe_format="bgr24",logging=True,**options).start()# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# Show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
In this example we stream BGR24 video frames from looping video using FFGear API:
The -stream_loop flag is a high-level FFmpeg command that repeats the entire input file a specified number of times before any filtering occurs. The recommended way to use the -stream_loop flag with the FFGear API is through the -ffprefixes list attribute of the options dictionary parameter.
Possible -stream_loop values are integer values
Integer values > 0 specify the number of loops, 0 means no looping, and -1 enables infinite looping.
Using -stream_loop 3 will loop the video 4 times in total.
# import required librariesfromvidgear.gearsimportFFGearimportcv2# define loop 3 times (total 4 playbacks) via ffprefixesoptions={"-ffprefixes":["-stream_loop","3"]}# stream with suitable sourcestream=FFGear(source="myvideo.mp4",frame_format="bgr24",logging=True,**options).start()# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# Show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
The loop filter is used within an FFmpeg filtergraph (-filter_complex) to repeat a specific segment of video frames. In the FFGear API, it can be configured as an attribute of the options dictionary parameter.
This filter places all frames into memory (RAM), so applying trim filter first is strongly recommended. Otherwise, you might run out of memory.
Using loop filter for looping video
The filter accepts the following options:
loop: Sets the number of loops for integer values > 0. Setting this value to -1 results in infinite loops. Default is 0 (no loops).
size: Sets the maximum size in number of frames. Default is 0.
start: Sets the first frame of the loop. Default is 0.
You must often include setpts to fix the timestamps, otherwise frames may be dropped or playback may stutter.
Using loop=3 will loop the video 4 times in total.
# import required librariesfromvidgear.gearsimportFFGearimportcv2# define loop 4 times, each loop is 15 frames, each loop skips the first 25 framesoptions={"-filter_complex":"loop=loop=3:size=15:start=25,setpts=N/FRAME_RATE/TB"# Or use: `loop=3:15:25`}# stream with suitable sourcestream=FFGear(source="myvideo.mp4",frame_format="bgr24",logging=True,**options).start()# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# Show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close video streamstream.stop()
FFGear integrates seamlessly with OpenCV's VideoWriter() class to encode video frames into a multimedia file. However, it lacks fine-grained control over output quality, bitrate, compression, and other advanced parameters—features that are readily available with WriteGear API's Compression Mode.
You can use FFGear API's stream.metadata property object that dumps source Video's metadata information (as JSON string) to retrieve source framerate and resolution.
# import the necessary packagesfromvidgear.gearsimportFFGearimportcv2# stream with BGR24 pixel format outputstream=FFGear(source="myvideo.mp4",frame_format="bgr24",logging=True).start()# retrieve Metadata as dictmetadata_dict=stream.metadata# prepare OpenCV parametersFOURCC=cv2.VideoWriter_fourcc("M","J","P","G")FRAMERATE=metadata_dict["output_framerate"]FRAMESIZE=tuple(metadata_dict["output_frames_resolution"])# Define writer with parameters and suitable output filename for e.g. `output_foo.avi`writer=cv2.VideoWriter("output_foo.avi",FOURCC,FRAMERATE,FRAMESIZE)# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# writing BGR24 frame to writerwriter.write(frame)# let's also show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close streamstream.stop()# safely close writerwriter.release()
Since OpenCV expects BGR format frames in its cv2.write() method, therefore we need to convert RGB frames into BGR before encoding as follows:
# import the necessary packagesfromvidgear.gearsimportFFGearimportcv2# stream with RGB24 pixel format outputstream=FFGear(source="myvideo.mp4",frame_format="rgb24",logging=True).start()# retrieve Metadata as dictmetadata_dict=stream.metadata# prepare OpenCV parametersFOURCC=cv2.VideoWriter_fourcc("M","J","P","G")FRAMERATE=metadata_dict["output_framerate"]FRAMESIZE=tuple(metadata_dict["output_frames_resolution"])# Define writer with parameters and suitable output filename for e.g. `output_foo.avi`writer=cv2.VideoWriter("output_foo.avi",FOURCC,FRAMERATE,FRAMESIZE)# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the RGB frame here}# converting RGB24 to BGR24 frameframe_bgr=cv2.cvtColor(frame,cv2.COLOR_RGB2BGR)# writing BGR24 frame to writerwriter.write(frame_bgr)# let's also show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close streamstream.stop()# safely close writerwriter.release()
OpenCV also directly consumes GRAYSCALE frames in its cv2.write() method.
When writing a grayscale video, don't forget to add that flag (isColor=False) to the VideoWriter.
# import the necessary packagesfromvidgear.gearsimportFFGearimportcv2# stream with GRAYSCALE pixel format outputstream=FFGear(source="myvideo.mp4",frame_format="gray",logging=True).start()# retrieve Metadata as dictmetadata_dict=stream.metadata# prepare OpenCV parametersFOURCC=cv2.VideoWriter_fourcc("M","J","P","G")FRAMERATE=metadata_dict["output_framerate"]FRAMESIZE=tuple(metadata_dict["output_frames_resolution"])# Define writer with parameters and suitable output filename for e.g. `output_foo_gray.avi`writer=cv2.VideoWriter("output_foo_gray.avi",FOURCC,FRAMERATE,FRAMESIZE,isColor=False)# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the GRAYSCALE frame here}# writing GRAYSCALE frame to writerwriter.write(frame)# let's also show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close streamstream.stop()# safely close writerwriter.release()
With FFGear API, frames extracted with YUV pixel formats (yuv420p, nv12, nv21 etc.) are generally incompatible with OpenCV APIs. But you can make them easily compatible by using exclusive -enforce_cv_patch boolean attribute of its options dictionary parameter, which auto-converts yuv420p, nv12 and nv21 frames to BGR.
Let's encode YUV420p pixel-format frames with OpenCV's write() method:
You can also use nv12 or nv21 pixel-formats in the similar manner. Other YUV pixel-formats such as yuv422p(4:2:2 subsampling), yuv444p(4:4:4 subsampling) or 10-bit ones have no OpenCV conversion, and are returned as stacked planes.
# import the necessary packagesfromvidgear.gearsimportFFGearimportcv2# enable OpenCV patch for YUV420p framesoptions={"-enforce_cv_patch":True}# stream YUV420p framesstream=FFGear(source="myvideo.mp4",frame_format="yuv420p",logging=True,**options).start()# retrieve Metadata as dictmetadata_dict=stream.metadata# prepare OpenCV parametersFOURCC=cv2.VideoWriter_fourcc("M","J","P","G")FRAMERATE=metadata_dict["output_framerate"]FRAMESIZE=tuple(metadata_dict["output_frames_resolution"])# Define writer with parameters and suitable output filename for e.g. `output_foo_yuv.avi`writer=cv2.VideoWriter("output_foo_yuv.avi",FOURCC,FRAMERATE,FRAMESIZE)# loop overwhileTrue:# read OpenCV compatible YUV420 framesframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with frame here}# writing BGR frame to writerwriter.write(frame)# let's also show output windowcv2.imshow("Output",frame)# check for 'q' key if pressedkey=cv2.waitKey(1)&0xFFifkey==ord("q"):break# close output windowcv2.destroyAllWindows()# safely close streamstream.stop()# safely close writerwriter.release()
Â
Using FFGear with WriteGear API (Compression Mode)¶
High CPU Usage when chaining FFGear with WriteGear
When chaining FFGear with WriteGear, both FFmpeg processes (decoding + encoding) run as fast as your hardware allows with no artificial pacing between them. This causes the pipeline to max out your CPU to process the video in the shortest time possible, which may be undesirable.
You can mitigate this in two ways depending on your use case:
Pass the -re flag via FFGear's -ffprefixes parameter to force FFmpeg to read the input at its native framerate. This naturally paces the pipeline to real-time speed and drastically reduces CPU usage:
# force input to be read at native frameratestream=FFGear(source="foo.mp4",frame_format="bgr24",**{"-ffprefixes":["-re"]})
Pass -threads to both FFGear and WriteGear to cap the number of CPU threads each FFmpeg process may use. This leaves headroom for other system tasks:
# limit decoder to 2 threadsstream=FFGear(source="foo.mp4",frame_format="bgr24",**{"-threads":2})# limit encoder to 2 threadswriter=WriteGear(output="output_foo.mp4",**{"-input_framerate":fps,"-threads":2})
# import required librariesfromvidgear.gearsimportFFGearfromvidgear.gearsimportWriteGear# open source with FFGear and BGR framesstream=FFGear(source="myvideo.mp4",frame_format="bgr24",logging=True).start()# retrieve framerate from source JSON Metadata and pass it as `-input_framerate` # parameter for controlled framerateoutput_params={"-input_framerate":stream.metadata["source_video_framerate"]}# Define writer with default parameters and suitable# output filename for e.g. `output_foo.mp4`writer=WriteGear(output="output_foo.mp4",**output_params)# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# write frame to outputwriter.write(frame)# safely close streamstream.stop()# safely close writerwriter.close()
In WriteGear API, you can use rgb_mode parameter in write() class method to write RGB format frames instead of default BGR as follows:
# import required librariesfromvidgear.gearsimportFFGearfromvidgear.gearsimportWriteGear# open source with FFGear and RGB framesstream=FFGear(source="myvideo.mp4",frame_format="rgb24",logging=True).start()# retrieve framerate from source JSON Metadata and pass it as `-input_framerate` # parameter for controlled framerateoutput_params={"-input_framerate":stream.metadata["source_video_framerate"]}# Define writer with default parameters and suitable# output filename for e.g. `output_foo_rgb.mp4`writer=WriteGear(output="output_foo_rgb.mp4",**output_params)# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# write frame to outputwriter.write(frame,rgb_mode=True)# safely close streamstream.stop()# safely close writerwriter.close()
WriteGear API also directly consumes GRAYSCALE format frames in its write() class method.
# import required librariesfromvidgear.gearsimportFFGearfromvidgear.gearsimportWriteGear# open source with FFGear and GRAYSCALE framesstream=FFGear(source="myvideo.mp4",frame_format="gray",logging=True).start()# retrieve framerate from source JSON Metadata and pass it as `-input_framerate` # parameter for controlled framerateoutput_params={"-input_framerate":stream.metadata["source_video_framerate"]}# Define writer with default parameters and suitable# output filename for e.g. `output_foo_gray.mp4`writer=WriteGear(output="output_foo_gray.mp4",**output_params)# loop overwhileTrue:# read frames from streamframe=stream.read()# check for frame if NonetypeifframeisNone:break# {do something with the frame here}# write frame to outputwriter.write(frame)# safely close streamstream.stop()# safely close writerwriter.close()
Performance Mode — Faster Decoding via YUV420p
Ingesting frames as 12-bit YUV 4:2:0 instead of 24-bit BGR halves the bytes moving through the FFmpeg pipe. Enable -enforce_cv_patch to auto-convert yuv420p, nv12 and nv21 frames to BGR inside FFGear for seamless OpenCV compatibility. Other YUV pixel formats (4:2:2, 4:4:4, 10-bit) are returned as stacked planes.
WriteGear API also directly consume YUV(or basically any other supported pixel format) frames in its write() class method with its -input_pixfmt attribute in compression mode.
You can also use yuv422p(4:2:2 subsampling) or yuv444p(4:4:4 subsampling) instead for more higher dynamic ranges.
# import required librariesfromvidgear.gearsimportFFGearfromvidgear.gearsimportWriteGear# open source with FFGear stream for YUV420 outputstream=FFGear(source="myvideo.mp4",frame_format="yuv420p",logging=True).start()# retrieve framerate from source JSON Metadata and pass it as # `-input_framerate` parameter for controlled framerate# and also add input pixfmt as yuv420p output_params={"-input_framerate":stream.metadata["output_framerate"],"-input_pixfmt":"yuv420p"}# Define writer with default parameters and suitable# output filename for e.g. `output_foo_yuv.mp4`writer=WriteGear(output="output_foo_yuv.mp4",logging=True,**output_params)# loop overwhileTrue:# read OpenCV compatible YUV420p framesframe=stream.read()# check for frame if NoneTypeifframeisNone:break# {do something with the YUV420p frame here}# write frame to outputwriter.write(frame)# safely close streamstream.stop()# safely close writerwriter.close()
Fastest RAW-to-Grayscale via -extract_luma
Every YUV/NV bytestream stores the Luma (Y) plane uncompressed at the top of each frame. The exclusive -extract_luma boolean attribute makes FFGear slice that Y-plane directly and hand back a 2D (H, W) grayscale ndarray — no colorspace conversion in FFmpeg, no cv2.cvtColor in Python. This is strictly faster than frame_format="gray", which still asks FFmpeg to do a yuv→gray conversion on every frame.
Combined with the reduced pipe-bytes of YUV 4:2:0 ingest, this is the fastest grayscale pipeline the API can produce.
Similar to normal GRAYSCALE format frames, you can directly consume these frames in WriteGear API’s write() class method:
# import required librariesfromvidgear.gearsimportFFGearfromvidgear.gearsimportWriteGear# enable direct Luma (Y-plane) extractionoptions={"-extract_luma":True}# stream Grayscale via YUV framesstream=FFGear(source="myvideo.mp4",frame_format="yuv420p",logging=True,**options).start()# retrieve framerate from source JSON Metadata and pass it as `-input_framerate` # parameter for controlled framerateoutput_params={"-input_framerate":stream.metadata["source_video_framerate"]}# Define writer with default parameters and suitable# output filename for e.g. `output_foo_yuv_gray.mp4`writer=WriteGear(output="output_foo_yuv_gray.mp4",**output_params)# loop overwhileTrue:# read grayscale framesframe=stream.read()# check for frame if NoneTypeifframeisNone:break# {do something with Luma (Y-plane) extracted grayscale frame here}# write frame to outputwriter.write(frame)# safely close streamstream.stop()# safely close writerwriter.close()