Implementation:PeterL1n BackgroundMattingV2 VideoWriter
Appearance
| Knowledge Sources | |
|---|---|
| Domains | Video_Processing, Output_Management |
| Last Updated | 2026-02-09 00:00 GMT |
Overview
Concrete tool for writing PyTorch tensor batches to MP4 video files provided by inference_video.py.
Description
VideoWriter wraps OpenCV's cv2.VideoWriter to accept PyTorch float tensor batches and convert them to video frames. The conversion pipeline multiplies by 255, casts to uint8, permutes from (B,C,H,W) to (B,H,W,C), converts RGB to BGR, and writes each frame to an MP4 file using the mp4v codec.
Usage
Use when saving matting output as video files. One instance per output type (composite, alpha, foreground, error, refinement map).
Code Reference
Source Location
- Repository: BackgroundMattingV2
- File: inference_video.py
- Lines: 80-90
Signature
class VideoWriter:
def __init__(
self,
path: str, # Output MP4 file path
frame_rate: float, # Video frame rate
width: int, # Frame width
height: int # Frame height
):
"""Creates cv2.VideoWriter with mp4v codec."""
def add_batch(self, frames: Tensor) -> None:
"""
Write a batch of frames to the video.
Args:
frames: Tensor[B, 3, H, W] float32, range 0-1, RGB
"""
Import
# Defined in inference_video.py (not a separate module)
# Used internally within the video inference script
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| path | str | Yes | Output MP4 file path |
| frame_rate | float | Yes | Target video frame rate |
| width | int | Yes | Frame width in pixels |
| height | int | Yes | Frame height in pixels |
| frames | Tensor[B,3,H,W] | Yes | Batch of RGB float tensors (0-1) to write |
Outputs
| Name | Type | Description |
|---|---|---|
| .mp4 file | File | MP4 video file at specified path |
Usage Examples
Writing Matting Output
# Create writers for each output type
pha_writer = VideoWriter('output/pha.mp4', vid.frame_rate, width, height)
com_writer = VideoWriter('output/com.mp4', vid.frame_rate, width, height)
# In inference loop
with torch.no_grad():
for src, bgr in dataloader:
pha, fgr = model(src.cuda(), bgr.cuda())[:2]
com = fgr * pha + tgt_bgr * (1 - pha)
pha_writer.add_batch(pha)
com_writer.add_batch(com)
Related Pages
Implements Principle
Page Connections
Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment