A small Python library that wraps common video I/O tasks — reading metadata, iterating frames, and writing frames back to a video file — behind a single, consistent interface across four backends: OpenCV, MoviePy, PyAV, and decord.
- Read video metadata (width, height, FPS, frame count, duration) with
video_info(). - Stream frames from a video one at a time with
video_frames(), without loading the whole file into memory. - Write frames to a new video file with
frames_to_video(). - Create an OpenCV
VideoWritermatching the properties of an existing video withvideo_writer_like(). - Swap between
"opencv","moviepy","pyav", and"decord"readers/writers per call, so you can pick whichever backend performs best or supports your codec.
pip install opencv-python-headless moviepy decord avThis library is designed to be used as a git submodule:
git submodule add https://github.com/rendicahya/python_video.gitReturns a dictionary containing information about a video:
widthheightfpsn_framesduration(in seconds)
Available readers are "opencv" (default), "moviepy", "pyav", and "decord". path can be either a string or a pathlib's PosixPath.
Usage:
frompython_videoimportvideo_infofrompathlibimportPathpath="/path/to/video"# or:# path = Path("/path/to/video")info=video_info(path, reader="opencv")Returns a frame generator from the specified video. Available readers are "opencv" (default), "moviepy", "pyav", and "decord".
Usage:
frompython_videoimportvideo_framespath="/path/to/video"# or:# path = Path("/path/to/video")frames=video_frames(path, reader="opencv")
forframeinframes:
# ...To grab all frames at once, cast to a list. This should be avoided, though, as it inefficiently loads all frames onto memory:
frames=list(video_frames(path))Returns an OpenCV video writer with the same properties as the specified video.
Usage:
frompython_videoimportvideo_writer_likesrc_path="/path/to/src-video.mp4"# or:# src_path = Path("/path/to/src-video.mp4")dst_path="/path/to/dst-video.mp4"# or:# dst_path = Path("/path/to/dst-video.mp4")writer=video_writer_like(src_path, target=dst_path)
forframeinframes:
writer.write(frame)
writer.release()Writes image frames to a video file. Available writers are "opencv" (default), "moviepy", and "pyav".
Usage:
path="/path/to/target/video"# or:# path = Path("/path/to/target/video")frames_to_video(frames, path, writer="opencv", fps=30, codec="mp4v")Combining with video_info() and video_frames() to read frames from a video and write them to another video:
src_path="/path/to/target/video-src.mp4"# or src_path = Path("/path/to/target/video-src.mp4")info=video_info(src_path)
frames=video_frames(src_path)
dst_path="/path/to/target/video-dst.mp4"# or dst_path = Path("/path/to/target/video-dst.mp4")frames_to_video(frames, dst_path, writer="opencv", fps=info["fps"], codec="mp4v")Licensed under the MIT License.