当前位置:   article > 正文

基于MobileNetV2主干的DeeplabV3+语义分割实现_mobilenet+deeplabv3+

mobilenet+deeplabv3+

目录

一. 语义分割的含义

二. DeepLabV3+ 模型

三. 模型整体框架

四. 模型检测效果

五. 代码实现

 六. 源码地址


一. 语义分割的含义

        语义分割是计算机视觉中的基本任务,在语义分割中我们需要将视觉输入分为不同的语义可解释类别,「语义的可解释性」即分类类别在真实世界中是有意义的。例如,我们可能需要区分图像中属于汽车的所有像素,并把这些像素涂成蓝色。

我们将   图像分类,目标检测  和   语义分割 进行对比 可以让我们更好的理解语义分割。
 图像分类:  通过  提取特征,输出 待测图片趋向于某个种类
 目标检测:   通过  提取特征,输出 待测图片中不同物体的位置与种类 
 语义分割:  通过 提取特征, 输出 待测图片的每个像素点的种类

二. DeepLabV3+ 模型

 如上图, Encoder中DCNN部分代表语义分割中的主干网络, 在本文中为轻量网络MobileNetV2
 特征提取分为高层语义提取低层的语义提取两个部分。
        首先 1 x 1 对通道上关联,起了一个全连接的作用,接下来是 3 个空洞卷积,有关空洞卷积参见。pooling ,然后经过 concate 将这些特征图进行组合,随后经过 1x1 卷积来改变通道大小。接下里对于底层特征图首先进行 1x1 卷积进行通道变换,这样可以拿到一些低层特征,在将上面组合变换通道数的特征图进行一次 4 倍上采样得到和低层特征图大小相同特征图后,进行组合后再进行一次 4 倍上采样

三. 模型整体框架

        自2017年mobile net问世之后,研究人员就不断在追求更小,更快,更准的网络模型。在这个过程中,也发现了mobile net存在的问题:1.1.结构简单,mobile net使用类似VGG的结构,这种结构已经被证明不如resnet bottle neck结构;2.depthwise convolution的输出,在relu的作用下,很容易废掉。即输出为0,且无法恢复。针对上述问题,谷歌做了改进,也即是本文的主角,mobile net v2。mobile net v2的主要改进为引入了Inverted residual block和利用线性变换替换relu。

四. 模型检测效果

五. 代码实现

