MIT License

技术解读

以下内容由 GitRead 中文社区 编辑团队基于项目 README 与官方资料整理, 结合中文开发者的常见使用场景补充技术选型建议。具体以项目官方文档为准。

AllentDan/LibtorchSegmentation 深度技术分析

项目背景与痛点

过去,基于深度学习的图像分割任务大多依赖于 Python 环境和 PyTorch。然而,嵌入式设备或对性能有更高要求的应用,往往需要更轻量级的解决方案。“AllentDan/LibtorchSegmentation” 提供了一个纯 C++ 的可训练语义分割库,通过 LibTorch (PyTorch C++ API) 实现了 VGG, ResNet, ResNext 等多种主流骨干网络,结合 FPN, U-Net, PAN, LinkNet, PSPNet, DeepLab-V3 和 DeepLab-V3+ 等前沿结构,旨在满足这一需求。它解决了在 C++ 环境下进行高效语义分割的重要问题,使得开发者能够充分利用 LibTorch 的优势,避免 Python 环境带来的性能瓶颈。

核心技术揭秘

架构解析

“LibtorchSegmentation” 的核心在于它的模型框架设计和高效的数据流向管理。项目通过 LibTorch 提供的 C++ API 实现了一个模块化且高度可扩展的语义分割器。它支持多种架构选择,用户可以根据具体的业务需求和硬件配置来选择合适的网络结构。

graph TD A[用户请求] --> B[加载预训练模型] B --> C[图像预处理模块] C --> D{"选择模型结构"} D -->|"VGG"| Z1[VGG模型执行] D -->|"ResNet"| Z2[ResNet模型执行] D -->|"U-Net"| Z3[U-Net模型执行] VGG模型执行 --> E[分割结果] ResNet模型执行 --> F[分割结果] U-Net模型执行 --> G[分割结果] E --> H[后处理] F --> H G --> H H --> I[结果返回]

实现原理与关键技术

  1. 模块化设计:项目引入了模块化的网络架构,这使得用户可以选择合适的模型结构以适配不同的应用场景,从 VGG, ResNet 到 U-Net, DeepLab 等,应有尽有。
  2. LibTorch 执行:基于 PyTorch C++ API 的 LibTorch,为高性能计算提供了支持。在复杂的语义分割任务中,模型的执行效率尤为关键。
  3. 高效的数据流向管理:图像输入首先进行预处理,经过模型选择和数据流管理后,通过选择的模型进行推理,最终进行后处理返回结果。这一过程中的数据流管理至关重要,能够确保高效准确的推理。

功能亮点与差异

“LibtorchSegmentation” 的核心亮点在于其极高的灵活性与可扩展性。它不仅支持多种主流的骨干网络,还涵盖了大量的网络架构选项,能够满足不同层面的需求。通过 LibTorch API,“LibtorchSegmentation” 不仅达到了较高的性能基准,还具备强大的并行处理能力,使其在嵌入式设备或其他对性能有较高要求的应用场景具有明显优势。

应用场景与落地建议

在生产环境中使用 “LibtorchSegmentation”,应重点考虑以下几点:

  1. 模型选择:根据具体的计算资源和预期的性能要求选择合适的骨干网络和分割模型。
  2. 实时性要求:确保所选模型能在规定的时间内完成推理,尤其是在实时性要求较高的场景中。
  3. 硬件资源:考虑运行环境的硬件配置,必要时进行模型裁剪或量化处理,确保在资源有限的设备上仍能进行高效的推理。

综合评价

优点

  1. 灵活性高:支持多种网络架构连接。
  2. 高性能:利用 LibTorch 提供的 C++ API,执行效率高。
  3. 模块化设计:易于扩展和维护。

缺点

  1. 依赖 LibTorch:虽然拥有强大的性能,但可能需要一定的学习成本来掌握 LibTorch API。
  2. 文档不足:项目中部分细节的阐述可能略显不足,有待进一步完善。

