deeplab.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import paddle
  15. import paddle.nn as nn
  16. import paddle.nn.functional as F
  17. from paddlex.paddleseg.cvlibs import manager
  18. from paddlex.paddleseg.models import layers
  19. from paddlex.paddleseg.utils import utils
  20. __all__ = ['DeepLabV3P', 'DeepLabV3']
  21. @manager.MODELS.add_component
  22. class DeepLabV3P(nn.Layer):
  23. """
  24. The DeepLabV3Plus implementation based on PaddlePaddle.
  25. The original article refers to
  26. Liang-Chieh Chen, et, al. "Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation"
  27. (https://arxiv.org/abs/1802.02611)
  28. Args:
  29. num_classes (int): The unique number of target classes.
  30. backbone (paddle.nn.Layer): Backbone network, currently support Resnet50_vd/Resnet101_vd/Xception65.
  31. backbone_indices (tuple, optional): Two values in the tuple indicate the indices of output of backbone.
  32. Default: (0, 3).
  33. aspp_ratios (tuple, optional): The dilation rate using in ASSP module.
  34. If output_stride=16, aspp_ratios should be set as (1, 6, 12, 18).
  35. If output_stride=8, aspp_ratios is (1, 12, 24, 36).
  36. Default: (1, 6, 12, 18).
  37. aspp_out_channels (int, optional): The output channels of ASPP module. Default: 256.
  38. align_corners (bool, optional): An argument of F.interpolate. It should be set to False when the feature size is even,
  39. e.g. 1024x512, otherwise it is True, e.g. 769x769. Default: False.
  40. pretrained (str, optional): The path or url of pretrained model. Default: None.
  41. """
  42. def __init__(self,
  43. num_classes,
  44. backbone,
  45. backbone_indices=(0, 3),
  46. aspp_ratios=(1, 6, 12, 18),
  47. aspp_out_channels=256,
  48. align_corners=False,
  49. pretrained=None):
  50. super().__init__()
  51. self.backbone = backbone
  52. backbone_channels = [
  53. backbone.feat_channels[i] for i in backbone_indices
  54. ]
  55. self.head = DeepLabV3PHead(num_classes, backbone_indices,
  56. backbone_channels, aspp_ratios,
  57. aspp_out_channels, align_corners)
  58. self.align_corners = align_corners
  59. self.pretrained = pretrained
  60. self.init_weight()
  61. def forward(self, x):
  62. feat_list = self.backbone(x)
  63. logit_list = self.head(feat_list)
  64. return [
  65. F.interpolate(
  66. logit,
  67. paddle.shape(x)[2:],
  68. mode='bilinear',
  69. align_corners=self.align_corners) for logit in logit_list
  70. ]
  71. def init_weight(self):
  72. if self.pretrained is not None:
  73. utils.load_entire_model(self, self.pretrained)
  74. class DeepLabV3PHead(nn.Layer):
  75. """
  76. The DeepLabV3PHead implementation based on PaddlePaddle.
  77. Args:
  78. num_classes (int): The unique number of target classes.
  79. backbone_indices (tuple): Two values in the tuple indicate the indices of output of backbone.
  80. the first index will be taken as a low-level feature in Decoder component;
  81. the second one will be taken as input of ASPP component.
  82. Usually backbone consists of four downsampling stage, and return an output of
  83. each stage. If we set it as (0, 3), it means taking feature map of the first
  84. stage in backbone as low-level feature used in Decoder, and feature map of the fourth
  85. stage as input of ASPP.
  86. backbone_channels (tuple): The same length with "backbone_indices". It indicates the channels of corresponding index.
  87. aspp_ratios (tuple): The dilation rates using in ASSP module.
  88. aspp_out_channels (int): The output channels of ASPP module.
  89. align_corners (bool): An argument of F.interpolate. It should be set to False when the output size of feature
  90. is even, e.g. 1024x512, otherwise it is True, e.g. 769x769.
  91. """
  92. def __init__(self, num_classes, backbone_indices, backbone_channels,
  93. aspp_ratios, aspp_out_channels, align_corners):
  94. super().__init__()
  95. self.aspp = layers.ASPPModule(
  96. aspp_ratios,
  97. backbone_channels[1],
  98. aspp_out_channels,
  99. align_corners,
  100. use_sep_conv=True,
  101. image_pooling=True)
  102. self.decoder = Decoder(num_classes, backbone_channels[0], align_corners)
  103. self.backbone_indices = backbone_indices
  104. def forward(self, feat_list):
  105. logit_list = []
  106. low_level_feat = feat_list[self.backbone_indices[0]]
  107. x = feat_list[self.backbone_indices[1]]
  108. x = self.aspp(x)
  109. logit = self.decoder(x, low_level_feat)
  110. logit_list.append(logit)
  111. return logit_list
  112. @manager.MODELS.add_component
  113. class DeepLabV3(nn.Layer):
  114. """
  115. The DeepLabV3 implementation based on PaddlePaddle.
  116. The original article refers to
  117. Liang-Chieh Chen, et, al. "Rethinking Atrous Convolution for Semantic Image Segmentation"
  118. (https://arxiv.org/pdf/1706.05587.pdf).
  119. Args:
  120. Please Refer to DeepLabV3P above.
  121. """
  122. def __init__(self,
  123. num_classes,
  124. backbone,
  125. backbone_indices=(3, ),
  126. aspp_ratios=(1, 6, 12, 18),
  127. aspp_out_channels=256,
  128. align_corners=False,
  129. pretrained=None):
  130. super().__init__()
  131. self.backbone = backbone
  132. backbone_channels = [
  133. backbone.feat_channels[i] for i in backbone_indices
  134. ]
  135. self.head = DeepLabV3Head(num_classes, backbone_indices,
  136. backbone_channels, aspp_ratios,
  137. aspp_out_channels, align_corners)
  138. self.align_corners = align_corners
  139. self.pretrained = pretrained
  140. self.init_weight()
  141. def forward(self, x):
  142. feat_list = self.backbone(x)
  143. logit_list = self.head(feat_list)
  144. return [
  145. F.interpolate(
  146. logit,
  147. paddle.shape(x)[2:],
  148. mode='bilinear',
  149. align_corners=self.align_corners) for logit in logit_list
  150. ]
  151. def init_weight(self):
  152. if self.pretrained is not None:
  153. utils.load_entire_model(self, self.pretrained)
  154. class DeepLabV3Head(nn.Layer):
  155. """
  156. The DeepLabV3Head implementation based on PaddlePaddle.
  157. Args:
  158. Please Refer to DeepLabV3PHead above.
  159. """
  160. def __init__(self, num_classes, backbone_indices, backbone_channels,
  161. aspp_ratios, aspp_out_channels, align_corners):
  162. super().__init__()
  163. self.aspp = layers.ASPPModule(
  164. aspp_ratios,
  165. backbone_channels[0],
  166. aspp_out_channels,
  167. align_corners,
  168. use_sep_conv=False,
  169. image_pooling=True)
  170. self.cls = nn.Conv2D(
  171. in_channels=aspp_out_channels,
  172. out_channels=num_classes,
  173. kernel_size=1)
  174. self.backbone_indices = backbone_indices
  175. def forward(self, feat_list):
  176. logit_list = []
  177. x = feat_list[self.backbone_indices[0]]
  178. x = self.aspp(x)
  179. logit = self.cls(x)
  180. logit_list.append(logit)
  181. return logit_list
  182. class Decoder(nn.Layer):
  183. """
  184. Decoder module of DeepLabV3P model
  185. Args:
  186. num_classes (int): The number of classes.
  187. in_channels (int): The number of input channels in decoder module.
  188. """
  189. def __init__(self, num_classes, in_channels, align_corners):
  190. super(Decoder, self).__init__()
  191. self.conv_bn_relu1 = layers.ConvBNReLU(
  192. in_channels=in_channels, out_channels=48, kernel_size=1)
  193. self.conv_bn_relu2 = layers.SeparableConvBNReLU(
  194. in_channels=304, out_channels=256, kernel_size=3, padding=1)
  195. self.conv_bn_relu3 = layers.SeparableConvBNReLU(
  196. in_channels=256, out_channels=256, kernel_size=3, padding=1)
  197. self.conv = nn.Conv2D(
  198. in_channels=256, out_channels=num_classes, kernel_size=1)
  199. self.align_corners = align_corners
  200. def forward(self, x, low_level_feat):
  201. low_level_feat = self.conv_bn_relu1(low_level_feat)
  202. x = F.interpolate(
  203. x,
  204. paddle.shape(low_level_feat)[2:],
  205. mode='bilinear',
  206. align_corners=self.align_corners)
  207. x = paddle.concat([x, low_level_feat], axis=1)
  208. x = self.conv_bn_relu2(x)
  209. x = self.conv_bn_relu3(x)
  210. x = self.conv(x)
  211. return x