Implementation:PeterL1n BackgroundMattingV2 Camera
| Knowledge Sources | |
|---|---|
| Domains | Video_Processing, Realtime_Systems |
| Last Updated | 2026-02-09 00:00 GMT |
Overview
Concrete tool for threaded webcam frame capture provided by inference_webcam.py.
Description
Camera wraps cv2.VideoCapture with a background reading thread. The thread continuously reads frames and stores the latest one behind a threading.Lock. The main thread calls read() to get the most recent frame without blocking on camera I/O. The camera's resolution is configured via OpenCV properties, and the actual negotiated resolution is stored in width and height attributes.
Usage
Use in the real-time webcam matting demo. Instantiate once at startup with desired resolution, then call read() in the matting loop.
Code Reference
Source Location
- Repository: BackgroundMattingV2
- File: inference_webcam.py
- Lines: 57-83
Signature
class Camera:
def __init__(
self,
device_id: int = 0,
width: int = 1280,
height: int = 720
):
"""
Args:
device_id: Camera device index (default 0)
width: Requested frame width
height: Requested frame height
Attributes:
width: int - Actual negotiated frame width
height: int - Actual negotiated frame height
"""
def read(self) -> numpy.ndarray:
"""Returns latest frame as BGR numpy array (thread-safe copy)."""
def __exit__(self, exec_type, exc_value, traceback) -> None:
"""Releases the camera capture."""
Import
# Defined in inference_webcam.py (not a separate module)
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| device_id | int | No | Camera device index (default 0) |
| width | int | No | Requested frame width (default 1280) |
| height | int | No | Requested frame height (default 720) |
Outputs
| Name | Type | Description |
|---|---|---|
| read() | numpy.ndarray | Latest camera frame as BGR uint8 array (H, W, 3) |
| .width | int | Actual camera width |
| .height | int | Actual camera height |
Usage Examples
Webcam Matting Loop
cam = Camera(device_id=0, width=1280, height=720)
print(f"Camera: {cam.width}x{cam.height}")
# Background capture
frame = cam.read()
bgr = cv2_frame_to_cuda(frame) # Convert BGR numpy to CUDA tensor
# Matting loop
while True:
frame = cam.read()
src = cv2_frame_to_cuda(frame)
pha, fgr = model(src, bgr)[:2]
# ... display result ...