MatAnyone 2

repository·main·Indexed 18 days ago

https://github.com/pq-yang/matanyone2

A practical human video matting framework designed to preserve fine details and maintain robustness in real-world conditions using a learned quality evaluator. It provides a Python API via MatAnyone2 and InferenceCore classes, a CLI for processing videos and frame folders, and a Gradio demo for interactive mask refinement using the Segment Anything Model (SAM).

Tokens
4.8K
Snippets
16
Records
22
Agent score
72%

What's inside matanyone2

  1. Install MatAnyone2 via Conda

    main

    To install MatAnyone2 using Conda, clone the repository, create a new environment with Python 3.10, and install the package in editable mode. You can optionally install dependencies for the Gradio demo.

    # Clone Repo
    git clone https://github.com/pq-yang/MatAnyone2
    cd MatAnyone2
    
    # Create Conda Environment and Install Dependencies
    conda create -n matanyone2 python=3.10 -y
    conda activate matanyone2
    
    # install python dependencies
    pip install -e .
    
    # [optional] install python dependencies for gradio demo
    pip3 install -r hugging_face/requirements.txt
  2. Reproduce VideoMatte benchmark results

    main

    To reproduce quantitative results for the VideoMatte benchmark, follow these steps for data preparation, batch inference, and evaluation. Low-resolution (lr) and high-resolution (hr) data use different hyperparameter settings for --warmup, --erode_kernel, and --dilate_kernel.

    ### 1. Preparation
    Arrange your files as follows:

    data |- VideoMatte_first_frame_seg_mask # for inference only |- VideoMatte |- videomatte_512x288 |- videomatte_1920x1080

    
    ### 2. Batch Inference
    ```shell
    # lr: videomatte_512x288
    bash evaluation/infer_batch_lr_vm.sh
    
    # hr: videomatte_1920x1080
    bash evaluation/infer_batch_hr_vm.sh

    3. Evaluation

    Arrange results and true data:

    data
       |- VideoMatte
            |- videomatte_512x288
            |- videomatte_1920x1080
    
       |- results
            |- videomatte_512x288
            |- videomatte_1920x1080
    # lr: videomatte_512x288
    python evaluation/eval_lr.py \
        --pred-dir ./data/results/videomatte_512x288 \
        --true-dir ./data/VideoMatte/videomatte_512x288 
    
    # hr: videomatte_1920x1080
    python evaluation/eval_hr.py \
        --pred-dir ./data/results/videomatte_1920x1080 \
        --true-dir ./data/VideoMatte/videomatte_1920x1080 
  3. Download MatAnyone2 Pretrained Model

    main

    Download the pretrained model matanyone2.pth and place it in a pretrained_models directory. The model will also be automatically downloaded during the first inference if not found.

    pretrained_models
       |- matanyone2.pth
  4. Reproduce CRGNN benchmark results

    main

    To reproduce quantitative results for the CRGNN real benchmark, follow these steps for data preparation, batch inference, and evaluation.

    ### 1. Preparation
    Arrange your files as follows:

    data |- crgnn
    |- alpha |- image_allframe |- mask # first frame seg mask

    
    ### 2. Batch Inference
    ```shell
    bash evaluation/infer_batch_crgnn.sh

    3. Evaluation

    Arrange results and true data:

    data
       |- crgnn
            |- alpha
    
       |- results
            |- crgnn
    python evaluation/eval_crgnn.py \
        --pred-dir ./data/results/crgnn \
        --true-dir ./data/crgnn/alpha 
  5. Reproduce YouTubeMatte benchmark results

    main

    To reproduce quantitative results for the YouTubeMatte benchmark, follow these steps for data preparation, batch inference, and evaluation. Note that low-resolution (lr) and high-resolution (hr) data require different hyperparameter values for --warmup, --erode_kernel, and --dilate_kernel.

    ### 1. Preparation
    Arrange your files as follows:

    data |- YouTubeMatte_first_frame_seg_mask # for inference only |- YouTubeMatte |- youtubematte_512x288 |- youtubematte_1920x1080

    
    ### 2. Batch Inference
    ```shell
    # lr: youtubematte_512x288
    bash evaluation/infer_batch_lr_yt.sh
    
    # hr: youtubematte_1920x1080
    bash evaluation/infer_batch_hr_yt.sh

    3. Evaluation

    Arrange results and true data:

    data
       |- YouTubeMatte
            |- youtubematte_512x288
            |- youtubematte_1920x1080
    
       |- results
            |- youtubematte_512x288
            |- youtubematte_1920x1080
    # lr: youtubematte_512x288
    python evaluation/eval_lr.py \
        --pred-dir ./data/results/youtubematte_512x288 \
        --true-dir ./data/YouTubeMatte/youtubematte_512x288 
    
    # hr: youtubematte_1920x1080
    python evaluation/eval_hr.py \
        --pred-dir ./data/results/youtubematte_1920x1080 \
        --true-dir ./data/YouTubeMatte/youtubematte_1920x1080 
  6. Install MatAnyone2 via uv

    main

    You can add MatAnyone2 to a new project using uv by initializing a project and adding the package directly from the GitHub repository.

    uv init my-matting-project && cd my-matting-project
    uv add matanyone2@git+https://github.com/pq-yang/MatAnyone2.git
  7. Launch the MatAnyone2 Gradio Demo locally

    main

    To run an interactive GUI that allows you to upload videos and assign masks via clicks, launch the Gradio app located in the hugging_face directory. Note that FFmpeg is required on your system.

    cd hugging_face
    
    # install GUI dependencies
    pip3 install -r requirements.txt
    
    # launch the demo
    python app.py
  8. Understand the Interactive State structure

    main

    The interactive_state is a dictionary used to track the progress of user interactions and mask accumulation. It is essential for multi-mask matting.

    Key Fields:

    • inference_times: Counter for total inferences.
    • negative_click_times: Count of negative point prompts.
    • positive_click_times: Count of positive point prompts.
    • mask_save: Boolean/config for saving masks.
    • multi_mask: A dictionary containing:
      • mask_names: List of names for the added masks.
      • masks: The actual mask data/arrays.
    • track_end_number: The frame number where tracking should stop.
  9. Use the MatAnyone2 Python API

    main

    You can perform video matting programmatically using the MatAnyone2 and InferenceCore classes. The model can be loaded from Hugging Face using from_pretrained.

    from matanyone2 import MatAnyone2, InferenceCore
    
    # Load model from Hugging Face
    model = MatAnyone2.from_pretrained("PeiqingYang/MatAnyone2")
    
    # Initialize processor
    processor = InferenceCore(model, device="cuda:0")
    
    # Run inference
    processor.process_video(
        input_path="inputs/video/test-sample2.mp4",
        mask_path="inputs/mask/test-sample2.png",
        output_path="results",
    )
  10. Run MatAnyone2 Inference via CLI

    main

    MatAnyone2 requires a video (or a folder of frames) and a segmentation mask of the first frame as input. The mask can be obtained from models like SAM2.

    Input Formats:

    • Video folder: A directory containing all video frames.
    • Video file: .mp4, .mov, or .avi files.

    CLI Options:

    • -i, --input: Path to the video or video folder.
    • -m, --mask: Path to the first-frame segmentation mask image.
    • --save-image: Save results as per-frame images instead of video.
    • --max-size: Set a limit for the maximum input resolution; the video will be downsampled if min(w, h) exceeds this value.
    # Input format: video folder
    python inference_matanyone2.py -i inputs/video/test-sample1 -m inputs/mask/test-sample1.png
    
    # Input format: mp4
    python inference_matanyone2.py -i inputs/video/test-sample2.mp4 -m inputs/mask/test-sample2.png
    
    # Using the matanyone2 CLI command directly
    matanyone2 -i inputs/video/test-sample1 -m inputs/mask/test-sample1.png
  11. Manage multiple masks

    main

    The interface supports adding and removing multiple masks to handle complex objects.

    Add a mask

    Use add_multi_mask to commit the current SAM refinement as a new mask layer.

    • Inputs: state, interactive_state, mask_dropdown.
    • Outputs: interactive_state, mask_dropdown, template_frame, click_state.

    Remove a mask

    Use remove_multi_mask to delete a mask layer.

    • Inputs: interactive_state, mask_dropdown.
    • Outputs: interactive_state, mask_dropdown.
  12. Initialize MaskGenerator for SAM

    main

    The MaskGenerator class is used to manage the Segment Anything Model (SAM) controller. It requires a SAM checkpoint and an argument object containing configuration like sam_model_type and device.

    class MaskGenerator():
        def __init__(self, sam_checkpoint, args):
            self.args = args
            self.samcontroler = SamControler(sam_checkpoint, args.sam_model_type, args.device)
    
        def first_frame_click(self, image: np.ndarray, points:np.ndarray, labels: np.ndarray, multimask=True):
            mask, logit, painted_image = self.samcontroler.first_frame_click(image, points, labels, multimask)
            return mask, logit, painted_image