🚀 分割模型库(segmentation - models - pytorch)
segmentation - models - pytorch
是一个用于图像分割的强大库,提供了预训练的Segformer模型,可帮助开发者快速实现图像分割任务,在ADE20K等数据集上有良好表现。
🚀 快速开始
加载预训练模型
你可以通过下面的步骤加载预训练的Segformer模型进行推理:
-
点击下面的按钮在Colab中打开示例:

-
安装所需依赖:
pip install -U segmentation_models_pytorch albumentations
- 运行推理代码:
import torch
import requests
import numpy as np
import albumentations as A
import segmentation_models_pytorch as smp
from PIL import Image
device = "cuda" if torch.cuda.is_available() else "cpu"
checkpoint = "smp-hub/segformer-b0-512x512-ade-160k"
model = smp.from_pretrained(checkpoint).eval().to(device)
preprocessing = A.Compose.from_pretrained(checkpoint)
url = "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg"
image = Image.open(requests.get(url, stream=True).raw)
np_image = np.array(image)
normalized_image = preprocessing(image=np_image)["image"]
input_tensor = torch.as_tensor(normalized_image)
input_tensor = input_tensor.permute(2, 0, 1).unsqueeze(0)
input_tensor = input_tensor.to(device)
with torch.no_grad():
output_mask = model(input_tensor)
mask = torch.nn.functional.interpolate(
output_mask, size=(image.height, image.width), mode="bilinear", align_corners=False
)
mask = mask.argmax(1).cpu().numpy()
💻 使用示例
基础用法
上述加载预训练模型并进行推理的代码就是基础用法示例,它展示了如何从预训练模型进行初始化、图像预处理、推理和后处理的完整流程。
高级用法
目前文档未提供高级用法示例,若有更多需求,可参考库的官方文档。
🔧 技术细节
模型初始化参数
model_init_params = {
"encoder_name": "mit_b0",
"encoder_depth": 5,
"encoder_weights": None,
"decoder_segmentation_channels": 256,
"in_channels": 3,
"classes": 150,
"activation": None,
"aux_params": None
}
数据集
本模型使用的数据集是 ADE20K 。
📚 详细文档
- 库的GitHub仓库:https://github.com/qubvel/segmentation_models.pytorch
- 文档链接:https://smp.readthedocs.io/en/latest/
📄 许可证
许可证信息请参考:https://github.com/NVlabs/SegFormer/blob/master/LICENSE
本模型使用 PytorchModelHubMixin 推送到了模型中心。