总而言之,“LibtorchSegmentation” 是一个高质量的 C++ 语义分割库,能够满足在高性能要求下进行语义分割任务的需求。通过充分理解和利用其提供的模块,开发者能够更有效地配置和调整模型,以适应各类应用场景中的实际需求。

关于

GitHub 原始描述(英文)

A c++ trainable semantic segmentation library based on libtorch (pytorch c++). Backbone: VGG, ResNet, ResNext. Architecture: FPN, U-Net, PAN, LinkNet, PSPNet, DeepLab-V3, DeepLab-V3+ by now.

描述取自 GitHub 官方 API,保持仓库作者书写的原文。

语言占比

C
C++
CMake
Python

Release

README

English | 中文

logo
C++ library with Neural Networks for Image
Segmentation based on LibTorch.

⭐Please give a star if this project helps you.⭐

The main features of this library are:

  • High level API (just a line to create a neural network)
  • 7 models architectures for binary and multi class segmentation (including legendary Unet)
  • 15 available encoders
  • All encoders have pre-trained weights for faster and better convergence
  • 35% or more inference speed boost compared with pytorch cuda, same speed for cpu. (Unet tested in rtx 2070s).

📚 Libtorch Tutorials 📚

Visit Libtorch Tutorials Project if you want to know more about Libtorch Segment library.

📋 Table of content

  1. Quick start
  2. Examples
  3. Train your own data
  4. Models
    1. Architectures
    2. Encoders
  5. Installation
  6. Thanks
  7. To do list
  8. Citing
  9. License
  10. Related repository

⏳ Quick start

1. Create your first Segmentation model with Libtorch Segment

A resnet34 trochscript file is provided here. Segmentation model is just a LibTorch torch::nn::Module, which can be created as easy as:

#include "Segmentor.h"
auto model = UNet(1, /*num of classes*/
                  "resnet34", /*encoder name, could be resnet50 or others*/
                  "path to resnet34.pt"/*weight path pretrained on ImageNet, it is produced by torchscript*/
                  );
  • see table with available model architectures
  • see table with available encoders and their corresponding weights
2. Generate your own pretrained weights

All encoders have pretrained weights. Preparing your data the same way as during weights pre-training may give your better results (higher metric score and faster convergence). And you can also train only the decoder and segmentation head while freeze the backbone.

import torch
from torchvision import models

# resnet34 for example
model = models.resnet34(pretrained=True)
model.eval()
var=torch.ones((1,3,224,224))
traced_script_module = torch.jit.trace(model, var)
traced_script_module.save("resnet34.pt")

Congratulations! You are done! Now you can train your model with your favorite backbone and segmentation framework.

💡 Examples

  • Training model for person segmentation using images from PASCAL VOC Dataset. “voc_person_seg” dir contains 32 json labels and their corresponding jpeg images for training and 8 json labels with corresponding images for validation.
Segmentor<FPN> segmentor;
segmentor.Initialize(0/*gpu id, -1 for cpu*/,
                    512/*resize width*/,
                    512/*resize height*/,
                    {"background","person"}/*class name dict, background included*/,
                    "resnet34"/*backbone name*/,
                    "your path to resnet34.pt");
segmentor.Train(0.0003/*initial leaning rate*/,
                300/*training epochs*/,
                4/*batch size*/,
                "your path to voc_person_seg",
                ".jpg"/*image type*/,
                "your path to save segmentor.pt");
  • Predicting test. A segmentor.pt file is provided in the project here. It is trained through a FPN with ResNet34 backbone for a few epochs. You can directly test the segmentation result through:
cv::Mat image = cv::imread("your path to voc_person_seg\\val\\2007_004000.jpg");
Segmentor<FPN> segmentor;
segmentor.Initialize(0,512,512,{"background","person"},
                      "resnet34","your path to resnet34.pt");
segmentor.LoadWeight("segmentor.pt"/*the saved .pt path*/);
segmentor.Predict(image,"person"/*class name for showing*/);

the predicted result shows as follow:

