tps.py 11 KB

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