MobileV2 网络代码搭建

  1. import math
  2. import os
  3. import torch
  4. import torch.nn as nn
  5. import torch.utils.model_zoo as model_zoo
  6. BatchNorm2d = nn.BatchNorm2d
  7. # PW、DW -> https://blog.csdn.net/qq_41895003/article/details/107408390
  8. # MobileNet V1、V2、V3 -> https://www.icode9.com/content-4-891085.html
  9. def conv_bn(inp, oup, stride):
  10. return nn.Sequential(
  11. nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
  12. BatchNorm2d(oup),
  13. nn.ReLU6(inplace=True)
  14. )
  15. def conv_1x1_bn(inp, oup):
  16. return nn.Sequential(
  17. nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
  18. BatchNorm2d(oup),
  19. nn.ReLU6(inplace=True)
  20. )
  21. # 深度可分离卷积(Depthwise Separable Convolution)
  22. # 一层深度卷积(Depthwise Convolution,DW)与一层逐点卷积(Pointwise Convolution,PW)组合
  23. # 倒残差结构Block PW升维 -> DW -> PW降维
  24. # 在 深度可分离卷积(DW + PW降维) 前加一层 PW
  25. # rate为卷积膨胀系数 若rate>1 则为膨胀卷积(空洞卷积)
  26. # nn.Conv2d(in_channels, out_channels, kernel_size, stride=1,padding=0, dilation=1, groups=1,bias=True):
  27. class InvertedResidual(nn.Module):
  28. def __init__(self, inp, oup, stride, expand_ratio):
  29. super(InvertedResidual, self).__init__()
  30. self.stride = stride
  31. assert stride in [1, 2] # assert in 断言, 若stride不在[1, 2]中则报错
  32. hidden_dim = round(inp * expand_ratio)
  33. self.use_res_connect = self.stride == 1 and inp == oup
  34. # --------------------------------------------#
  35. # 深度可分离卷积
  36. # 第一部分:DW, groups = 输出通道数 = 输入通道数, 当group = 1 时 即为普通卷积
  37. # 第二部分:PW, 利用1×1的卷积更改输出通道数
  38. # --------------------------------------------#
  39. if expand_ratio == 1:
  40. self.conv = nn.Sequential(
  41. #--------------------------------------------#
  42. # 进行3x3的逐层卷积,进行跨特征点的特征提取
  43. #--------------------------------------------#
  44. nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
  45. BatchNorm2d(hidden_dim),
  46. nn.ReLU6(inplace=True),
  47. #-----------------------------------#
  48. # 利用1x1卷积进行通道数的调整
  49. #-----------------------------------#
  50. nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
  51. BatchNorm2d(oup),
  52. )
  53. else:
  54. self.conv = nn.Sequential(
  55. #-----------------------------------#
  56. # 利用1x1卷积进行通道数的上升
  57. #-----------------------------------#
  58. nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False),
  59. BatchNorm2d(hidden_dim),
  60. nn.ReLU6(inplace=True),
  61. #--------------------------------------------#
  62. # 进行3x3的逐层卷积,进行跨特征点的特征提取
  63. #--------------------------------------------#
  64. nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False),
  65. BatchNorm2d(hidden_dim),
  66. nn.ReLU6(inplace=True),
  67. #-----------------------------------#
  68. # 利用1x1卷积进行通道数的下降
  69. #-----------------------------------#
  70. nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False),
  71. BatchNorm2d(oup),
  72. )
  73. def forward(self, x):
  74. if self.use_res_connect:
  75. return x + self.conv(x)
  76. else:
  77. return self.conv(x)
  78. class MobileNetV2(nn.Module):
  79. def __init__(self, n_class=1000, input_size=224, width_mult=1.):
  80. super(MobileNetV2, self).__init__()
  81. block = InvertedResidual
  82. input_channel = 32
  83. last_channel = 1280
  84. interverted_residual_setting = [
  85. # t, c, n, s
  86. [1, 16, 1, 1], # 256, 256, 32 -> 256, 256, 16
  87. [6, 24, 2, 2], # 256, 256, 16 -> 128, 128, 24 2
  88. [6, 32, 3, 2], # 128, 128, 24 -> 64, 64, 32 4
  89. [6, 64, 4, 2], # 64, 64, 32 -> 32, 32, 64 7
  90. [6, 96, 3, 1], # 32, 32, 64 -> 32, 32, 96
  91. [6, 160, 3, 2], # 32, 32, 96 -> 16, 16, 160 14
  92. [6, 320, 1, 1], # 16, 16, 160 -> 16, 16, 320
  93. ]
  94. assert input_size % 32 == 0
  95. input_channel = int(input_channel * width_mult)
  96. self.last_channel = int(last_channel * width_mult) if width_mult > 1.0 else last_channel
  97. # 512, 512, 3 -> 256, 256, 32
  98. # 对应 nets/nets.jpg中的MobilenetV2表中的第一个Conv2d
  99. self.features = [conv_bn(3, input_channel, 2)]
  100. for t, c, n, s in interverted_residual_setting:
  101. output_channel = int(c * width_mult)
  102. # 每一个blocks中包括 n个残差block, 第一个block的步长为s, 剩下的为1
  103. for i in range(n):
  104. if i == 0:
  105. self.features.append(block(input_channel, output_channel, s, expand_ratio=t))
  106. else:
  107. self.features.append(block(input_channel, output_channel, 1, expand_ratio=t))
  108. input_channel = output_channel
  109. self.features.append(conv_1x1_bn(input_channel, self.last_channel))
  110. self.features = nn.Sequential(*self.features)
  111. self.classifier = nn.Sequential(
  112. nn.Dropout(0.2),
  113. nn.Linear(self.last_channel, n_class),
  114. )
  115. self._initialize_weights()
  116. def forward(self, x):
  117. x = self.features(x)
  118. x = x.mean(3).mean(2)
  119. x = self.classifier(x)
  120. return x
  121. # isinstance(x, y)判断x , y是否时相同类型 ,返回bool类型
  122. # 例如:设置一个条件,如果m为Conv2d层就为该m添加相应的参数
  123. def _initialize_weights(self):
  124. for m in self.modules():
  125. if isinstance(m, nn.Conv2d):
  126. n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
  127. m.weight.data.normal_(0, math.sqrt(2. / n))
  128. if m.bias is not None:
  129. m.bias.data.zero_()
  130. elif isinstance(m, BatchNorm2d):
  131. m.weight.data.fill_(1)
  132. m.bias.data.zero_()
  133. elif isinstance(m, nn.Linear):
  134. n = m.weight.size(1)
  135. m.weight.data.normal_(0, 0.01)
  136. m.bias.data.zero_()
  137. def load_url(url, model_dir='./model_data', map_location=None):
  138. if not os.path.exists(model_dir):
  139. os.makedirs(model_dir)
  140. filename = url.split('/')[-1]
  141. cached_file = os.path.join(model_dir, filename)
  142. if os.path.exists(cached_file):
  143. return torch.load(cached_file, map_location=map_location)
  144. else:
  145. return model_zoo.load_url(url,model_dir=model_dir)
  146. def mobilenetv2(pretrained=False, **kwargs):
  147. model = MobileNetV2(n_class=1000, **kwargs)
  148. if pretrained:
  149. model.load_state_dict(load_url('https://github.com/bubbliiiing/deeplabv3-plus-pytorch/releases/download/v1.0/mobilenet_v2.pth.tar'), strict=False)
  150. return model
  151. if __name__ == "__main__":
  152. model = mobilenetv2()
  153. for i, layer in enumerate(model.features):
  154. print(i, layer)