🧑‍🚀 Train your own data

  • Create your own dataset. Using labelme through “pip install” and label your images. Split the output json files and images into folders just like below:
Dataset
├── train
│   ├── xxx.json
│   ├── xxx.jpg
│   └......
├── val
│   ├── xxxx.json
│   ├── xxxx.jpg
│   └......
  • Training or testing. Just like the example of “voc_person_seg”, replace “voc_person_seg” with your own dataset path.
  • Refer to training tricks to improve your final training performance.

📦 Models

Architectures
Encoders
  • ResNet
  • ResNext
  • VGG

The following is a list of supported encoders in the Libtorch Segment. All the encoders weights can be generated through torchvision except resnest. Select the appropriate family of encoders and click to expand the table and select a specific encoder and its pre-trained weights.

ResNet
Encoder Weights Params, M
resnet18 imagenet 11M
resnet34 imagenet 21M
resnet50 imagenet 23M
resnet101 imagenet 42M
resnet152 imagenet 58M
ResNeXt
Encoder Weights Params, M
resnext50_32x4d imagenet 22M
resnext101_32x8d imagenet 86M
ResNeSt
Encoder Weights Params, M
timm-resnest14d imagenet 8M
timm-resnest26d imagenet 15M
timm-resnest50d imagenet 25M
timm-resnest101e imagenet 46M
timm-resnest200e imagenet 68M
timm-resnest269e imagenet 108M
timm-resnest50d_4s2x40d imagenet 28M
timm-resnest50d_1s4x24d imagenet 23M
SE-Net
Encoder Weights Params, M
senet154 imagenet 113M
se_resnet50 imagenet 26M
se_resnet101 imagenet 47M
se_resnet152 imagenet 64M
se_resnext50_32x4d imagenet 25M
se_resnext101_32x4d imagenet 46M
VGG
Encoder Weights Params, M
vgg11 imagenet 9M
vgg11_bn imagenet 9M
vgg13 imagenet 9M
vgg13_bn imagenet 9M
vgg16 imagenet 14M
vgg16_bn imagenet 14M
vgg19 imagenet 20M
vgg19_bn imagenet 20M

🛠 Installation

Dependency:

Windows:

Configure the environment for libtorch development. Visual studio and Qt Creator are verified for libtorch1.7x release.

Linux && MacOS:

Install libtorch and opencv.

For libtorch, follow the official pytorch c++ tutorials here.

For opencv, follow the official opencv install steps here.

If you have already configured them both, congratulations!!! Download the pretrained weight here and a demo .pt file here into weights.

Building shared or static library -DBUILD_SHARED=<TRUE/FALSE>:

export Torch_DIR='/path/to/libtorch'
cd build
cmake -DBUILD_SHARED=TRUE ..
make
sudo make install

Building tests:

cd test
mkdir build && cd build
cmake ..
make
./resnet34 ../../voc_person_seg/val/2007_003747.jpg ../../weights/resnet34.pt ../../weights/segmentor.pt

⏳ ToDo

  • More segmentation architectures and backbones
    • UNet++ [paper]
    • ResNest
    • Se-Net
    • …
  • Data augmentations
    • Random horizontal flip
    • Random vertical flip
    • Random scale rotation
    • …
  • Training tricks
    • Combined dice and cross entropy loss
    • Freeze backbone
    • Multi step learning rate schedule
    • …

🤝 Thanks

By now, these projects helps a lot.

📝 Citing

@misc{Chunyu:2021,
  Author = {Chunyu Dong},
  Title = {Libtorch Segment},
  Year = {2021},
  Publisher = {GitHub},
  Journal = {GitHub repository},
  Howpublished = {\url{https://github.com/AllentDan/SegmentationCpp}}
}

🛡️ License

Project is distributed under MIT License.

Based on libtorch, I released following repositories:

Last but not least, don’t forget your star…

Feel free to commit issues or pull requests, contributors wanted.

stargazers over time

评论

暂无评论