det_db_head.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. # copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import math
  18. import paddle
  19. from paddle import nn
  20. import paddle.nn.functional as F
  21. from paddle import ParamAttr
  22. from ppocr.modeling.backbones.det_mobilenet_v3 import ConvBNLayer
  23. def get_bias_attr(k):
  24. stdv = 1.0 / math.sqrt(k * 1.0)
  25. initializer = paddle.nn.initializer.Uniform(-stdv, stdv)
  26. bias_attr = ParamAttr(initializer=initializer)
  27. return bias_attr
  28. class Head(nn.Layer):
  29. def __init__(self, in_channels, kernel_list=[3, 2, 2], fix_nan=False, **kwargs):
  30. super(Head, self).__init__()
  31. self.conv1 = nn.Conv2D(
  32. in_channels=in_channels,
  33. out_channels=in_channels // 4,
  34. kernel_size=kernel_list[0],
  35. padding=int(kernel_list[0] // 2),
  36. weight_attr=ParamAttr(),
  37. bias_attr=False,
  38. )
  39. self.conv_bn1 = nn.BatchNorm(
  40. num_channels=in_channels // 4,
  41. param_attr=ParamAttr(initializer=paddle.nn.initializer.Constant(value=1.0)),
  42. bias_attr=ParamAttr(initializer=paddle.nn.initializer.Constant(value=1e-4)),
  43. act="relu",
  44. )
  45. self.conv2 = nn.Conv2DTranspose(
  46. in_channels=in_channels // 4,
  47. out_channels=in_channels // 4,
  48. kernel_size=kernel_list[1],
  49. stride=2,
  50. weight_attr=ParamAttr(initializer=paddle.nn.initializer.KaimingUniform()),
  51. bias_attr=get_bias_attr(in_channels // 4),
  52. )
  53. self.conv_bn2 = nn.BatchNorm(
  54. num_channels=in_channels // 4,
  55. param_attr=ParamAttr(initializer=paddle.nn.initializer.Constant(value=1.0)),
  56. bias_attr=ParamAttr(initializer=paddle.nn.initializer.Constant(value=1e-4)),
  57. act="relu",
  58. )
  59. self.conv3 = nn.Conv2DTranspose(
  60. in_channels=in_channels // 4,
  61. out_channels=1,
  62. kernel_size=kernel_list[2],
  63. stride=2,
  64. weight_attr=ParamAttr(initializer=paddle.nn.initializer.KaimingUniform()),
  65. bias_attr=get_bias_attr(in_channels // 4),
  66. )
  67. self.fix_nan = fix_nan
  68. def forward(self, x, return_f=False):
  69. x = self.conv1(x)
  70. x = self.conv_bn1(x)
  71. if self.fix_nan and self.training:
  72. x = paddle.where(paddle.isnan(x), paddle.zeros_like(x), x)
  73. x = self.conv2(x)
  74. x = self.conv_bn2(x)
  75. if self.fix_nan and self.training:
  76. x = paddle.where(paddle.isnan(x), paddle.zeros_like(x), x)
  77. if return_f is True:
  78. f = x
  79. x = self.conv3(x)
  80. x = F.sigmoid(x)
  81. if return_f is True:
  82. return x, f
  83. return x
  84. class DBHead(nn.Layer):
  85. """
  86. Differentiable Binarization (DB) for text detection:
  87. see https://arxiv.org/abs/1911.08947
  88. args:
  89. params(dict): super parameters for build DB network
  90. """
  91. def __init__(self, in_channels, k=50, **kwargs):
  92. super(DBHead, self).__init__()
  93. self.k = k
  94. self.binarize = Head(in_channels, **kwargs)
  95. self.thresh = Head(in_channels, **kwargs)
  96. def step_function(self, x, y):
  97. return paddle.reciprocal(1 + paddle.exp(-self.k * (x - y)))
  98. def forward(self, x, targets=None):
  99. shrink_maps = self.binarize(x)
  100. if not self.training:
  101. return {"maps": shrink_maps}
  102. threshold_maps = self.thresh(x)
  103. binary_maps = self.step_function(shrink_maps, threshold_maps)
  104. y = paddle.concat([shrink_maps, threshold_maps, binary_maps], axis=1)
  105. return {"maps": y}
  106. class LocalModule(nn.Layer):
  107. def __init__(self, in_c, mid_c, use_distance=True):
  108. super(self.__class__, self).__init__()
  109. self.last_3 = ConvBNLayer(in_c + 1, mid_c, 3, 1, 1, act="relu")
  110. self.last_1 = nn.Conv2D(mid_c, 1, 1, 1, 0)
  111. def forward(self, x, init_map, distance_map):
  112. outf = paddle.concat([init_map, x], axis=1)
  113. # last Conv
  114. out = self.last_1(self.last_3(outf))
  115. return out
  116. class PFHeadLocal(DBHead):
  117. def __init__(self, in_channels, k=50, mode="small", **kwargs):
  118. super(PFHeadLocal, self).__init__(in_channels, k, **kwargs)
  119. self.mode = mode
  120. self.up_conv = nn.Upsample(scale_factor=2, mode="nearest", align_mode=1)
  121. if self.mode == "large":
  122. self.cbn_layer = LocalModule(in_channels // 4, in_channels // 4)
  123. elif self.mode == "small":
  124. self.cbn_layer = LocalModule(in_channels // 4, in_channels // 8)
  125. def forward(self, x, targets=None):
  126. shrink_maps, f = self.binarize(x, return_f=True)
  127. base_maps = shrink_maps
  128. cbn_maps = self.cbn_layer(self.up_conv(f), shrink_maps, None)
  129. cbn_maps = F.sigmoid(cbn_maps)
  130. if not self.training:
  131. return {"maps": 0.5 * (base_maps + cbn_maps)}
  132. threshold_maps = self.thresh(x)
  133. binary_maps = self.step_function(shrink_maps, threshold_maps)
  134. y = paddle.concat([cbn_maps, threshold_maps, binary_maps], axis=1)
  135. return {"maps": y, "distance_maps": cbn_maps, "cbn_maps": binary_maps}