gscnn.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 cv2
  15. import numpy as np
  16. import paddle
  17. import paddle.nn as nn
  18. import paddle.nn.functional as F
  19. from paddlex.paddleseg.cvlibs import manager
  20. from paddlex.paddleseg.models import layers
  21. from paddlex.paddleseg.models.backbones import resnet_vd
  22. from paddlex.paddleseg.models import deeplab
  23. from paddlex.paddleseg.utils import utils
  24. @manager.MODELS.add_component
  25. class GSCNN(nn.Layer):
  26. """
  27. The GSCNN implementation based on PaddlePaddle.
  28. The original article refers to
  29. Towaki Takikawa, et, al. "Gated-SCNN: Gated Shape CNNs for Semantic Segmentation"
  30. (https://arxiv.org/pdf/1907.05740.pdf)
  31. Args:
  32. num_classes (int): The unique number of target classes.
  33. backbone (paddle.nn.Layer): Backbone network, currently support Resnet50_vd/Resnet101_vd.
  34. backbone_indices (tuple, optional): Two values in the tuple indicate the indices of output of backbone.
  35. Default: (0, 1, 2, 3).
  36. aspp_ratios (tuple, optional): The dilation rate using in ASSP module.
  37. If output_stride=16, aspp_ratios should be set as (1, 6, 12, 18).
  38. If output_stride=8, aspp_ratios is (1, 12, 24, 36).
  39. Default: (1, 6, 12, 18).
  40. aspp_out_channels (int, optional): The output channels of ASPP module. Default: 256.
  41. align_corners (bool, optional): An argument of F.interpolate. It should be set to False when the feature size is even,
  42. e.g. 1024x512, otherwise it is True, e.g. 769x769. Default: False.
  43. pretrained (str, optional): The path or url of pretrained model. Default: None.
  44. """
  45. def __init__(self,
  46. num_classes,
  47. backbone,
  48. backbone_indices=(0, 1, 2, 3),
  49. aspp_ratios=(1, 6, 12, 18),
  50. aspp_out_channels=256,
  51. align_corners=False,
  52. pretrained=None):
  53. super().__init__()
  54. self.backbone = backbone
  55. backbone_channels = self.backbone.feat_channels
  56. self.head = GSCNNHead(num_classes, backbone_indices, backbone_channels,
  57. aspp_ratios, 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(x, feat_list, self.backbone.conv1_logit)
  64. seg_logit, edge_logit = [
  65. F.interpolate(
  66. logit,
  67. x.shape[2:],
  68. mode='bilinear',
  69. align_corners=self.align_corners) for logit in logit_list
  70. ]
  71. return [seg_logit, (seg_logit, edge_logit), edge_logit, seg_logit]
  72. def init_weight(self):
  73. if self.pretrained is not None:
  74. utils.load_entire_model(self, self.pretrained)
  75. class GSCNNHead(nn.Layer):
  76. """
  77. The GSCNNHead implementation based on PaddlePaddle.
  78. Args:
  79. num_classes (int): The unique number of target classes.
  80. backbone_indices (tuple): Two values in the tuple indicate the indices of output of backbone.
  81. the first index will be taken as a low-level feature in Decoder component;
  82. the last one will be taken as input of ASPP component; the second to fourth
  83. will be taken as input for GCL component.
  84. Usually backbone consists of four downsampling stage, and return an output of
  85. each stage. If we set it as (0, 1, 2, 3), it means taking feature map of the first
  86. stage in backbone as low-level feature used in Decoder, feature map of the fourth
  87. stage as input of ASPP, and the feature map of the second to fourth stage as input of GCL.
  88. backbone_channels (tuple): The channels of output of backbone.
  89. aspp_ratios (tuple): The dilation rates using in ASSP module.
  90. aspp_out_channels (int): The output channels of ASPP module.
  91. align_corners (bool): An argument of F.interpolate. It should be set to False when the output size of feature
  92. is even, e.g. 1024x512, otherwise it is True, e.g. 769x769.
  93. """
  94. def __init__(self, num_classes, backbone_indices, backbone_channels,
  95. aspp_ratios, aspp_out_channels, align_corners):
  96. super().__init__()
  97. self.backbone_indices = backbone_indices
  98. self.align_corners = align_corners
  99. self.dsn1 = nn.Conv2D(
  100. backbone_channels[backbone_indices[1]], 1, kernel_size=1)
  101. self.dsn2 = nn.Conv2D(
  102. backbone_channels[backbone_indices[2]], 1, kernel_size=1)
  103. self.dsn3 = nn.Conv2D(
  104. backbone_channels[backbone_indices[3]], 1, kernel_size=1)
  105. self.res1 = resnet_vd.BasicBlock(64, 64, stride=1)
  106. self.d1 = nn.Conv2D(64, 32, kernel_size=1)
  107. self.gate1 = GatedSpatailConv2d(32, 32)
  108. self.res2 = resnet_vd.BasicBlock(32, 32, stride=1)
  109. self.d2 = nn.Conv2D(32, 16, kernel_size=1)
  110. self.gate2 = GatedSpatailConv2d(16, 16)
  111. self.res3 = resnet_vd.BasicBlock(16, 16, stride=1)
  112. self.d3 = nn.Conv2D(16, 8, kernel_size=1)
  113. self.gate3 = GatedSpatailConv2d(8, 8)
  114. self.fuse = nn.Conv2D(8, 1, kernel_size=1, bias_attr=False)
  115. self.cw = nn.Conv2D(2, 1, kernel_size=1, bias_attr=False)
  116. self.aspp = ASPPModule(
  117. aspp_ratios=aspp_ratios,
  118. in_channels=backbone_channels[-1],
  119. out_channels=aspp_out_channels,
  120. align_corners=self.align_corners,
  121. image_pooling=True)
  122. self.decoder = deeplab.Decoder(
  123. num_classes=num_classes,
  124. in_channels=backbone_channels[0],
  125. align_corners=self.align_corners)
  126. def forward(self, x, feat_list, s_input):
  127. input_shape = paddle.shape(x)
  128. m1f = F.interpolate(
  129. s_input,
  130. input_shape[2:],
  131. mode='bilinear',
  132. align_corners=self.align_corners)
  133. l1, l2, l3 = [
  134. feat_list[self.backbone_indices[i]]
  135. for i in range(1, len(self.backbone_indices))
  136. ]
  137. s1 = F.interpolate(
  138. self.dsn1(l1),
  139. input_shape[2:],
  140. mode='bilinear',
  141. align_corners=self.align_corners)
  142. s2 = F.interpolate(
  143. self.dsn2(l2),
  144. input_shape[2:],
  145. mode='bilinear',
  146. align_corners=self.align_corners)
  147. s3 = F.interpolate(
  148. self.dsn3(l3),
  149. input_shape[2:],
  150. mode='bilinear',
  151. align_corners=self.align_corners)
  152. # Get image gradient
  153. im_arr = x.numpy().transpose((0, 2, 3, 1))
  154. im_arr = ((im_arr * 0.5 + 0.5) * 255).astype(np.uint8)
  155. canny = np.zeros((input_shape[0], 1, input_shape[2], input_shape[3]))
  156. for i in range(input_shape[0]):
  157. canny[i] = cv2.Canny(im_arr[i], 10, 100)
  158. canny = canny / 255
  159. canny = paddle.to_tensor(canny).astype('float32')
  160. canny.stop_gradient = True
  161. cs = self.res1(m1f)
  162. cs = F.interpolate(
  163. cs,
  164. input_shape[2:],
  165. mode='bilinear',
  166. align_corners=self.align_corners)
  167. cs = self.d1(cs)
  168. cs = self.gate1(cs, s1)
  169. cs = self.res2(cs)
  170. cs = F.interpolate(
  171. cs,
  172. input_shape[2:],
  173. mode='bilinear',
  174. align_corners=self.align_corners)
  175. cs = self.d2(cs)
  176. cs = self.gate2(cs, s2)
  177. cs = self.res3(cs)
  178. cs = F.interpolate(
  179. cs,
  180. input_shape[2:],
  181. mode='bilinear',
  182. align_corners=self.align_corners)
  183. cs = self.d3(cs)
  184. cs = self.gate3(cs, s3)
  185. cs = self.fuse(cs)
  186. cs = F.interpolate(
  187. cs,
  188. input_shape[2:],
  189. mode='bilinear',
  190. align_corners=self.align_corners)
  191. edge_out = F.sigmoid(cs) # Ouput of shape stream
  192. cat = paddle.concat([edge_out, canny], axis=1)
  193. acts = self.cw(cat)
  194. acts = F.sigmoid(acts) # Input of fusion module
  195. x = self.aspp(l3, acts)
  196. low_level_feat = feat_list[self.backbone_indices[0]]
  197. logit = self.decoder(x, low_level_feat)
  198. logit_list = [logit, edge_out]
  199. return logit_list
  200. class GatedSpatailConv2d(nn.Layer):
  201. def __init__(self,
  202. in_channels,
  203. out_channels,
  204. kernel_size=1,
  205. stride=1,
  206. padding=0,
  207. dilation=1,
  208. groups=1,
  209. bias_attr=False):
  210. super().__init__()
  211. self._gate_conv = nn.Sequential(
  212. layers.SyncBatchNorm(in_channels + 1),
  213. nn.Conv2D(
  214. in_channels + 1, in_channels + 1, kernel_size=1),
  215. nn.ReLU(),
  216. nn.Conv2D(
  217. in_channels + 1, 1, kernel_size=1),
  218. layers.SyncBatchNorm(1),
  219. nn.Sigmoid())
  220. self.conv = nn.Conv2D(
  221. in_channels,
  222. out_channels,
  223. kernel_size=kernel_size,
  224. stride=stride,
  225. padding=padding,
  226. dilation=dilation,
  227. groups=groups,
  228. bias_attr=bias_attr)
  229. def forward(self, input_features, gating_features):
  230. cat = paddle.concat([input_features, gating_features], axis=1)
  231. alphas = self._gate_conv(cat)
  232. x = input_features * (alphas + 1)
  233. x = self.conv(x)
  234. return x
  235. class ASPPModule(nn.Layer):
  236. """
  237. Atrous Spatial Pyramid Pooling.
  238. Args:
  239. aspp_ratios (tuple): The dilation rate using in ASSP module.
  240. in_channels (int): The number of input channels.
  241. out_channels (int): The number of output channels.
  242. align_corners (bool): An argument of F.interpolate. It should be set to False when the output size of feature
  243. is even, e.g. 1024x512, otherwise it is True, e.g. 769x769.
  244. use_sep_conv (bool, optional): If using separable conv in ASPP module. Default: False.
  245. image_pooling (bool, optional): If augmented with image-level features. Default: False
  246. """
  247. def __init__(self,
  248. aspp_ratios,
  249. in_channels,
  250. out_channels,
  251. align_corners,
  252. use_sep_conv=False,
  253. image_pooling=False):
  254. super().__init__()
  255. self.align_corners = align_corners
  256. self.aspp_blocks = nn.LayerList()
  257. for ratio in aspp_ratios:
  258. if use_sep_conv and ratio > 1:
  259. conv_func = layers.SeparableConvBNReLU
  260. else:
  261. conv_func = layers.ConvBNReLU
  262. block = conv_func(
  263. in_channels=in_channels,
  264. out_channels=out_channels,
  265. kernel_size=1 if ratio == 1 else 3,
  266. dilation=ratio,
  267. padding=0 if ratio == 1 else ratio)
  268. self.aspp_blocks.append(block)
  269. out_size = len(self.aspp_blocks)
  270. if image_pooling:
  271. self.global_avg_pool = nn.Sequential(
  272. nn.AdaptiveAvgPool2D(output_size=(1, 1)),
  273. layers.ConvBNReLU(
  274. in_channels, out_channels, kernel_size=1, bias_attr=False))
  275. out_size += 1
  276. self.image_pooling = image_pooling
  277. self.edge_conv = layers.ConvBNReLU(
  278. 1, out_channels, kernel_size=1, bias_attr=False)
  279. out_size += 1
  280. self.conv_bn_relu = layers.ConvBNReLU(
  281. in_channels=out_channels * out_size,
  282. out_channels=out_channels,
  283. kernel_size=1)
  284. self.dropout = nn.Dropout(p=0.1) # drop rate
  285. def forward(self, x, edge):
  286. outputs = []
  287. x_shape = paddle.shape(x)
  288. for block in self.aspp_blocks:
  289. y = block(x)
  290. y = F.interpolate(
  291. y,
  292. x_shape[2:],
  293. mode='bilinear',
  294. align_corners=self.align_corners)
  295. outputs.append(y)
  296. if self.image_pooling:
  297. img_avg = self.global_avg_pool(x)
  298. img_avg = F.interpolate(
  299. img_avg,
  300. x_shape[2:],
  301. mode='bilinear',
  302. align_corners=self.align_corners)
  303. outputs.append(img_avg)
  304. edge_features = F.interpolate(
  305. edge,
  306. size=x_shape[2:],
  307. mode='bilinear',
  308. align_corners=self.align_corners)
  309. edge_features = self.edge_conv(edge_features)
  310. outputs.append(edge_features)
  311. x = paddle.concat(outputs, axis=1)
  312. x = self.conv_bn_relu(x)
  313. x = self.dropout(x)
  314. return x