Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:PeterL1n BackgroundMattingV2 Displayer

From Leeroopedia


Knowledge Sources
Domains Visualization, Realtime_Systems
Last Updated 2026-02-09 00:00 GMT

Overview

Concrete tool for interactive real-time frame display with FPS overlay and keyboard input provided by inference_webcam.py.

Description

Displayer wraps OpenCV's HighGUI functions to provide an interactive display window for real-time matting output. It combines three responsibilities:

  • Frame rendering via cv2.imshow in a named, resizable window
  • FPS tracking via an embedded FPSTracker that computes exponentially-weighted moving average FPS
  • Keyboard input via cv2.waitKey(1) returning the pressed key code

The FPSTracker helper class (lines 86-101) uses EMA with configurable ratio (default 0.5): fpsavg=ratiofpssample+(1ratio)fpsprev

When show_info is True, FPS and resolution are overlaid on the frame using cv2.putText.

Usage

Use in the webcam matting demo. Instantiate with a window title and dimensions, then call step(image) in the main loop.

Code Reference

Source Location

  • Repository: BackgroundMattingV2
  • File: inference_webcam.py
  • Lines: 86-120 (FPSTracker: 86-101, Displayer: 105-120)

Signature

class FPSTracker:
    def __init__(self, ratio: float = 0.5):
        """EMA-based FPS tracker."""
    def tick(self) -> Optional[float]:
        """Record a tick and return current EMA FPS estimate."""
    def get(self) -> Optional[float]:
        """Return last computed FPS."""

class Displayer:
    def __init__(
        self,
        title: str,
        width: Optional[int] = None,
        height: Optional[int] = None,
        show_info: bool = True
    ):
        """
        Args:
            title: Window title
            width: Window width (None for auto)
            height: Window height (None for auto)
            show_info: Overlay FPS and resolution text
        """

    def step(self, image: numpy.ndarray) -> int:
        """
        Display frame and return key press code.

        Args:
            image: BGR numpy array to display
        Returns:
            Key code from cv2.waitKey(1) & 0xFF
        """

Import

# Defined in inference_webcam.py (not a separate module)

I/O Contract

Inputs

Name Type Required Description
title str Yes OpenCV window title
width int No Window width in pixels
height int No Window height in pixels
show_info bool No Show FPS overlay (default True)
image numpy.ndarray Yes BGR uint8 frame to display

Outputs

Name Type Description
step() returns int Key code of pressed key (e.g., ord('q'), ord('b'))

Usage Examples

Interactive Matting Display

cam = Camera(width=1280, height=720)
dsp = Displayer('MattingV2', cam.width, cam.height, show_info=True)

# Background capture loop
while True:
    frame = cam.read()
    key = dsp.step(frame)
    if key == ord('b'):
        bgr = process_frame(frame)
        break
    elif key == ord('q'):
        exit()

# Matting loop
while True:
    frame = cam.read()
    result = process_matting(frame, bgr)
    key = dsp.step(result)
    if key == ord('q'):
        exit()
    elif key == ord('b'):
        break  # Recapture background

Related Pages

Implements Principle

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment