stn.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. # copyright (c) 2020 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. """
  15. This code is refer from:
  16. https://github.com/ayumiymk/aster.pytorch/blob/master/lib/models/stn_head.py
  17. """
  18. from __future__ import absolute_import
  19. from __future__ import division
  20. from __future__ import print_function
  21. import math
  22. import paddle
  23. from paddle import nn, ParamAttr
  24. from paddle.nn import functional as F
  25. import numpy as np
  26. from .tps_spatial_transformer import TPSSpatialTransformer
  27. def conv3x3_block(in_channels, out_channels, stride=1):
  28. n = 3 * 3 * out_channels
  29. w = math.sqrt(2.0 / n)
  30. conv_layer = nn.Conv2D(
  31. in_channels,
  32. out_channels,
  33. kernel_size=3,
  34. stride=stride,
  35. padding=1,
  36. weight_attr=nn.initializer.Normal(mean=0.0, std=w),
  37. bias_attr=nn.initializer.Constant(0),
  38. )
  39. block = nn.Sequential(conv_layer, nn.BatchNorm2D(out_channels), nn.ReLU())
  40. return block
  41. class STN(nn.Layer):
  42. def __init__(self, in_channels, num_ctrlpoints, activation="none"):
  43. super(STN, self).__init__()
  44. self.in_channels = in_channels
  45. self.num_ctrlpoints = num_ctrlpoints
  46. self.activation = activation
  47. self.stn_convnet = nn.Sequential(
  48. conv3x3_block(in_channels, 32), # 32x64
  49. nn.MaxPool2D(kernel_size=2, stride=2),
  50. conv3x3_block(32, 64), # 16x32
  51. nn.MaxPool2D(kernel_size=2, stride=2),
  52. conv3x3_block(64, 128), # 8*16
  53. nn.MaxPool2D(kernel_size=2, stride=2),
  54. conv3x3_block(128, 256), # 4*8
  55. nn.MaxPool2D(kernel_size=2, stride=2),
  56. conv3x3_block(256, 256), # 2*4,
  57. nn.MaxPool2D(kernel_size=2, stride=2),
  58. conv3x3_block(256, 256),
  59. ) # 1*2
  60. self.stn_fc1 = nn.Sequential(
  61. nn.Linear(
  62. 2 * 256,
  63. 512,
  64. weight_attr=nn.initializer.Normal(0, 0.001),
  65. bias_attr=nn.initializer.Constant(0),
  66. ),
  67. nn.BatchNorm1D(512),
  68. nn.ReLU(),
  69. )
  70. fc2_bias = self.init_stn()
  71. self.stn_fc2 = nn.Linear(
  72. 512,
  73. num_ctrlpoints * 2,
  74. weight_attr=nn.initializer.Constant(0.0),
  75. bias_attr=nn.initializer.Assign(fc2_bias),
  76. )
  77. def init_stn(self):
  78. margin = 0.01
  79. sampling_num_per_side = int(self.num_ctrlpoints / 2)
  80. ctrl_pts_x = np.linspace(margin, 1.0 - margin, sampling_num_per_side)
  81. ctrl_pts_y_top = np.ones(sampling_num_per_side) * margin
  82. ctrl_pts_y_bottom = np.ones(sampling_num_per_side) * (1 - margin)
  83. ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1)
  84. ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1)
  85. ctrl_points = np.concatenate([ctrl_pts_top, ctrl_pts_bottom], axis=0).astype(
  86. np.float32
  87. )
  88. if self.activation == "none":
  89. pass
  90. elif self.activation == "sigmoid":
  91. ctrl_points = -np.log(1.0 / ctrl_points - 1.0)
  92. ctrl_points = paddle.to_tensor(ctrl_points)
  93. fc2_bias = paddle.reshape(
  94. ctrl_points, shape=[ctrl_points.shape[0] * ctrl_points.shape[1]]
  95. )
  96. return fc2_bias
  97. def forward(self, x):
  98. x = self.stn_convnet(x)
  99. batch_size, _, h, w = x.shape
  100. x = paddle.reshape(x, shape=(batch_size, -1))
  101. img_feat = self.stn_fc1(x)
  102. x = self.stn_fc2(0.1 * img_feat)
  103. if self.activation == "sigmoid":
  104. x = F.sigmoid(x)
  105. x = paddle.reshape(x, shape=[-1, self.num_ctrlpoints, 2])
  106. return img_feat, x
  107. class STN_ON(nn.Layer):
  108. def __init__(
  109. self,
  110. in_channels,
  111. tps_inputsize,
  112. tps_outputsize,
  113. num_control_points,
  114. tps_margins,
  115. stn_activation,
  116. ):
  117. super(STN_ON, self).__init__()
  118. self.tps = TPSSpatialTransformer(
  119. output_image_size=tuple(tps_outputsize),
  120. num_control_points=num_control_points,
  121. margins=tuple(tps_margins),
  122. )
  123. self.stn_head = STN(
  124. in_channels=in_channels,
  125. num_ctrlpoints=num_control_points,
  126. activation=stn_activation,
  127. )
  128. self.tps_inputsize = tps_inputsize
  129. self.out_channels = in_channels
  130. def forward(self, image):
  131. stn_input = paddle.nn.functional.interpolate(
  132. image, self.tps_inputsize, mode="bilinear", align_corners=True
  133. )
  134. stn_img_feat, ctrl_points = self.stn_head(stn_input)
  135. x, _ = self.tps(image, ctrl_points)
  136. return x