Background Matting v2

repository·master·Indexed 27 days ago

https://github.com/peterl1n/backgroundmattingv2

A high-resolution, real-time background matting system capable of 4K 30fps and HD 60fps. It uses a pre-captured background image to isolate subjects and supports multiple runtimes including PyTorch, TorchScript, TensorFlow, and ONNX. The system includes the MattingRefine model with configurable refinement modes (sampling, thresholding, full) and provides scripts for image, video, and webcam inference.

Tokens
1.9K
Snippets
2
Records
10
Agent score
93%

What's inside Background Matting v2

  1. Run matting demos with provided scripts

    master

    The repository includes several Python scripts for experimenting with the model:

    • inference_images.py: Performs matting on a directory of images.
    • inference_video.py: Performs matting on a video file.
    • inference_webcam.py: Provides an interactive matting demo using your webcam.
    • inference_speed_test.py: Measures the tensor throughput of the model to verify real-time capability.

    Note on Performance: The inference_video.py script is not optimized for real-time use because video encoding/decoding lacks hardware acceleration and parallelization. For production real-time performance, you must implement hardware encoding/decoding and parallel frame loading to the GPU.

  2. Configure training for the model

    master

    To train the model, you must configure data_path.pth to point to your dataset.

    Following the original paper's methodology:

    1. Use train_base.pth to train only the base model until convergence.
    2. Use train_refine.pth to train the entire network end-to-end.
  3. Run inference using ONNX (Experimental)

    master

    The model can be used with onnxruntime. Note that ONNX inference is reported to be slower than PyTorch/TorchScript. Pre-exported models are available for HD and 4K configurations.

    Python Example:

    import onnxruntime
    import numpy as np
    
    sess = onnxruntime.InferenceSession('PATH_TO_MODEL.onnx')
    
    src = np.random.normal(size=(1, 3, 1080, 1920)).astype(np.float32)
    bgr = np.random.normal(size=(1, 3, 1080, 1920)).astype(np.float32)
    
    pha, fgr = sess.run(['pha', 'fgr'], {'src': src, 'bgr': bgr})

    Compatibility Note: The architecture uses cropping and patch replacement which may cause issues in some backends. The provided ONNX models use roi_align for cropping and scatter_element for replacing patches. Other configurations can be exported using export_onnx.py.

  4. Use the model with PyTorch, TorchScript, TensorFlow, or ONNX

    master

    The Background Matting v2 model is compatible with multiple runtimes. You can integrate it into your workflow using:

    • PyTorch
    • TorchScript
    • TensorFlow
    • ONNX

    For detailed integration instructions, refer to the doc/model_usage.md file.

  5. Run inference using PyTorch (Research)

    master

    For research purposes, you can use the architecture defined in the /model directory. You must manually instantiate the MattingRefine class and load the state dictionary from a checkpoint file.

    Requirements:

    • Access to the model module in the repository.
    • A trained checkpoint file (.pth).
    import torch
    from model import MattingRefine
    
    device = torch.device('cuda')
    precision = torch.float32
    
    model = MattingRefine(backbone='mobilenetv2',
                          backbone_scale=0.25,
                          refine_mode='sampling',
                          refine_sample_pixels=80_000)
    
    model.load_state_dict(torch.load('PATH_TO_CHECKPOINT.pth'))
    model = model.eval().to(precision).to(device)
    
    src = torch.rand(1, 3, 1080, 1920).to(precision).to(device)
    bgr = torch.rand(1, 3, 1080, 1920).to(precision).to(device)
    
    with torch.no_grad():
        pha, fgr = model(src, bgr)[:2]
  6. Configure MattingRefine model arguments

    master

    The following arguments control the quality and computation trade-offs of the model:

    • backbone_scale (float, default: 0.25): The downsampling scale for the backbone. For 1920x1080 input with 0.25, the backbone operates at 480x270.
    • refine_mode (string, default: sampling, options: [sampling, thresholding, full]):
      • sampling: Refines a fixed maximum amount of pixels defined by refine_sample_pixels. Best for live applications with fixed computation bounds.
      • thresholding: Refines all pixels with errors above refine_threshold. Best for image editing where quality is prioritized over speed.
      • full: Refines the entire image. Used for debugging only.
    • refine_sample_pixels (int, default: 80,000): The fixed amount of pixels to refine when refine_mode is sampling.
    • refine_threshold (float, default: 0.1): The error threshold for refinement when refine_mode is thresholding.
    • prevent_oversampling (bool, default: true): Used in sampling mode. If false, it forces the model to refine exactly refine_sample_pixels even if unnecessary (used for speedtesting).
  7. Run inference using TorchScript (Production)

    master

    For production environments, use a TorchScript model file that has both the architecture and weights baked in. This does not require the repository source code. You can run this in both Python and C++.

    Python Example:

    import torch
    
    device = torch.device('cuda')
    precision = torch.float16
    
    model = torch.jit.load('PATH_TO_MODEL.pth')
    model.backbone_scale = 0.25
    model.refine_mode = 'sampling'
    model.refine_sample_pixels = 80_000
    
    model = model.to(device)
    
    src = torch.rand(1, 3, 1080, 1920).to(precision).to(device)
    bgr = torch.rand(1, 3, 1080, 1920).to(precision).to(device)
    
    pha, fgr = model(src, bgr)[:2]

    C++ Example:

    #include <torch/script.h>
    
    int main() {
        auto device = torch::Device("cuda");
        auto precision = torch::kFloat16;
    
        auto model = torch::jit::load("PATH_TO_MODEL.pth");
        model.setattr("backbone_scale", 0.25);
        model.setattr("refine_mode", "sampling");
        model.setattr("refine_sample_pixels", 80000);
        model.to(device);
    
        auto src = torch::rand({1, 3, 1080, 1920}).to(device).to(precision);
        auto bgr = torch::rand({1, 3, 1080, 1920}).to(device).to(precision);
    
        auto outputs = model.forward({src, bgr}).toTuple()->elements();
        auto pha = outputs[0].toTensor();
        auto fgr = outputs[1].toTensor();
    }
  8. Reference model inputs and outputs

    master

    Model Inputs

    • src: (B, 3, H, W) - Source image with RGB channels normalized to 0 ~ 1.
    • bgr: (B, 3, H, W) - Background image with RGB channels normalized to 0 ~ 1.

    Model Outputs

    For regular use cases, only pha and fgr are required. To composite the result, use: com = pha * fgr + (1 - pha) * bgr.

    • pha: (B, 1, H, W) - Alpha matte (0 ~ 1).
    • fgr: (B, 3, H, W) - Foreground (0 ~ 1).

    Intermediate outputs (training/debugging):

    • pha_sm: (B, 1, Hc, Wc) - Coarse alpha matte.
    • fgr_sm: (B, 3, Hc, Wc) - Coarse foreground.
    • err_sm: (B, 1, Hc, Wc) - Coarse error prediction map.
    • ref_sm: (B, 1, H/4, W/4) - Refinement regions (1 denotes a refined 4x4 patch).