tps_spatial_transformer.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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/tps_spatial_transformer.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. import itertools
  27. def grid_sample(input, grid, canvas=None):
  28. input.stop_gradient = False
  29. output = F.grid_sample(input, grid)
  30. if canvas is None:
  31. return output
  32. else:
  33. input_mask = paddle.ones(shape=input.shape)
  34. output_mask = F.grid_sample(input_mask, grid)
  35. padded_output = output * output_mask + canvas * (1 - output_mask)
  36. return padded_output
  37. # phi(x1, x2) = r^2 * log(r), where r = ||x1 - x2||_2
  38. def compute_partial_repr(input_points, control_points):
  39. N = input_points.shape[0]
  40. M = control_points.shape[0]
  41. pairwise_diff = paddle.reshape(
  42. input_points, shape=[N, 1, 2]) - paddle.reshape(
  43. control_points, shape=[1, M, 2])
  44. # original implementation, very slow
  45. # pairwise_dist = torch.sum(pairwise_diff ** 2, dim = 2) # square of distance
  46. pairwise_diff_square = pairwise_diff * pairwise_diff
  47. pairwise_dist = pairwise_diff_square[:, :, 0] + pairwise_diff_square[:, :,
  48. 1]
  49. repr_matrix = 0.5 * pairwise_dist * paddle.log(pairwise_dist)
  50. # fix numerical error for 0 * log(0), substitute all nan with 0
  51. mask = np.array(repr_matrix != repr_matrix)
  52. repr_matrix[mask] = 0
  53. return repr_matrix
  54. # output_ctrl_pts are specified, according to our task.
  55. def build_output_control_points(num_control_points, margins):
  56. margin_x, margin_y = margins
  57. num_ctrl_pts_per_side = num_control_points // 2
  58. ctrl_pts_x = np.linspace(margin_x, 1.0 - margin_x, num_ctrl_pts_per_side)
  59. ctrl_pts_y_top = np.ones(num_ctrl_pts_per_side) * margin_y
  60. ctrl_pts_y_bottom = np.ones(num_ctrl_pts_per_side) * (1.0 - margin_y)
  61. ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1)
  62. ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1)
  63. output_ctrl_pts_arr = np.concatenate(
  64. [ctrl_pts_top, ctrl_pts_bottom], axis=0)
  65. output_ctrl_pts = paddle.to_tensor(output_ctrl_pts_arr)
  66. return output_ctrl_pts
  67. class TPSSpatialTransformer(nn.Layer):
  68. def __init__(self,
  69. output_image_size=None,
  70. num_control_points=None,
  71. margins=None):
  72. super(TPSSpatialTransformer, self).__init__()
  73. self.output_image_size = output_image_size
  74. self.num_control_points = num_control_points
  75. self.margins = margins
  76. self.target_height, self.target_width = output_image_size
  77. target_control_points = build_output_control_points(num_control_points,
  78. margins)
  79. N = num_control_points
  80. # create padded kernel matrix
  81. forward_kernel = paddle.zeros(shape=[N + 3, N + 3])
  82. target_control_partial_repr = compute_partial_repr(
  83. target_control_points, target_control_points)
  84. target_control_partial_repr = paddle.cast(target_control_partial_repr,
  85. forward_kernel.dtype)
  86. forward_kernel[:N, :N] = target_control_partial_repr
  87. forward_kernel[:N, -3] = 1
  88. forward_kernel[-3, :N] = 1
  89. target_control_points = paddle.cast(target_control_points,
  90. forward_kernel.dtype)
  91. forward_kernel[:N, -2:] = target_control_points
  92. forward_kernel[-2:, :N] = paddle.transpose(
  93. target_control_points, perm=[1, 0])
  94. # compute inverse matrix
  95. inverse_kernel = paddle.inverse(forward_kernel)
  96. # create target cordinate matrix
  97. HW = self.target_height * self.target_width
  98. target_coordinate = list(
  99. itertools.product(
  100. range(self.target_height), range(self.target_width)))
  101. target_coordinate = paddle.to_tensor(target_coordinate) # HW x 2
  102. Y, X = paddle.split(
  103. target_coordinate, target_coordinate.shape[1], axis=1)
  104. Y = Y / (self.target_height - 1)
  105. X = X / (self.target_width - 1)
  106. target_coordinate = paddle.concat(
  107. [X, Y], axis=1) # convert from (y, x) to (x, y)
  108. target_coordinate_partial_repr = compute_partial_repr(
  109. target_coordinate, target_control_points)
  110. target_coordinate_repr = paddle.concat(
  111. [
  112. target_coordinate_partial_repr, paddle.ones(shape=[HW, 1]),
  113. target_coordinate
  114. ],
  115. axis=1)
  116. # register precomputed matrices
  117. self.inverse_kernel = inverse_kernel
  118. self.padding_matrix = paddle.zeros(shape=[3, 2])
  119. self.target_coordinate_repr = target_coordinate_repr
  120. self.target_control_points = target_control_points
  121. def forward(self, input, source_control_points):
  122. assert source_control_points.ndimension() == 3
  123. assert source_control_points.shape[1] == self.num_control_points
  124. assert source_control_points.shape[2] == 2
  125. batch_size = paddle.shape(source_control_points)[0]
  126. padding_matrix = paddle.expand(
  127. self.padding_matrix, shape=[batch_size, 3, 2])
  128. Y = paddle.concat([source_control_points, padding_matrix], 1)
  129. mapping_matrix = paddle.matmul(self.inverse_kernel, Y)
  130. source_coordinate = paddle.matmul(self.target_coordinate_repr,
  131. mapping_matrix)
  132. grid = paddle.reshape(
  133. source_coordinate,
  134. shape=[-1, self.target_height, self.target_width, 2])
  135. grid = paddle.clip(grid, 0,
  136. 1) # the source_control_points may be out of [0, 1].
  137. # the input to grid_sample is normalized [-1, 1], but what we get is [0, 1]
  138. grid = 2.0 * grid - 1.0
  139. output_maps = grid_sample(input, grid, canvas=None)
  140. return output_maps, source_coordinate