tps.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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/clovaai/deep-text-recognition-benchmark/blob/master/modules/transformation.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. class ConvBNLayer(nn.Layer):
  27. def __init__(self,
  28. in_channels,
  29. out_channels,
  30. kernel_size,
  31. stride=1,
  32. groups=1,
  33. act=None,
  34. name=None):
  35. super(ConvBNLayer, self).__init__()
  36. self.conv = nn.Conv2D(
  37. in_channels=in_channels,
  38. out_channels=out_channels,
  39. kernel_size=kernel_size,
  40. stride=stride,
  41. padding=(kernel_size - 1) // 2,
  42. groups=groups,
  43. weight_attr=ParamAttr(name=name + "_weights"),
  44. bias_attr=False)
  45. bn_name = "bn_" + name
  46. self.bn = nn.BatchNorm(
  47. out_channels,
  48. act=act,
  49. param_attr=ParamAttr(name=bn_name + '_scale'),
  50. bias_attr=ParamAttr(bn_name + '_offset'),
  51. moving_mean_name=bn_name + '_mean',
  52. moving_variance_name=bn_name + '_variance')
  53. def forward(self, x):
  54. x = self.conv(x)
  55. x = self.bn(x)
  56. return x
  57. class LocalizationNetwork(nn.Layer):
  58. def __init__(self, in_channels, num_fiducial, loc_lr, model_name):
  59. super(LocalizationNetwork, self).__init__()
  60. self.F = num_fiducial
  61. F = num_fiducial
  62. if model_name == "large":
  63. num_filters_list = [64, 128, 256, 512]
  64. fc_dim = 256
  65. else:
  66. num_filters_list = [16, 32, 64, 128]
  67. fc_dim = 64
  68. self.block_list = []
  69. for fno in range(0, len(num_filters_list)):
  70. num_filters = num_filters_list[fno]
  71. name = "loc_conv%d" % fno
  72. conv = self.add_sublayer(
  73. name,
  74. ConvBNLayer(
  75. in_channels=in_channels,
  76. out_channels=num_filters,
  77. kernel_size=3,
  78. act='relu',
  79. name=name))
  80. self.block_list.append(conv)
  81. if fno == len(num_filters_list) - 1:
  82. pool = nn.AdaptiveAvgPool2D(1)
  83. else:
  84. pool = nn.MaxPool2D(kernel_size=2, stride=2, padding=0)
  85. in_channels = num_filters
  86. self.block_list.append(pool)
  87. name = "loc_fc1"
  88. stdv = 1.0 / math.sqrt(num_filters_list[-1] * 1.0)
  89. self.fc1 = nn.Linear(
  90. in_channels,
  91. fc_dim,
  92. weight_attr=ParamAttr(
  93. learning_rate=loc_lr,
  94. name=name + "_w",
  95. initializer=nn.initializer.Uniform(-stdv, stdv)),
  96. bias_attr=ParamAttr(name=name + '.b_0'),
  97. name=name)
  98. # Init fc2 in LocalizationNetwork
  99. initial_bias = self.get_initial_fiducials()
  100. initial_bias = initial_bias.reshape(-1)
  101. name = "loc_fc2"
  102. param_attr = ParamAttr(
  103. learning_rate=loc_lr,
  104. initializer=nn.initializer.Assign(np.zeros([fc_dim, F * 2])),
  105. name=name + "_w")
  106. bias_attr = ParamAttr(
  107. learning_rate=loc_lr,
  108. initializer=nn.initializer.Assign(initial_bias),
  109. name=name + "_b")
  110. self.fc2 = nn.Linear(
  111. fc_dim,
  112. F * 2,
  113. weight_attr=param_attr,
  114. bias_attr=bias_attr,
  115. name=name)
  116. self.out_channels = F * 2
  117. def forward(self, x):
  118. """
  119. Estimating parameters of geometric transformation
  120. Args:
  121. image: input
  122. Return:
  123. batch_C_prime: the matrix of the geometric transformation
  124. """
  125. B = x.shape[0]
  126. i = 0
  127. for block in self.block_list:
  128. x = block(x)
  129. x = x.squeeze(axis=2).squeeze(axis=2)
  130. x = self.fc1(x)
  131. x = F.relu(x)
  132. x = self.fc2(x)
  133. x = x.reshape(shape=[-1, self.F, 2])
  134. return x
  135. def get_initial_fiducials(self):
  136. """ see RARE paper Fig. 6 (a) """
  137. F = self.F
  138. ctrl_pts_x = np.linspace(-1.0, 1.0, int(F / 2))
  139. ctrl_pts_y_top = np.linspace(0.0, -1.0, num=int(F / 2))
  140. ctrl_pts_y_bottom = np.linspace(1.0, 0.0, num=int(F / 2))
  141. ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1)
  142. ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1)
  143. initial_bias = np.concatenate([ctrl_pts_top, ctrl_pts_bottom], axis=0)
  144. return initial_bias
  145. class GridGenerator(nn.Layer):
  146. def __init__(self, in_channels, num_fiducial):
  147. super(GridGenerator, self).__init__()
  148. self.eps = 1e-6
  149. self.F = num_fiducial
  150. name = "ex_fc"
  151. initializer = nn.initializer.Constant(value=0.0)
  152. param_attr = ParamAttr(
  153. learning_rate=0.0, initializer=initializer, name=name + "_w")
  154. bias_attr = ParamAttr(
  155. learning_rate=0.0, initializer=initializer, name=name + "_b")
  156. self.fc = nn.Linear(
  157. in_channels,
  158. 6,
  159. weight_attr=param_attr,
  160. bias_attr=bias_attr,
  161. name=name)
  162. def forward(self, batch_C_prime, I_r_size):
  163. """
  164. Generate the grid for the grid_sampler.
  165. Args:
  166. batch_C_prime: the matrix of the geometric transformation
  167. I_r_size: the shape of the input image
  168. Return:
  169. batch_P_prime: the grid for the grid_sampler
  170. """
  171. C = self.build_C_paddle()
  172. P = self.build_P_paddle(I_r_size)
  173. inv_delta_C_tensor = self.build_inv_delta_C_paddle(C).astype('float32')
  174. P_hat_tensor = self.build_P_hat_paddle(
  175. C, paddle.to_tensor(P)).astype('float32')
  176. inv_delta_C_tensor.stop_gradient = True
  177. P_hat_tensor.stop_gradient = True
  178. batch_C_ex_part_tensor = self.get_expand_tensor(batch_C_prime)
  179. batch_C_ex_part_tensor.stop_gradient = True
  180. batch_C_prime_with_zeros = paddle.concat(
  181. [batch_C_prime, batch_C_ex_part_tensor], axis=1)
  182. batch_T = paddle.matmul(inv_delta_C_tensor, batch_C_prime_with_zeros)
  183. batch_P_prime = paddle.matmul(P_hat_tensor, batch_T)
  184. return batch_P_prime
  185. def build_C_paddle(self):
  186. """ Return coordinates of fiducial points in I_r; C """
  187. F = self.F
  188. ctrl_pts_x = paddle.linspace(-1.0, 1.0, int(F / 2), dtype='float64')
  189. ctrl_pts_y_top = -1 * paddle.ones([int(F / 2)], dtype='float64')
  190. ctrl_pts_y_bottom = paddle.ones([int(F / 2)], dtype='float64')
  191. ctrl_pts_top = paddle.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1)
  192. ctrl_pts_bottom = paddle.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1)
  193. C = paddle.concat([ctrl_pts_top, ctrl_pts_bottom], axis=0)
  194. return C # F x 2
  195. def build_P_paddle(self, I_r_size):
  196. I_r_height, I_r_width = I_r_size
  197. I_r_grid_x = (paddle.arange(
  198. -I_r_width, I_r_width, 2, dtype='float64') + 1.0
  199. ) / paddle.to_tensor(np.array([I_r_width]))
  200. I_r_grid_y = (paddle.arange(
  201. -I_r_height, I_r_height, 2, dtype='float64') + 1.0
  202. ) / paddle.to_tensor(np.array([I_r_height]))
  203. # P: self.I_r_width x self.I_r_height x 2
  204. P = paddle.stack(paddle.meshgrid(I_r_grid_x, I_r_grid_y), axis=2)
  205. P = paddle.transpose(P, perm=[1, 0, 2])
  206. # n (= self.I_r_width x self.I_r_height) x 2
  207. return P.reshape([-1, 2])
  208. def build_inv_delta_C_paddle(self, C):
  209. """ Return inv_delta_C which is needed to calculate T """
  210. F = self.F
  211. hat_eye = paddle.eye(F, dtype='float64') # F x F
  212. hat_C = paddle.norm(
  213. C.reshape([1, F, 2]) - C.reshape([F, 1, 2]), axis=2) + hat_eye
  214. hat_C = (hat_C**2) * paddle.log(hat_C)
  215. delta_C = paddle.concat( # F+3 x F+3
  216. [
  217. paddle.concat(
  218. [paddle.ones(
  219. (F, 1), dtype='float64'), C, hat_C], axis=1), # F x F+3
  220. paddle.concat(
  221. [
  222. paddle.zeros(
  223. (2, 3), dtype='float64'), paddle.transpose(
  224. C, perm=[1, 0])
  225. ],
  226. axis=1), # 2 x F+3
  227. paddle.concat(
  228. [
  229. paddle.zeros(
  230. (1, 3), dtype='float64'), paddle.ones(
  231. (1, F), dtype='float64')
  232. ],
  233. axis=1) # 1 x F+3
  234. ],
  235. axis=0)
  236. inv_delta_C = paddle.inverse(delta_C)
  237. return inv_delta_C # F+3 x F+3
  238. def build_P_hat_paddle(self, C, P):
  239. F = self.F
  240. eps = self.eps
  241. n = P.shape[0] # n (= self.I_r_width x self.I_r_height)
  242. # P_tile: n x 2 -> n x 1 x 2 -> n x F x 2
  243. P_tile = paddle.tile(paddle.unsqueeze(P, axis=1), (1, F, 1))
  244. C_tile = paddle.unsqueeze(C, axis=0) # 1 x F x 2
  245. P_diff = P_tile - C_tile # n x F x 2
  246. # rbf_norm: n x F
  247. rbf_norm = paddle.norm(P_diff, p=2, axis=2, keepdim=False)
  248. # rbf: n x F
  249. rbf = paddle.multiply(
  250. paddle.square(rbf_norm), paddle.log(rbf_norm + eps))
  251. P_hat = paddle.concat(
  252. [paddle.ones(
  253. (n, 1), dtype='float64'), P, rbf], axis=1)
  254. return P_hat # n x F+3
  255. def get_expand_tensor(self, batch_C_prime):
  256. B, H, C = batch_C_prime.shape
  257. batch_C_prime = batch_C_prime.reshape([B, H * C])
  258. batch_C_ex_part_tensor = self.fc(batch_C_prime)
  259. batch_C_ex_part_tensor = batch_C_ex_part_tensor.reshape([-1, 3, 2])
  260. return batch_C_ex_part_tensor
  261. class TPS(nn.Layer):
  262. def __init__(self, in_channels, num_fiducial, loc_lr, model_name):
  263. super(TPS, self).__init__()
  264. self.loc_net = LocalizationNetwork(in_channels, num_fiducial, loc_lr,
  265. model_name)
  266. self.grid_generator = GridGenerator(self.loc_net.out_channels,
  267. num_fiducial)
  268. self.out_channels = in_channels
  269. def forward(self, image):
  270. image.stop_gradient = False
  271. batch_C_prime = self.loc_net(image)
  272. batch_P_prime = self.grid_generator(batch_C_prime, image.shape[2:])
  273. batch_P_prime = batch_P_prime.reshape(
  274. [-1, image.shape[2], image.shape[3], 2])
  275. batch_I_r = F.grid_sample(x=image, grid=batch_P_prime)
  276. return batch_I_r