tps.py 11 KB

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