tps.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. import numpy as np
  2. import torch
  3. from torch import nn
  4. from torch.nn import functional as F
  5. from openrec.modeling.common import Activation
  6. class ConvBNLayer(nn.Module):
  7. def __init__(self,
  8. in_channels,
  9. out_channels,
  10. kernel_size,
  11. stride=1,
  12. groups=1,
  13. act=None):
  14. super(ConvBNLayer, self).__init__()
  15. self.conv = nn.Conv2d(
  16. in_channels=in_channels,
  17. out_channels=out_channels,
  18. kernel_size=kernel_size,
  19. stride=stride,
  20. padding=(kernel_size - 1) // 2,
  21. groups=groups,
  22. bias=False,
  23. )
  24. self.bn = nn.BatchNorm2d(out_channels)
  25. self.act = Activation(act) if act else None
  26. def forward(self, x):
  27. x = self.conv(x)
  28. x = self.bn(x)
  29. if self.act is not None:
  30. x = self.act(x)
  31. return x
  32. class LocalizationNetwork(nn.Module):
  33. def __init__(self, in_channels, num_fiducial, loc_lr, model_name):
  34. super(LocalizationNetwork, self).__init__()
  35. self.F = num_fiducial
  36. F = num_fiducial
  37. if model_name == 'large':
  38. num_filters_list = [64, 128, 256, 512]
  39. fc_dim = 256
  40. else:
  41. num_filters_list = [16, 32, 64, 128]
  42. fc_dim = 64
  43. self.block_list = nn.ModuleList()
  44. for fno in range(0, len(num_filters_list)):
  45. num_filters = num_filters_list[fno]
  46. conv = ConvBNLayer(
  47. in_channels=in_channels,
  48. out_channels=num_filters,
  49. kernel_size=3,
  50. act='relu',
  51. )
  52. self.block_list.append(conv)
  53. if fno == len(num_filters_list) - 1:
  54. pool = nn.AdaptiveAvgPool2d(1)
  55. else:
  56. pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
  57. in_channels = num_filters
  58. self.block_list.append(pool)
  59. self.fc1 = nn.Linear(in_channels, fc_dim)
  60. # Init fc2 in LocalizationNetwork
  61. self.fc2 = nn.Linear(fc_dim, F * 2)
  62. initial_bias = self.get_initial_fiducials()
  63. initial_bias = initial_bias.reshape(-1)
  64. self.fc2.bias.data = torch.tensor(initial_bias, dtype=torch.float32)
  65. nn.init.zeros_(self.fc2.weight.data)
  66. self.out_channels = F * 2
  67. def forward(self, x):
  68. """
  69. Estimating parameters of geometric transformation
  70. Args:
  71. image: input
  72. Return:
  73. batch_C_prime: the matrix of the geometric transformation
  74. """
  75. for block in self.block_list:
  76. x = block(x)
  77. x = x.squeeze(dim=2).squeeze(dim=2)
  78. x = self.fc1(x)
  79. x = F.relu(x)
  80. x = self.fc2(x)
  81. x = x.reshape(shape=[-1, self.F, 2])
  82. return x
  83. def get_initial_fiducials(self):
  84. """see RARE paper Fig.
  85. 6 (a)
  86. """
  87. F = self.F
  88. ctrl_pts_x = np.linspace(-1.0, 1.0, int(F / 2))
  89. ctrl_pts_y_top = np.linspace(0.0, -1.0, num=int(F / 2))
  90. ctrl_pts_y_bottom = np.linspace(1.0, 0.0, num=int(F / 2))
  91. ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1)
  92. ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1)
  93. initial_bias = np.concatenate([ctrl_pts_top, ctrl_pts_bottom], axis=0)
  94. return initial_bias
  95. class GridGenerator(nn.Module):
  96. def __init__(self, in_channels, num_fiducial):
  97. super(GridGenerator, self).__init__()
  98. self.eps = 1e-6
  99. self.F = num_fiducial
  100. self.fc = nn.Linear(in_channels, 6)
  101. nn.init.constant_(self.fc.weight, 0)
  102. nn.init.constant_(self.fc.bias, 0)
  103. self.fc.weight.requires_grad = False
  104. self.fc.bias.requires_grad = False
  105. def forward(self, batch_C_prime, I_r_size):
  106. """Generate the grid for the grid_sampler.
  107. Args:
  108. batch_C_prime: the matrix of the geometric transformation
  109. I_r_size: the shape of the input image
  110. Return:
  111. batch_P_prime: the grid for the grid_sampler
  112. """
  113. C = self.build_C_paddle()
  114. P = self.build_P_paddle(I_r_size)
  115. inv_delta_C_tensor = self.build_inv_delta_C_paddle(C).float()
  116. P_hat_tensor = self.build_P_hat_paddle(C, torch.tensor(P)).float()
  117. batch_C_ex_part_tensor = self.get_expand_tensor(batch_C_prime)
  118. batch_C_prime_with_zeros = torch.cat(
  119. [batch_C_prime, batch_C_ex_part_tensor], dim=1)
  120. batch_T = torch.matmul(
  121. inv_delta_C_tensor.to(batch_C_prime_with_zeros.device),
  122. batch_C_prime_with_zeros,
  123. )
  124. batch_P_prime = torch.matmul(P_hat_tensor.to(batch_T.device), batch_T)
  125. return batch_P_prime
  126. def build_C_paddle(self):
  127. """Return coordinates of fiducial points in I_r; C."""
  128. F = self.F
  129. ctrl_pts_x = torch.linspace(-1.0, 1.0, int(F / 2), dtype=torch.float64)
  130. ctrl_pts_y_top = -1 * torch.ones([int(F / 2)], dtype=torch.float64)
  131. ctrl_pts_y_bottom = torch.ones([int(F / 2)], dtype=torch.float64)
  132. ctrl_pts_top = torch.stack([ctrl_pts_x, ctrl_pts_y_top], dim=1)
  133. ctrl_pts_bottom = torch.stack([ctrl_pts_x, ctrl_pts_y_bottom], dim=1)
  134. C = torch.cat([ctrl_pts_top, ctrl_pts_bottom], dim=0)
  135. return C # F x 2
  136. def build_P_paddle(self, I_r_size):
  137. I_r_height, I_r_width = I_r_size
  138. I_r_grid_x = (torch.arange(-I_r_width, I_r_width, 2) +
  139. 1.0) / torch.tensor(np.array([I_r_width]))
  140. I_r_grid_y = (torch.arange(-I_r_height, I_r_height, 2) +
  141. 1.0) / torch.tensor(np.array([I_r_height]))
  142. # P: self.I_r_width x self.I_r_height x 2
  143. P = torch.stack(torch.meshgrid(I_r_grid_x, I_r_grid_y), dim=2)
  144. P = torch.permute(P, [1, 0, 2])
  145. # n (= self.I_r_width x self.I_r_height) x 2
  146. return P.reshape([-1, 2])
  147. def build_inv_delta_C_paddle(self, C):
  148. """Return inv_delta_C which is needed to calculate T."""
  149. F = self.F
  150. hat_eye = torch.eye(F) # F x F
  151. hat_C = torch.norm(C.reshape([1, F, 2]) - C.reshape([F, 1, 2]),
  152. dim=2) + hat_eye
  153. hat_C = (hat_C**2) * torch.log(hat_C)
  154. delta_C = torch.cat( # F+3 x F+3
  155. [
  156. torch.cat([torch.ones((F, 1)), C, hat_C], dim=1), # F x F+3
  157. torch.concat([torch.zeros(
  158. (2, 3)), C.transpose(0, 1)], dim=1), # 2 x F+3
  159. torch.concat([torch.zeros(
  160. (1, 3)), torch.ones((1, F))], dim=1), # 1 x F+3
  161. ],
  162. axis=0,
  163. )
  164. inv_delta_C = torch.inverse(delta_C)
  165. return inv_delta_C # F+3 x F+3
  166. def build_P_hat_paddle(self, C, P):
  167. F = self.F
  168. eps = self.eps
  169. n = P.shape[0] # n (= self.I_r_width x self.I_r_height)
  170. # P_tile: n x 2 -> n x 1 x 2 -> n x F x 2
  171. P_tile = torch.tile(torch.unsqueeze(P, dim=1), (1, F, 1))
  172. C_tile = torch.unsqueeze(C, dim=0) # 1 x F x 2
  173. P_diff = P_tile - C_tile # n x F x 2
  174. # rbf_norm: n x F
  175. rbf_norm = torch.norm(P_diff, p=2, dim=2, keepdim=False)
  176. # rbf: n x F
  177. rbf = torch.multiply(torch.square(rbf_norm), torch.log(rbf_norm + eps))
  178. P_hat = torch.cat([torch.ones((n, 1)), P, rbf], dim=1)
  179. return P_hat # n x F+3
  180. def get_expand_tensor(self, batch_C_prime):
  181. B, H, C = batch_C_prime.shape
  182. batch_C_prime = batch_C_prime.reshape([B, H * C])
  183. batch_C_ex_part_tensor = self.fc(batch_C_prime)
  184. batch_C_ex_part_tensor = batch_C_ex_part_tensor.reshape([-1, 3, 2])
  185. return batch_C_ex_part_tensor
  186. class TPS(nn.Module):
  187. def __init__(self, in_channels, num_fiducial, loc_lr, model_name):
  188. super(TPS, self).__init__()
  189. self.loc_net = LocalizationNetwork(in_channels, num_fiducial, loc_lr,
  190. model_name)
  191. self.grid_generator = GridGenerator(self.loc_net.out_channels,
  192. num_fiducial)
  193. self.out_channels = in_channels
  194. def forward(self, image):
  195. image.stop_gradient = False
  196. batch_C_prime = self.loc_net(image)
  197. batch_P_prime = self.grid_generator(batch_C_prime, image.shape[2:])
  198. batch_P_prime = batch_P_prime.reshape(
  199. [-1, image.shape[2], image.shape[3], 2])
  200. is_fp16 = False
  201. if batch_P_prime.dtype != torch.float32:
  202. data_type = batch_P_prime.dtype
  203. image = image.float()
  204. batch_P_prime = batch_P_prime.float()
  205. is_fp16 = True
  206. batch_I_r = F.grid_sample(image, grid=batch_P_prime)
  207. if is_fp16:
  208. batch_I_r = batch_I_r.astype(data_type)
  209. return batch_I_r