deeplab.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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],
  103. align_corners)
  104. self.backbone_indices = backbone_indices
  105. def forward(self, feat_list):
  106. logit_list = []
  107. low_level_feat = feat_list[self.backbone_indices[0]]
  108. x = feat_list[self.backbone_indices[1]]
  109. x = self.aspp(x)
  110. logit = self.decoder(x, low_level_feat)
  111. logit_list.append(logit)
  112. return logit_list
  113. @manager.MODELS.add_component
  114. class DeepLabV3(nn.Layer):
  115. """
  116. The DeepLabV3 implementation based on PaddlePaddle.
  117. The original article refers to
  118. Liang-Chieh Chen, et, al. "Rethinking Atrous Convolution for Semantic Image Segmentation"
  119. (https://arxiv.org/pdf/1706.05587.pdf).
  120. Args:
  121. Please Refer to DeepLabV3P above.
  122. """
  123. def __init__(self,
  124. num_classes,
  125. backbone,
  126. backbone_indices=(3, ),
  127. aspp_ratios=(1, 6, 12, 18),
  128. aspp_out_channels=256,
  129. align_corners=False,
  130. pretrained=None):
  131. super().__init__()
  132. self.backbone = backbone
  133. backbone_channels = [
  134. backbone.feat_channels[i] for i in backbone_indices
  135. ]
  136. self.head = DeepLabV3Head(num_classes, backbone_indices,
  137. backbone_channels, aspp_ratios,
  138. aspp_out_channels, align_corners)
  139. self.align_corners = align_corners
  140. self.pretrained = pretrained
  141. self.init_weight()
  142. def forward(self, x):
  143. feat_list = self.backbone(x)
  144. logit_list = self.head(feat_list)
  145. return [
  146. F.interpolate(
  147. logit,
  148. paddle.shape(x)[2:],
  149. mode='bilinear',
  150. align_corners=self.align_corners) for logit in logit_list
  151. ]
  152. def init_weight(self):
  153. if self.pretrained is not None:
  154. utils.load_entire_model(self, self.pretrained)
  155. class DeepLabV3Head(nn.Layer):
  156. """
  157. The DeepLabV3Head implementation based on PaddlePaddle.
  158. Args:
  159. Please Refer to DeepLabV3PHead above.
  160. """
  161. def __init__(self, num_classes, backbone_indices, backbone_channels,
  162. aspp_ratios, aspp_out_channels, align_corners):
  163. super().__init__()
  164. self.aspp = layers.ASPPModule(
  165. aspp_ratios,
  166. backbone_channels[0],
  167. aspp_out_channels,
  168. align_corners,
  169. use_sep_conv=False,
  170. image_pooling=True)
  171. self.cls = nn.Conv2D(
  172. in_channels=aspp_out_channels,
  173. out_channels=num_classes,
  174. kernel_size=1)
  175. self.backbone_indices = backbone_indices
  176. def forward(self, feat_list):
  177. logit_list = []
  178. x = feat_list[self.backbone_indices[0]]
  179. x = self.aspp(x)
  180. logit = self.cls(x)
  181. logit_list.append(logit)
  182. return logit_list
  183. class Decoder(nn.Layer):
  184. """
  185. Decoder module of DeepLabV3P model
  186. Args:
  187. num_classes (int): The number of classes.
  188. in_channels (int): The number of input channels in decoder module.
  189. """
  190. def __init__(self, num_classes, in_channels, align_corners):
  191. super(Decoder, self).__init__()
  192. self.conv_bn_relu1 = layers.ConvBNReLU(
  193. in_channels=in_channels, out_channels=48, kernel_size=1)
  194. self.conv_bn_relu2 = layers.SeparableConvBNReLU(
  195. in_channels=304, out_channels=256, kernel_size=3, padding=1)
  196. self.conv_bn_relu3 = layers.SeparableConvBNReLU(
  197. in_channels=256, out_channels=256, kernel_size=3, padding=1)
  198. self.conv = nn.Conv2D(
  199. in_channels=256, out_channels=num_classes, kernel_size=1)
  200. self.align_corners = align_corners
  201. def forward(self, x, low_level_feat):
  202. low_level_feat = self.conv_bn_relu1(low_level_feat)
  203. x = F.interpolate(
  204. x,
  205. paddle.shape(low_level_feat)[2:],
  206. mode='bilinear',
  207. align_corners=self.align_corners)
  208. x = paddle.concat([x, low_level_feat], axis=1)
  209. x = self.conv_bn_relu2(x)
  210. x = self.conv_bn_relu3(x)
  211. x = self.conv(x)
  212. return x