DepthCrafter

repository·main·Indexed 23 days ago

https://github.com/tencent/depthcrafter

A tool for generating consistent, long-duration depth sequences for open-world videos. It features a high-level inference API, the DepthCrafterPipeline for temporal consistency using a sliding window approach, and a specialized UNet model (DiffusersUNetSpatioTemporalConditionModelDepthCrafter) for spatio-temporal forward passes. The package includes utilities for video preprocessing, VAE encoding, and depth visualization via ColorMapper.

Tokens
3.1K
Snippets
7
Records
19
Agent score
82%

What's inside DepthCrafter

  1. Install DepthCrafter

    main

    Follow these steps to set up the environment using uv:

    1. Clone the repository:
      git clone https://github.com/Tencent/DepthCrafter.git
    2. Navigate to the directory and set up the virtual environment:
      cd DepthCrafter
      uv venv
      source .venv/bin/activate
      uv sync
    3. Verify the installation:
      uv pip list
    git clone https://github.com/Tencent/DepthCrafter.git
    cd DepthCrafter
    uv venv
    source .venv/bin/activate
    uv sync
    uv pip list
  2. Run unit tests

    main

    DepthCrafter includes a suite of unit tests located in unit_tests/. You can run them using pytest.

    Common Test Commands

    • Run all tests: pytest unit_tests/
    • Run with verbose output: pytest unit_tests/ -v
    • Run a specific test file: pytest unit_tests/test_depth_crafter_ppl.py

    Test Coverage

    • test_depth_crafter_ppl.py: Main depth estimation pipeline.
    • test_inference.py: Inference interface.
    • test_utils.py: Utility functions.
    • test_unet.py: UNet model.

    Note: A GPU with CUDA support is required for test_pipeline_gpu_integration. Tests use small tensor sizes to minimize memory usage and mock heavy computations for speed.

    pytest unit_tests/
  3. Evaluate DepthCrafter on Datasets

    main

    Evaluation scripts are located in the benchmark folder.

    1. Prepare Dataset: Run dataset_extract/dataset_extract_${dataset_name}.py to generate the necessary CSV files containing paths to RGB videos and depth .npz files.
    2. Run Inference: Execute bash benchmark/infer/infer.sh. Note: You must replace input_rgb_root and saved_root with your actual paths in the script.
    3. Run Evaluation: Execute bash benchmark/eval/eval.sh. Note: You must replace pred_disp_root and gt_disp_root with your actual paths in the script.
    bash benchmark/infer/infer.sh
    bash benchmark/eval/eval.sh
  4. Run DepthCrafter Inference

    main

    You can run depth estimation on videos using the run.py script. Depending on your GPU memory, choose between high-resolution or low-resolution modes.

    High-resolution Inference

    Requirements: ~26GB GPU memory (e.g., for 1024x576 resolution). Performance: ~2.1 fps on A100.

    Low-resolution Inference

    Requirements: ~9GB GPU memory (e.g., for 512x256 resolution). Performance: ~8.6 fps on A100.

    Use the --max-res flag to specify the resolution for low-memory setups.

  5. Initialize DepthCrafterInference

    main

    Use the DepthCrafterInference class to set up the depth estimation pipeline. You must provide paths to the UNet model and the pre-trained pipeline. The class supports CPU offloading strategies to manage memory usage on GPUs.

    Arguments:

    • unet_path (str): Path to the UNet model.
    • pre_train_path (str): Path to the pre-trained model.
    • cpu_offload (Optional[str]): Strategy for CPU offloading. Options are:
      • "model": Enables model CPU offload.
      • "sequential": Enables sequential CPU offload.
      • None: No offloading (runs entirely on the specified device).
    • device (str): Device to run the model on (e.g., `
  6. Use DepthCrafterPipeline for depth sequence generation

    main

    The DepthCrafterPipeline is a specialized pipeline for generating consistent long depth sequences from input videos. It extends the StableVideoDiffusionPipeline and uses a sliding window approach with overlap to maintain temporal consistency across long video sequences.

    To use the pipeline, call it with an input video (as a NumPy array or PyTorch tensor) and specify desired output dimensions and denoising parameters.

  7. Run depth inference with DepthCrafterInference.infer()

    main

    The .infer() method performs the core depth generation task. It takes a video path and several configuration parameters to control the generation process.

    Parameters:

    • video_path (str): Path to the input video file.
    • num_denoising_steps (int): Number of denoising steps.
    • guidance_scale (float): Classifier-Free Guidance (CFG) scale.
    • save_folder (str): Directory where results will be saved.
    • window_size (int): Size of the temporal window for processing.
    • process_length (int): Length of the video to process (-1 for full).
    • overlap (int): Overlap between temporal windows.
    • max_res (int): Maximum resolution for processing.
    • target_fps (int): Target frames per second.
    • seed (int): Random seed for reproducibility.
    • track_time (bool): Whether to track time.
    • save_npz (bool): Whether to save results in .npz format.

    Returns: Returns a list of paths (res_paths) to the generated files (e.g., preprocessed video and generated depth video).

    res_paths = depthcrafter_inference.infer(
        video_path=video_path,
        num_denoising_steps=num_denoising_steps,
        guidance_scale=guidance_scale,
        save_folder=save_folder,
        window_size=window_size,
        process_length=process_length,
        overlap=overlap,
        max_res=max_res,
        target_fps=target_fps,
        seed=seed,
        track_time=track_time,
        save_npz=save_npz,
    )
  8. Use DiffusersUNetSpatioTemporalConditionModelDepthCrafter for forward passes

    main

    The DiffusersUNetSpatioTemporalConditionModelDepthCrafter class is a specialized UNet model for DepthCrafter that extends UNetSpatioTemporalConditionModel. It implements a spatio-temporal forward pass designed to handle video sequences by flattening batch and frame dimensions during processing and reshaping them back at the end.

    forward Method

    Performs the forward pass of the UNet model.

    Arguments:

    • sample (torch.Tensor): The input sample tensor. Expected shape is [batch, frames, channels, height, width].
    • timestep (Union[torch.Tensor, float, int]): The timestep. It is recommended to pass this as a torch.Tensor to avoid CPU/GPU synchronization overhead.
    • encoder_hidden_states (torch.Tensor): Encoder hidden states.
    • added_time_ids (torch.Tensor): Added time IDs used for temporal conditioning.
    • return_dict (bool, default=True): If True, returns a UNetSpatioTemporalConditionOutput object. If False, returns a Tuple containing the sample.
  9. Save video frames with save_video

    main

    Use save_video to encode and save video frames to a file. It accepts a numpy array, a list of numpy arrays, or a list of PIL.Image.Image objects.

    Arguments:

    • video_frames: The frames to save. If providing a numpy array, it is expected to be in uint8 format; if it is float32, it will be automatically scaled by 255 and converted to uint8.
    • output_video_path (str, optional): Path to save the video. If None, a temporary .mp4 file is created and its path is returned.
    • fps (int): Frames per second. Defaults to 10.
    • crf (int): Constant Rate Factor for encoding quality. Higher values mean lower quality/smaller size. Defaults to 18.

    Returns:

    • The path to the saved video file as a str.
  10. Read and preprocess video frames with read_video_frames

    main

    Use read_video_frames to load a video file and prepare it for processing. It handles resizing, downsampling to a target FPS, and normalizing pixel values to a float32 range of [0.0, 1.0].

    Arguments:

    • video_path (str): Path to the video file.
    • process_length (int): Maximum number of frames to return. Use -1 to return all frames.
    • target_fps (int): Desired FPS. Use -1 to use the video's original FPS.
    • max_res (int): Maximum resolution (height or width). The function will scale the video so the largest dimension does not exceed this value, while ensuring dimensions are multiples of 64.
    • dataset (str): If not 'open', use a specific dataset name to set fixed resolutions. Supported datasets: 'sintel', 'scannet', 'KITTI', 'bonn', 'NYUv2'.

    Returns:

    • A tuple containing (frames, fps), where frames is a np.ndarray of shape (N, H, W, C) and fps is the actual FPS used.