mmsegmentation 之修改输入通道

open-mmlab有许多非常实用的框架,其中目标检测的话mmdetection确实很实用。但语义分割的话当属mmsegmentation,这篇博客介绍mmsegmentation如何将输入图像通道数修改为单通道。

1.默认你自己已经用mmsegmentation 训练了自己的数据集,后面可能根据项目需求,部署时候输入图像通道数为1.而不是RGB。

2.首先去到mmseg下的models,打开backbone文件。选中你自己的backbone,举个例子源码里面输入通道为3,但现在项目需要,将输入通道修改为1,修改成其他通道也可以。这个地方还没完,如果直接编译训练会出现下面bug,也就是说你现在网络输入的是gray但是输入数据还是rgb,需要对输入数据进行rgb2gray。

RuntimeError: Given groups=1, weight of size [32, 1, 3, 3], expected input[4, 3, 320, 220] to have 1 channels, but got 3 channels instead
def __init__(self,
                 in_channels=1,
                 #in_channels=3,
                 downsample_dw_channels=(32, 48),
                 global_in_channels=64,
                 global_block_channels=(64, 96, 128),
                 global_block_strides=(2, 2, 1),
                 global_out_channels=128,
                 higher_in_channels=64,
                 lower_in_channels=128,
                 fusion_out_channels=128,
                 out_indices=(0, 1, 2),
                 conv_cfg=None,
                 norm_cfg=dict(type='BN'),
                 act_cfg=dict(type='ReLU'),
                 align_corners=False,
                 dw_act_cfg=None,
                 init_cfg=None):

3.吹一波,mmsegmentation确实很好用,接着第二步,这个地方不管你是用自定义数据集还是其他数据集,将transformer.py里的rgb2gray添加到训练验证数据处理阶段,举个例子

train_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(type='LoadAnnotations'),
    dict(type='Resize', img_scale=img_scale, ratio_range=(0.5, 2.0)),
    dict(type='RandomCrop', crop_size=crop_size, cat_max_ratio=0.85),
    dict(type='RandomFlip', prob=0.9),
    dict(type='PhotoMetricDistortion'),
    dict(type='Normalize', **img_norm_cfg),
    dict(type='Pad', size=crop_size, pad_val=0, seg_pad_val=255),
    dict(type='RGB2Gray', out_channels=1),
    dict(type='DefaultFormatBundle'),

    dict(type='Collect', keys=['img', 'gt_semantic_seg'])

]
test_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(
        type='MultiScaleFlipAug',
        img_scale=img_scale,
        # img_ratios=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0],
        flip=True,
        transforms=[
            dict(type='Resize', keep_ratio=True),
            dict(type='RandomFlip'),
            dict(type='Normalize', **img_norm_cfg),
            dict(type='RGB2Gray', out_channels=1),

            dict(type='ImageToTensor', keys=['img']),
            dict(type='Collect', keys=['img']),

        ])
]

4.此时你可能会遇到一些bug,第三步完后进行编译后直接训练可能会出现以下错误。

RuntimeError: Input type (torch.cuda.DoubleTensor) and weight type (torch.cuda.FloatTensor) should be the same

网上解释的很多关于这个问题,直接找到对应地方进行修改就可以,去到mmseg下segmentors打开encoder_decoder.py,添加img=img.float

    def extract_feat(self, img):
        """Extract features from images."""
        img = img.float()
        x = self.backbone(img)
        if self.with_neck:
            x = self.neck(x)
        return x

    def encode_decode(self, img, img_metas):
        """Encode images with backbone and decode into a semantic segmentation
        map of the same size as input."""
        img = img.float()
        x = self.extract_feat(img)
        out = self._decode_head_forward_test(x, img_metas)
        out = resize(
            input=out,
            size=img.shape[2:],
            mode='bilinear',
            align_corners=self.align_corners)
        return out

5.编译,在训练

在这里插入图片描述
踩坑结束,

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
修改mmsegmentation的模型,您可以按照以下步骤进行操作: 1. 打开mmseg/core/optimizer/__init__.py文件,并在其中添加您的新模块。例如,如果您的新模块名为MyOptimizer,可以添加以下代码:`from .my_optimizer import MyOptimizer`。这样,注册器(registry)将会发现这个新的模块并添加它。\[1\] 2. 在配置文件中找到optimizer域,并根据您的需求进行修改。例如,如果您想使用ADAM优化器,可以将optimizer字段修改为`optimizer = dict(type='Adam', lr=0.0003, weight_decay=0.0001)`。请注意,使用ADAM优化器可能会导致数值表现下降。\[2\] 3. 如果您想修改特定模型(如DANet),可以找到对应的配置文件。例如,如果您想修改danet_r50-d8_512x512_20k_voc12aug.py配置文件,可以打开该文件并进行修改。 - 在文件中找到_base_字段,并根据您的需求修改其中的路径。例如,您可以修改骨架模型的路径、数据集的路径等。\[3\] - 在model字段中,根据您的需求修改decode_head和auxiliary_head的num_classes参数,以适应您的分类类别数。\[3\] 请根据您的具体需求进行相应的修改。希望对您有所帮助! #### 引用[.reference_title] - *1* *2* [MMsegmentation教程 4: 自定义模型](https://blog.csdn.net/yanqianglifei/article/details/122598010)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [mmsegmentation教程1:自定义数据集、config文件修改、训练教程](https://blog.csdn.net/weixin_42748439/article/details/122845505)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

VisionX Lab

你的鼓励将是我更新的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值