segmentation_models.pytorch

repository·main·Indexed 11 days ago

https://github.com/qubvel-org/segmentation_models.pytorch

A Python library providing Neural Networks for Image Semantic Segmentation based on PyTorch. It offers a high-level API to create complex encoder-decoder models such as Unet, Unet++, MAnet, Linknet, FPN, PSPNet, PAN, DeepLabV3, DeepLabV3+, UPerNet, Segformer, and DPT. The library supports over 800+ pretrained convolution- and transform-based encoders, including integration with the timm (PyTorch Image Models) library.

Tokens
24.4K
Snippets
40
Records
55
Agent score
94%

What's inside segmentation_models.pytorch

  1. Understanding encoders and pretrained weights

    main

    Encoders (also known as backbones) are used to extract intermediate features that are fed into the decoder for segmentation. SMP provides over 800+ pretrained convolution- and transform-based encoders, including support for timm encoders.

    Choosing an encoder allows you to balance efficiency and accuracy:

    • Lightweight encoders (e.g., mobilenet, mobileone) are suitable for low-latency or real-time inference on edge devices.
    • High-capacity architectures (e.g., convnext, swin, mit) are better for complex tasks with many classes where superior accuracy is required.
  2. Understand the SMP model architecture

    main

    All segmentation models in segmentation_models_pytorch (SMP) are composed of four main components:

    1. Encoder (backbone/feature extractor): Extracts features from the input image.
    2. Decoder: A feature fusion block that uses encoder features to create the segmentation mask.
    3. Segmentation head: The final head that reduces the number of channels from the decoder and upsamples the mask to match the input-output spatial resolution.
    4. Classification head (optional): A head built on top of the deepest encoder features for auxiliary classification tasks.
  3. Configure dynamic image sizes for certain encoders

    main
    When using certain encoders with the provided architectures, the model may require the dynamic_img_size=True parameter to be passed during initialization. This allows the model to work correctly with input resolutions that differ from the resolution the encoder was originally trained for.
  4. Use Transformer-style Timm encoders

    main

    Transformer-style models (such as Swin Transformer or ConvNeXt) available via timm typically produce feature maps at multiple scales: 1/4, 1/8, 1/16, and 1/32. When using these as encoders in segmentation models, ensure your architecture is compatible with these scale transitions.

    Supported Transformer-style encoders include:

    • Caformer: caformer_b36, caformer_m36, caformer_s18, caformer_s36
    • Convformer: convformer_b36, convformer_m36, convformer_s18, convformer_s36
    • ConvNeXt: Various sizes including convnext_tiny, convnext_base, convnext_large, convnext_xlarge, convnext_xxlarge, and convnextv2 variants. Note that most convnext models support dilation.
    • Davit: davit_tiny, davit_small, davit_base, davit_large, davit_huge, davit_giant
    • EfficientFormer: efficientformer_l1, efficientformer_l3, efficientformer_l7, efficientformerv2_l, efficientformerv2_s0, efficientformerv2_s1, efficientformerv2_s2
    • EfficientViT: efficientvit_b0 through efficientvit_l3
    • FastViT: fastvit_t8, fastvit_t12, fastvit_sa12, fastvit_sa24, fastvit_sa36, etc.
    • FocalNet: focalnet_tiny_lrf, focalnet_small_srf, focalnet_base_lrf, focalnet_large_fl3, focalnet_huge_fl3, etc.
    • Hiera: hiera_tiny_224, hiera_small_224, hiera_base_224, hiera_large_224, hiera_huge_224, and sam2_hiera variants.
    • MambaOut: mambaout_tiny, mambaout_small, mambaout_base, etc.
    • MViTv2: mvitv2_tiny, mvitv2_small, mvitv2_base, mvitv2_large, mvitv2_huge
    • PoolFormer: poolformer_s12, poolformer_s24, poolformer_s36, poolformerv2_s12, etc.
    • Swin Transformer: swin_tiny_patch4_window7_224, swin_small_patch4_window7_224, swin_base_patch4_window7_224, swin_large_patch4_window7_224, and swinv2 variants.
    • TinyViT: tiny_vit_5m_224, tiny_vit_11m_224, tiny_vit_21m_224, etc.
  5. Register and use a custom encoder

    main

    After defining your MyEncoder class, you must register it in the smp.encoders.encoders dictionary so it can be used via the encoder_name parameter in model constructors.

    Register the encoder with its pretrained_settings (optional) and any initialization params.

    # Register the encoder
    smp.encoders.encoders["my_awesome_encoder"] = {
        "encoder": MyEncoder, # encoder class here
        "pretrained_settings": {
            "imagenet": {
                "mean": [0.485, 0.456, 0.406],
                "std": [0.229, 0.224, 0.225],
                "url": "https://some-url.com/my-model-weights",
                "input_space": "RGB",
                "input_range": [0, 1],
            },
        },
        "params": {
            # init params for encoder if any
        },
    }
    
    # Use the encoder
    model = smp.Unet(encoder_name="my_awesome_encoder")
  6. Install segmentation-models-pytorch and dependencies

    main

    To use the library, install segmentation-models-pytorch along with lightning and albumentations for training and augmentation support.

    !pip install segmentation-models-pytorch lightning albumentations
  7. Configure data preprocessing for encoders

    main

    To achieve better results and faster convergence, you should preprocess your input data using the same method used during the original weight pre-training. This is particularly relevant for 1, 2, or 3-channel images.

    You can retrieve the appropriate preprocessing function using get_preprocessing_fn from segmentation_models_pytorch.encoders by providing the encoder name and the pre-training type.

    from segmentation_models_pytorch.encoders import get_preprocessing_fn
    
    preprocess_input = get_preprocessing_fn('resnet18', pretrained='imagenet')
  8. Install segmentation-models-pytorch

    main

    You can install the library via PyPI or directly from the GitHub repository.

    To install the stable version from PyPI:

    pip install segmentation-models-pytorch

    To install the latest version from GitHub:

    pip install git+https://github.com/qubvel/segmentation_models.pytorch
    pip install segmentation-models-pytorch