def random_apply_affine(img, p, G=None, antialiasing_kernel=SYM6): kernel = antialiasing_kernel len_k = len(kernel) pad_k = (len_k + 1) // 2 kernel = torch.as_tensor(kernel) kernel = torch.ger(kernel, kernel).to(img) kernel_flip = torch.flip(kernel, (0, 1)) img_pad, G, (pad_x1, pad_x2, pad_y1, pad_y2) = try_sample_affine_and_pad(img, p, pad_k, G) p_ux1 = pad_x1 p_ux2 = pad_x2 + 1 p_uy1 = pad_y1 p_uy2 = pad_y2 + 1 w_p = img_pad.shape[3] - len_k + 1 h_p = img_pad.shape[2] - len_k + 1 h_o = img.shape[2] w_o = img.shape[3] img_2x = upfirdn2d(img_pad, kernel_flip, up=2) grid = make_grid( img_2x.shape, -2 * p_ux1 / w_o - 1, 2 * (w_p - p_ux1) / w_o - 1, -2 * p_uy1 / h_o - 1, 2 * (h_p - p_uy1) / h_o - 1, device=img_2x.device, ).to(img_2x) grid = affine_grid(grid, torch.inverse(G)[:, :2, :].to(img_2x)) grid = grid * torch.tensor([w_o / w_p, h_o / h_p], device=grid.device) + torch.tensor( [(w_o + 2 * p_ux1) / w_p - 1, (h_o + 2 * p_uy1) / h_p - 1], device=grid.device) img_affine = F.grid_sample(img_2x, grid, mode="bilinear", align_corners=False, padding_mode="zeros") img_down = upfirdn2d(img_affine, kernel, down=2) end_y = -pad_y2 - 1 if end_y == 0: end_y = img_down.shape[2] end_x = -pad_x2 - 1 if end_x == 0: end_x = img_down.shape[3] img = img_down[:, :, pad_y1:end_y, pad_x1:end_x] return img, G
def forward(self, input): out = upfirdn2d(input, self.kernel, up=1, down=self.factor, pad=self.pad) return out
def forward(self, input): out = upfirdn2d(input, self.kernel, pad=self.pad) return out