DeepLabV3 + 网络代码搭建

  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from nets.xception import xception
  5. from nets.mobilenetV2 import mobilenetv2
  6. class MobileNetV2(nn.Module):
  7. def __init__(self, downsample_factor=8, pretrained=True):
  8. super(MobileNetV2, self).__init__()
  9. from functools import partial
  10. model = mobilenetv2(pretrained)
  11. # res = [0, 1, 2, 3, 4]
  12. # print(res[:-1])
  13. # out:[0, 1, 2, 3]
  14. self.features = model.features[:-1]
  15. # [2, 4, 7, 14] 代表的是 self.features 中层的位置
  16. self.total_idx = len(self.features)
  17. self.down_idx = [2, 4, 7, 14]
  18. if downsample_factor == 8:
  19. for i in range(self.down_idx[-2], self.down_idx[-1]):
  20. self.features[i].apply(
  21. partial(self._nostride_dilate, dilate=2)
  22. )
  23. for i in range(self.down_idx[-1], self.total_idx):
  24. self.features[i].apply(
  25. partial(self._nostride_dilate, dilate=4)
  26. )
  27. elif downsample_factor == 16:
  28. for i in range(self.down_idx[-1], self.total_idx):
  29. self.features[i].apply(
  30. partial(self._nostride_dilate, dilate=2)
  31. )
  32. # dilate 膨胀系数
  33. def _nostride_dilate(self, m, dilate):
  34. classname = m.__class__.__name__
  35. if classname.find('Conv') != -1:
  36. if m.stride == (2, 2):
  37. m.stride = (1, 1)
  38. if m.kernel_size == (3, 3):
  39. m.dilation = (dilate // 2, dilate // 2)
  40. m.padding = (dilate // 2, dilate // 2)
  41. else:
  42. if m.kernel_size == (3, 3):
  43. m.dilation = (dilate, dilate)
  44. m.padding = (dilate, dilate)
  45. def forward(self, x):
  46. low_level_features = self.features[:4](x)
  47. x = self.features[4:](low_level_features)
  48. return low_level_features, x
  49. # -----------------------------------------#
  50. # ASPP特征提取模块
  51. # 利用不同膨胀率的膨胀卷积进行特征提取
  52. # -----------------------------------------#
  53. class ASPP(nn.Module):
  54. def __init__(self, dim_in, dim_out, rate=1, bn_mom=0.1):
  55. super(ASPP, self).__init__()
  56. self.branch1 = nn.Sequential(
  57. nn.Conv2d(dim_in, dim_out, 1, 1, padding=0, dilation=rate, bias=True),
  58. nn.BatchNorm2d(dim_out, momentum=bn_mom),
  59. nn.ReLU(inplace=True),
  60. )
  61. self.branch2 = nn.Sequential(
  62. nn.Conv2d(dim_in, dim_out, 3, 1, padding=6 * rate, dilation=6 * rate, bias=True),
  63. nn.BatchNorm2d(dim_out, momentum=bn_mom),
  64. nn.ReLU(inplace=True),
  65. )
  66. self.branch3 = nn.Sequential(
  67. nn.Conv2d(dim_in, dim_out, 3, 1, padding=12 * rate, dilation=12 * rate, bias=True),
  68. nn.BatchNorm2d(dim_out, momentum=bn_mom),
  69. nn.ReLU(inplace=True),
  70. )
  71. self.branch4 = nn.Sequential(
  72. nn.Conv2d(dim_in, dim_out, 3, 1, padding=18 * rate, dilation=18 * rate, bias=True),
  73. nn.BatchNorm2d(dim_out, momentum=bn_mom),
  74. nn.ReLU(inplace=True),
  75. )
  76. self.branch5_conv = nn.Conv2d(dim_in, dim_out, 1, 1, 0, bias=True)
  77. self.branch5_bn = nn.BatchNorm2d(dim_out, momentum=bn_mom)
  78. self.branch5_relu = nn.ReLU(inplace=True)
  79. self.conv_cat = nn.Sequential(
  80. nn.Conv2d(dim_out * 5, dim_out, 1, 1, padding=0, bias=True),
  81. nn.BatchNorm2d(dim_out, momentum=bn_mom),
  82. nn.ReLU(inplace=True),
  83. )
  84. def forward(self, x):
  85. [b, c, row, col] = x.size()
  86. # -----------------------------------------#
  87. # 一共五个分支
  88. # -----------------------------------------#
  89. conv1x1 = self.branch1(x)
  90. conv3x3_1 = self.branch2(x)
  91. conv3x3_2 = self.branch3(x)
  92. conv3x3_3 = self.branch4(x)
  93. # -----------------------------------------#
  94. # 第五个分支,全局平均池化+卷积
  95. # -----------------------------------------#
  96. global_feature = torch.mean(x, 2, True)
  97. global_feature = torch.mean(global_feature, 3, True)
  98. global_feature = self.branch5_conv(global_feature)
  99. global_feature = self.branch5_bn(global_feature)
  100. global_feature = self.branch5_relu(global_feature)
  101. global_feature = F.interpolate(global_feature, (row, col), None, 'bilinear', True)
  102. # -----------------------------------------#
  103. # 将五个分支的内容堆叠起来
  104. # 然后1x1卷积整合特征
  105. # -----------------------------------------#
  106. feature_cat = torch.cat([conv1x1, conv3x3_1, conv3x3_2, conv3x3_3, global_feature], dim=1)
  107. # 对应 nets.jpg中 encoder 右侧的 1x1 Covn
  108. # 利用1x1卷积调整通道数
  109. # 52, 52, 1280 -> 52,52,256
  110. result = self.conv_cat(feature_cat)
  111. return result
  112. class DeepLab(nn.Module):
  113. def __init__(self, num_classes, backbone="mobilenet", pretrained=False, downsample_factor=16):
  114. super(DeepLab, self).__init__()
  115. if backbone == "xception":
  116. # ----------------------------------#
  117. # 获得两个特征层
  118. # 浅层特征 [128,128,256]
  119. # 主干部分 [30,30,2048]
  120. # ----------------------------------#
  121. self.backbone = xception(downsample_factor=downsample_factor, pretrained=pretrained)
  122. in_channels = 2048
  123. low_level_channels = 256
  124. elif backbone == "mobilenet":
  125. # ----------------------------------#
  126. # 获得两个特征层
  127. # 浅层特征 [128,128,24]
  128. # 主干部分 [30,30,320]
  129. # ----------------------------------#
  130. self.backbone = MobileNetV2(downsample_factor=downsample_factor, pretrained=pretrained)
  131. in_channels = 320
  132. low_level_channels = 24
  133. else:
  134. raise ValueError('Unsupported backbone - `{}`, Use mobilenet, xception.'.format(backbone))
  135. # -----------------------------------------#
  136. # ASPP特征提取模块
  137. # 利用不同膨胀率的膨胀卷积进行特征提取
  138. # -----------------------------------------#
  139. self.aspp = ASPP(dim_in=in_channels, dim_out=256, rate=16 // downsample_factor)
  140. # ----------------------------------#
  141. # 浅层特征边
  142. # ----------------------------------#
  143. self.shortcut_conv = nn.Sequential(
  144. nn.Conv2d(low_level_channels, 48, 1),
  145. nn.BatchNorm2d(48),
  146. nn.ReLU(inplace=True)
  147. )
  148. self.cat_conv = nn.Sequential(
  149. nn.Conv2d(48 + 256, 256, 3, stride=1, padding=1),
  150. nn.BatchNorm2d(256),
  151. nn.ReLU(inplace=True),
  152. nn.Dropout(0.5),
  153. nn.Conv2d(256, 256, 3, stride=1, padding=1),
  154. nn.BatchNorm2d(256),
  155. nn.ReLU(inplace=True),
  156. nn.Dropout(0.1),
  157. )
  158. self.cls_conv = nn.Conv2d(256, num_classes, 1, stride=1)
  159. def forward(self, x):
  160. H, W = x.size(2), x.size(3)
  161. # -----------------------------------------#
  162. # 获得两个特征层
  163. # low_level_features: 浅层特征-进行卷积处理
  164. # x : 主干部分-利用ASPP结构进行加强特征提取
  165. # -----------------------------------------#
  166. low_level_features, x = self.backbone(x)
  167. # mobilenetV2 返回的主干特征 进行aspp 对应nets.jpg中的 encoder
  168. # 注意返回的 主干特征是 进行到 5个层堆叠为止, 未进行后续操作
  169. x = self.aspp(x)
  170. # mobilenetV2 返回的浅层特征 进行1x1的conv 对应nets.jpg中的 decoder中左侧的那个conv
  171. low_level_features = self.shortcut_conv(low_level_features)
  172. # -----------------------------------------#
  173. # 将加强特征边上采样
  174. # 与浅层特征堆叠后利用卷积进行特征提取
  175. # interpolate() 插值函数, 进行上/下采样处理 , 其中的 size 代表是输出后的 shape
  176. # -----------------------------------------#
  177. x = F.interpolate(x, size=(low_level_features.size(2), low_level_features.size(3)), mode='bilinear',
  178. align_corners=True)
  179. # 对应nets.jpg中的 decoder中的那个Concat
  180. # 48, 128, 128 + 256, 128, 128 -> 304, 128, 128
  181. # 304, 128, 128 -> 256, 128, 128
  182. x = self.cat_conv(torch.cat((x, low_level_features), dim=1))
  183. # 256, 128, 128 -> 2, 128, 128
  184. x = self.cls_conv(x)
  185. # 2, 128, 128 -> 2, 512, 512
  186. # 将分类好的特征举证 resize成原图尺寸大小 的 特征
  187. x = F.interpolate(x, size=(H, W), mode='bilinear', align_corners=True)
  188. return x

 六. 源码地址

GitHub - mcuwangzaiacm/MobileV2_DeepLabV3plus_pytorch1.2: 这是一个基于MobileV2主干的DeepLabV3plus语义分割模型基础代码,用于入门学习

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/678192
推荐阅读
相关标签
  

闽ICP备14008679号