深度学习训练营(四):语义分割实战——打造自动驾驶感知系统


一、语义分割技术演进与核心价值

技术里程碑

突破性创新

自动驾驶应用场景

典型模型mIoU (Cityscapes)

FCN (2015)

全卷积网络替代全连接层

基础道路区域分割

62.2%

U-Net (2015)

跳跃连接增强细节恢复

高精度车道线识别

68.9%

DeepLabV3+ (2018)

空洞卷积 + ASPP多尺度融合

复杂交通场景理解

82.1%

SegFormer (2021)

Transformer + 轻量级解码器

实时道路场景解析

84.5%


二、环境配置(30分钟快速搭建)

2.1 基础环境

# 创建专用环境conda create -n mmseg python=3.8 -yconda activate mmseg
# 安装PyTorch (CUDA 11.3)pip install torch==1.12.1+cu113 torchvision==0.13.1+cu113 --extra-index-url <https://download.pytorch.org/whl/cu113>
# 安装MMSegmentationpip install mmcv-full==1.7.0 -f <https://download.openmmlab.com/mmcv/dist/cu113/torch1.12.0/index.html>pip install mmsegmentation==0.30.0
# 安装数据处理工具pip install cityscapesscripts albumentations==1.3.0

2.2 验证安装

import mmsegprint(mmseg.__version__)  # 应输出0.30.0

三、Cityscapes数据集全流程处理

3.1 数据集下载与结构

# 目录结构cityscapes/├── leftImg8bit/│   └── train/           # 2955张训练图像│       └── aachen/└── gtFine/    └── train/           # 像素级标注        └── aachen/

3.2 标注格式转换

# 转换ID标注为训练格式python tools/convert_datasets/cityscapes.py data/cityscapes --nproc 8
# 生成类别颜色映射文件python tools/dataset_converters/cityscapes.py --nproc 8

3.3 数据增强策略(Albumentations)

import albumentations as A
train_pipeline = [    A.HorizontalFlip(p=0.5),    A.RandomBrightnessContrast(p=0.2),    A.RGBShift(r_shift_limit=20, g_shift_limit=20, b_shift_limit=20, p=0.5),    A.RandomScale(scale_limit=(0.5, 2.0),    A.PadIfNeeded(min_height=1024, min_width=2048),    A.RandomCrop(height=512, width=1024)]

四、DeepLabV3+模型实战

4.1 模型配置(configs/deeplabv3plus_r50-d8.py)

model = dict(    type='EncoderDecoder',    backbone=dict(        type='ResNetV1c',        depth=50,        dilations=(1, 1, 2, 4)),    decode_head=dict(        type='DepthwiseSeparableASPPHead',        in_channels=2048,        channels=512,        dilations=(6, 12, 18)),    auxiliary_head=dict(        type='FCNHead',        in_channels=1024,        channels=256))

4.2 分布式训练(8卡A100)

./tools/dist_train.sh configs/deeplabv3plus/deeplabv3plus_r50-d8_512x1024_80k_cityscapes.py 8

4.3 训练参数优化

# 学习率策略optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0005)lr_config = dict(policy='poly', power=0.9, min_lr=1e-4, by_epoch=False)
# 损失函数调整(应对类别不平衡)loss_decode=dict(    type='CrossEntropyLoss',    use_sigmoid=False,    loss_weight=1.0,    class_weight=[        0.8373,  # road        0.9180,  # sidewalk        0.8660,  # building        ...       # 其他类别权重    ])

五、模型评估与可视化

5.1 性能指标解析

指标

计算公式

自动驾驶应用意义

mIoU

各类别IoU的平均值

整体场景理解能力评估

FWIoU

按类别频率加权的IoU

重点评估道路/障碍物区域

Accuracy

正确像素数 / 总像素数

车道线等细节识别能力

5.2 可视化工具

# 预测结果可视化from mmseg.apis import inference_segmentor, show_result_pyplot
result = inference_segmentor(model, img_path)show_result_pyplot(model, img_path, result, opacity=0.5)
# TensorBoard日志分析tensorboard --logdir=work_dirs --port=6006

六、Jetson Xavier部署实战

6.1 模型转换(TensorRT)

# 导出ONNXpython tools/deployment/pytorch2onnx.py \\    configs/deeplabv3plus/deeplabv3plus_r50-d8_512x1024_80k_cityscapes.py \\    checkpoints/deeplabv3plus_r50-d8.pth \\    --shape 512 1024
# 生成TensorRT引擎trtexec --onnx=deeplabv3plus.onnx \\        --saveEngine=deeplabv3plus.engine \\        --fp16 \\        --workspace=4096

6.2 C++推理加速

// 初始化TensorRT引擎nvinfer1::IRuntime* runtime = nvinfer1::createInferRuntime(gLogger);nvinfer1::ICudaEngine* engine = runtime->deserializeCudaEngine(trtModelStream, size);
// 预处理(CUDA加速)cudaMemcpyAsync(buffers[0], input, inputSize, cudaMemcpyHostToDevice, stream);
// 执行推理context->enqueueV2(buffers, stream, nullptr);
// 后处理(生成伪彩色分割图)void visualizeSegmentation(float* output, int width, int height) {    for (int i = 0; i < height; i++) {        for (int j = 0; j < width; j++) {            int class_id = argmax(output[i*width + j]);            cv::Vec3b color = class_colors[class_id];            result_image.at<cv::Vec3b>(i, j) = color;        }    }}

七、避坑指南与性能优化

7.1 显存不足解决方案

# 混合精度训练fp16 = dict(loss_scale=512.)
# 梯度累积optimizer_config = dict(type='GradientCumulativeOptimizerHook', cumulative_iters=4)
# 输入尺寸调整img_scale = (1024, 512)  # 原始(2048,1024) → 缩小50%

7.2 类别不平衡处理

# 自定义损失权重class_weight = [    2.0,  # 罕见类别(交通灯)    0.5,  # 常见类别(天空)    ...]
# 使用Focal Lossloss_decode=dict(    type='FocalLoss',    use_sigmoid=True,    gamma=2.0,    alpha=0.25,    loss_weight=1.0)

八、自动驾驶感知系统进阶

8.1 多传感器融合

class FusionNet(nn.Module):    def __init__(self):        super().__init__()        self.camera_branch = DeepLabV3Plus()  # 摄像头分支        self.lidar_branch = PointNet2()       # 激光雷达分支        self.fusion_layer = CrossAttention(dim=256)  # 特征融合
    def forward(self, img, point_cloud):        img_feat = self.camera_branch(img)        lidar_feat = self.lidar_branch(point_cloud)        fused_feat = self.fusion_layer(img_feat, lidar_feat)        return fused_feat

8.2 时序信息建模

# 3D卷积处理视频流self.conv3d = nn.Sequential(    nn.Conv3d(256, 128, kernel_size=(3,1,1)),  # 时序维度卷积    nn.BatchNorm3d(128),    nn.ReLU())

九、总结与展望

通过本实战,您已掌握:

语义分割核心技术原理

Cityscapes数据集全流程处理方法

工业级模型训练与部署方案

下期预告:深度学习训练营(五):PyTorch入门

挑战任务:在nuScenes数据集上实现激光雷达与视觉的融合分割!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bryan Ding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值