deeplabv3p.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. # coding: utf8
  2. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from __future__ import absolute_import
  16. from __future__ import division
  17. from __future__ import print_function
  18. from collections import OrderedDict
  19. import paddle.fluid as fluid
  20. from .model_utils.libs import scope, name_scope
  21. from .model_utils.libs import bn, bn_relu, relu, qsigmoid
  22. from .model_utils.libs import conv, max_pool, deconv
  23. from .model_utils.libs import separate_conv
  24. from .model_utils.libs import sigmoid_to_softmax
  25. from .model_utils.loss import softmax_with_loss
  26. from .model_utils.loss import dice_loss
  27. from .model_utils.loss import bce_loss
  28. from paddlex.cv.nets.xception import Xception
  29. from paddlex.cv.nets.mobilenet_v2 import MobileNetV2
  30. class DeepLabv3p(object):
  31. """实现DeepLabv3+模型
  32. `"Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation"
  33. <https://arxiv.org/abs/1802.02611>`
  34. Args:
  35. num_classes (int): 类别数。
  36. backbone (paddlex.cv.nets): 神经网络,实现DeepLabv3+特征图的计算。
  37. mode (str): 网络运行模式,根据mode构建网络的输入和返回。
  38. 当mode为'train'时,输入为image(-1, 3, -1, -1)和label (-1, 1, -1, -1) 返回loss。
  39. 当mode为'train'时,输入为image (-1, 3, -1, -1)和label (-1, 1, -1, -1),返回loss,
  40. pred (与网络输入label 相同大小的预测结果,值代表相应的类别),label,mask(非忽略值的mask,
  41. 与label相同大小,bool类型)。
  42. 当mode为'test'时,输入为image(-1, 3, -1, -1)返回pred (-1, 1, -1, -1)和
  43. logit (-1, num_classes, -1, -1) 通道维上代表每一类的概率值。
  44. output_stride (int): backbone 输出特征图相对于输入的下采样倍数,一般取值为8或16。
  45. aspp_with_sep_conv (bool): 在asspp模块是否采用separable convolutions。
  46. decoder_use_sep_conv (bool): decoder模块是否采用separable convolutions。
  47. encoder_with_aspp (bool): 是否在encoder阶段采用aspp模块。
  48. enable_decoder (bool): 是否使用decoder模块。
  49. use_bce_loss (bool): 是否使用bce loss作为网络的损失函数,只能用于两类分割。可与dice loss同时使用。
  50. use_dice_loss (bool): 是否使用dice loss作为网络的损失函数,只能用于两类分割,可与bce loss同时使用。
  51. 当use_bce_loss和use_dice_loss都为False时,使用交叉熵损失函数。
  52. class_weight (list/str): 交叉熵损失函数各类损失的权重。当class_weight为list的时候,长度应为
  53. num_classes。当class_weight为str时, weight.lower()应为'dynamic',这时会根据每一轮各类像素的比重
  54. 自行计算相应的权重,每一类的权重为:每类的比例 * num_classes。class_weight取默认值None是,各类的权重1,
  55. 即平时使用的交叉熵损失函数。
  56. ignore_index (int): label上忽略的值,label为ignore_index的像素不参与损失函数的计算。
  57. fixed_input_shape (list): 长度为2,维度为1的list,如:[640,720],用来固定模型输入:'image'的shape,默认为None。
  58. Raises:
  59. ValueError: use_bce_loss或use_dice_loss为真且num_calsses > 2。
  60. ValueError: class_weight为list, 但长度不等于num_class。
  61. class_weight为str, 但class_weight.low()不等于dynamic。
  62. TypeError: class_weight不为None时,其类型不是list或str。
  63. """
  64. def __init__(self,
  65. num_classes,
  66. backbone,
  67. mode='train',
  68. output_stride=16,
  69. aspp_with_sep_conv=True,
  70. decoder_use_sep_conv=True,
  71. encoder_with_aspp=True,
  72. enable_decoder=True,
  73. use_bce_loss=False,
  74. use_dice_loss=False,
  75. class_weight=None,
  76. ignore_index=255,
  77. fixed_input_shape=None,
  78. pooling_stride=[1, 1],
  79. pooling_crop_size=None,
  80. aspp_with_se=False,
  81. se_use_qsigmoid=False,
  82. aspp_convs_filters=256,
  83. aspp_with_concat_projection=True,
  84. add_image_level_feature=True,
  85. use_sum_merge=False,
  86. conv_filters=256,
  87. output_is_logits=False):
  88. # dice_loss或bce_loss只适用两类分割中
  89. if num_classes > 2 and (use_bce_loss or use_dice_loss):
  90. raise ValueError(
  91. "dice loss and bce loss is only applicable to binary classfication"
  92. )
  93. if class_weight is not None:
  94. if isinstance(class_weight, list):
  95. if len(class_weight) != num_classes:
  96. raise ValueError(
  97. "Length of class_weight should be equal to number of classes"
  98. )
  99. elif isinstance(class_weight, str):
  100. if class_weight.lower() != 'dynamic':
  101. raise ValueError(
  102. "if class_weight is string, must be dynamic!")
  103. else:
  104. raise TypeError(
  105. 'Expect class_weight is a list or string but receive {}'.
  106. format(type(class_weight)))
  107. self.num_classes = num_classes
  108. self.backbone = backbone
  109. self.mode = mode
  110. self.use_bce_loss = use_bce_loss
  111. self.use_dice_loss = use_dice_loss
  112. self.class_weight = class_weight
  113. self.ignore_index = ignore_index
  114. self.output_stride = output_stride
  115. self.aspp_with_sep_conv = aspp_with_sep_conv
  116. self.decoder_use_sep_conv = decoder_use_sep_conv
  117. self.encoder_with_aspp = encoder_with_aspp
  118. self.enable_decoder = enable_decoder
  119. self.fixed_input_shape = fixed_input_shape
  120. self.output_is_logits = output_is_logits
  121. self.aspp_convs_filters = aspp_convs_filters
  122. self.output_stride = output_stride
  123. self.pooling_crop_size = pooling_crop_size
  124. self.pooling_stride = pooling_stride
  125. self.se_use_qsigmoid = se_use_qsigmoid
  126. self.aspp_with_concat_projection = aspp_with_concat_projection
  127. self.add_image_level_feature = add_image_level_feature
  128. self.aspp_with_se = aspp_with_se
  129. self.use_sum_merge = use_sum_merge
  130. self.conv_filters = conv_filters
  131. def _encoder(self, input):
  132. # 编码器配置,采用ASPP架构,pooling + 1x1_conv + 三个不同尺度的空洞卷积并行, concat后1x1conv
  133. # ASPP_WITH_SEP_CONV:默认为真,使用depthwise可分离卷积,否则使用普通卷积
  134. # OUTPUT_STRIDE: 下采样倍数,8或16,决定aspp_ratios大小
  135. # aspp_ratios:ASPP模块空洞卷积的采样率
  136. if self.output_stride == 16:
  137. aspp_ratios = [6, 12, 18]
  138. elif self.output_stride == 8:
  139. aspp_ratios = [12, 24, 36]
  140. else:
  141. aspp_ratios = []
  142. param_attr = fluid.ParamAttr(
  143. name=name_scope + 'weights',
  144. regularizer=None,
  145. initializer=fluid.initializer.TruncatedNormal(
  146. loc=0.0, scale=0.06))
  147. concat_logits = []
  148. with scope('encoder'):
  149. channel = self.aspp_convs_filters
  150. with scope("image_pool"):
  151. if self.pooling_crop_size is None:
  152. image_avg = fluid.layers.reduce_mean(
  153. input, [2, 3], keep_dim=True)
  154. else:
  155. pool_w = int((self.pooling_crop_size[0] - 1.0) /
  156. self.output_stride + 1.0)
  157. pool_h = int((self.pooling_crop_size[1] - 1.0) /
  158. self.output_stride + 1.0)
  159. image_avg = fluid.layers.pool2d(
  160. input,
  161. pool_size=(pool_h, pool_w),
  162. pool_stride=self.pooling_stride,
  163. pool_type='avg',
  164. pool_padding='VALID')
  165. act = qsigmoid if self.se_use_qsigmoid else bn_relu
  166. image_avg = act(
  167. conv(
  168. image_avg,
  169. channel,
  170. 1,
  171. 1,
  172. groups=1,
  173. padding=0,
  174. param_attr=param_attr))
  175. input_shape = fluid.layers.shape(input)
  176. image_avg = fluid.layers.resize_bilinear(image_avg,
  177. input_shape[2:])
  178. if self.add_image_level_feature:
  179. concat_logits.append(image_avg)
  180. with scope("aspp0"):
  181. aspp0 = bn_relu(
  182. conv(
  183. input,
  184. channel,
  185. 1,
  186. 1,
  187. groups=1,
  188. padding=0,
  189. param_attr=param_attr))
  190. concat_logits.append(aspp0)
  191. if aspp_ratios:
  192. with scope("aspp1"):
  193. if self.aspp_with_sep_conv:
  194. aspp1 = separate_conv(
  195. input,
  196. channel,
  197. 1,
  198. 3,
  199. dilation=aspp_ratios[0],
  200. act=relu)
  201. else:
  202. aspp1 = bn_relu(
  203. conv(
  204. input,
  205. channel,
  206. stride=1,
  207. filter_size=3,
  208. dilation=aspp_ratios[0],
  209. padding=aspp_ratios[0],
  210. param_attr=param_attr))
  211. concat_logits.append(aspp1)
  212. with scope("aspp2"):
  213. if self.aspp_with_sep_conv:
  214. aspp2 = separate_conv(
  215. input,
  216. channel,
  217. 1,
  218. 3,
  219. dilation=aspp_ratios[1],
  220. act=relu)
  221. else:
  222. aspp2 = bn_relu(
  223. conv(
  224. input,
  225. channel,
  226. stride=1,
  227. filter_size=3,
  228. dilation=aspp_ratios[1],
  229. padding=aspp_ratios[1],
  230. param_attr=param_attr))
  231. concat_logits.append(aspp2)
  232. with scope("aspp3"):
  233. if self.aspp_with_sep_conv:
  234. aspp3 = separate_conv(
  235. input,
  236. channel,
  237. 1,
  238. 3,
  239. dilation=aspp_ratios[2],
  240. act=relu)
  241. else:
  242. aspp3 = bn_relu(
  243. conv(
  244. input,
  245. channel,
  246. stride=1,
  247. filter_size=3,
  248. dilation=aspp_ratios[2],
  249. padding=aspp_ratios[2],
  250. param_attr=param_attr))
  251. concat_logits.append(aspp3)
  252. with scope("concat"):
  253. data = fluid.layers.concat(concat_logits, axis=1)
  254. if self.aspp_with_concat_projection:
  255. data = bn_relu(
  256. conv(
  257. data,
  258. channel,
  259. 1,
  260. 1,
  261. groups=1,
  262. padding=0,
  263. param_attr=param_attr))
  264. data = fluid.layers.dropout(data, 0.9)
  265. if self.aspp_with_se:
  266. data = data * image_avg
  267. return data
  268. def _decoder_with_sum_merge(self, encode_data, decode_shortcut,
  269. param_attr):
  270. decode_shortcut_shape = fluid.layers.shape(decode_shortcut)
  271. encode_data = fluid.layers.resize_bilinear(encode_data,
  272. decode_shortcut_shape[2:])
  273. encode_data = conv(
  274. encode_data,
  275. self.conv_filters,
  276. 1,
  277. 1,
  278. groups=1,
  279. padding=0,
  280. param_attr=param_attr)
  281. with scope('merge'):
  282. decode_shortcut = conv(
  283. decode_shortcut,
  284. self.conv_filters,
  285. 1,
  286. 1,
  287. groups=1,
  288. padding=0,
  289. param_attr=param_attr)
  290. return encode_data + decode_shortcut
  291. def _decoder_with_concat(self, encode_data, decode_shortcut, param_attr):
  292. with scope('concat'):
  293. decode_shortcut = bn_relu(
  294. conv(
  295. decode_shortcut,
  296. 48,
  297. 1,
  298. 1,
  299. groups=1,
  300. padding=0,
  301. param_attr=param_attr))
  302. decode_shortcut_shape = fluid.layers.shape(decode_shortcut)
  303. encode_data = fluid.layers.resize_bilinear(
  304. encode_data, decode_shortcut_shape[2:])
  305. encode_data = fluid.layers.concat(
  306. [encode_data, decode_shortcut], axis=1)
  307. if self.decoder_use_sep_conv:
  308. with scope("separable_conv1"):
  309. encode_data = separate_conv(
  310. encode_data, self.conv_filters, 1, 3, dilation=1, act=relu)
  311. with scope("separable_conv2"):
  312. encode_data = separate_conv(
  313. encode_data, self.conv_filters, 1, 3, dilation=1, act=relu)
  314. else:
  315. with scope("decoder_conv1"):
  316. encode_data = bn_relu(
  317. conv(
  318. encode_data,
  319. self.conv_filters,
  320. stride=1,
  321. filter_size=3,
  322. dilation=1,
  323. padding=1,
  324. param_attr=param_attr))
  325. with scope("decoder_conv2"):
  326. encode_data = bn_relu(
  327. conv(
  328. encode_data,
  329. self.conv_filters,
  330. stride=1,
  331. filter_size=3,
  332. dilation=1,
  333. padding=1,
  334. param_attr=param_attr))
  335. return encode_data
  336. def _decoder(self, encode_data, decode_shortcut):
  337. # 解码器配置
  338. # encode_data:编码器输出
  339. # decode_shortcut: 从backbone引出的分支, resize后与encode_data concat
  340. # decoder_use_sep_conv: 默认为真,则concat后连接两个可分离卷积,否则为普通卷积
  341. param_attr = fluid.ParamAttr(
  342. name=name_scope + 'weights',
  343. regularizer=None,
  344. initializer=fluid.initializer.TruncatedNormal(
  345. loc=0.0, scale=0.06))
  346. with scope('decoder'):
  347. if self.use_sum_merge:
  348. return self._decoder_with_sum_merge(
  349. encode_data, decode_shortcut, param_attr)
  350. return self._decoder_with_concat(encode_data, decode_shortcut,
  351. param_attr)
  352. def _get_loss(self, logit, label, mask):
  353. avg_loss = 0
  354. if not (self.use_dice_loss or self.use_bce_loss):
  355. avg_loss += softmax_with_loss(
  356. logit,
  357. label,
  358. mask,
  359. num_classes=self.num_classes,
  360. weight=self.class_weight,
  361. ignore_index=self.ignore_index)
  362. else:
  363. if self.use_dice_loss:
  364. avg_loss += dice_loss(logit, label, mask)
  365. if self.use_bce_loss:
  366. avg_loss += bce_loss(
  367. logit, label, mask, ignore_index=self.ignore_index)
  368. return avg_loss
  369. def generate_inputs(self):
  370. inputs = OrderedDict()
  371. if self.fixed_input_shape is not None:
  372. input_shape = [
  373. None, 3, self.fixed_input_shape[1], self.fixed_input_shape[0]
  374. ]
  375. inputs['image'] = fluid.data(
  376. dtype='float32', shape=input_shape, name='image')
  377. else:
  378. inputs['image'] = fluid.data(
  379. dtype='float32', shape=[None, 3, None, None], name='image')
  380. if self.mode == 'train':
  381. inputs['label'] = fluid.data(
  382. dtype='int32', shape=[None, 1, None, None], name='label')
  383. return inputs
  384. def build_net(self, inputs):
  385. # 在两类分割情况下,当loss函数选择dice_loss或bce_loss的时候,最后logit输出通道数设置为1
  386. if self.use_dice_loss or self.use_bce_loss:
  387. self.num_classes = 1
  388. image = inputs['image']
  389. if 'MobileNetV3' in self.backbone.__class__.__name__:
  390. data, decode_shortcut = self.backbone(image)
  391. else:
  392. data, decode_shortcuts = self.backbone(image)
  393. decode_shortcut = decode_shortcuts[self.backbone.decode_points]
  394. # 编码器解码器设置
  395. if self.encoder_with_aspp:
  396. data = self._encoder(data)
  397. if self.enable_decoder:
  398. data = self._decoder(data, decode_shortcut)
  399. # 根据类别数设置最后一个卷积层输出,并resize到图片原始尺寸
  400. param_attr = fluid.ParamAttr(
  401. name=name_scope + 'weights',
  402. regularizer=fluid.regularizer.L2DecayRegularizer(
  403. regularization_coeff=0.0),
  404. initializer=fluid.initializer.TruncatedNormal(
  405. loc=0.0, scale=0.01))
  406. if not self.output_is_logits:
  407. with scope('logit'):
  408. with fluid.name_scope('last_conv'):
  409. logit = conv(
  410. data,
  411. self.num_classes,
  412. 1,
  413. stride=1,
  414. padding=0,
  415. bias_attr=True,
  416. param_attr=param_attr)
  417. else:
  418. logit = data
  419. image_shape = fluid.layers.shape(image)
  420. logit = fluid.layers.resize_bilinear(logit, image_shape[2:])
  421. if self.num_classes == 1:
  422. out = sigmoid_to_softmax(logit)
  423. out = fluid.layers.transpose(out, [0, 2, 3, 1])
  424. else:
  425. out = fluid.layers.transpose(logit, [0, 2, 3, 1])
  426. pred = fluid.layers.argmax(out, axis=3)
  427. pred = fluid.layers.unsqueeze(pred, axes=[3])
  428. if self.mode == 'train':
  429. label = inputs['label']
  430. mask = label != self.ignore_index
  431. return self._get_loss(logit, label, mask)
  432. elif self.mode == 'eval':
  433. label = inputs['label']
  434. mask = label != self.ignore_index
  435. loss = self._get_loss(logit, label, mask)
  436. return loss, pred, label, mask
  437. else:
  438. if self.num_classes == 1:
  439. logit = sigmoid_to_softmax(logit)
  440. else:
  441. logit = fluid.layers.softmax(logit, axis=1)
  442. return pred, logit
  443. return logit