| 74 | |
| 75 | |
| 76 | def bilinear_sample(img, sample_coords, mode="bilinear", padding_mode="zeros", return_mask=False): |
| 77 | # img: [B, C, H, W] |
| 78 | # sample_coords: [B, 2, H, W] in image scale |
| 79 | if sample_coords.size(1) != 2: # [B, H, W, 2] |
| 80 | sample_coords = sample_coords.permute(0, 3, 1, 2) |
| 81 | |
| 82 | b, _, h, w = sample_coords.shape |
| 83 | |
| 84 | # Normalize to [-1, 1] |
| 85 | x_grid = 2 * sample_coords[:, 0] / (w - 1) - 1 |
| 86 | y_grid = 2 * sample_coords[:, 1] / (h - 1) - 1 |
| 87 | |
| 88 | grid = torch.stack([x_grid, y_grid], dim=-1) # [B, H, W, 2] |
| 89 | |
| 90 | img = F.grid_sample(img, grid, mode=mode, padding_mode=padding_mode, align_corners=True) |
| 91 | |
| 92 | if return_mask: |
| 93 | mask = (x_grid >= -1) & (y_grid >= -1) & (x_grid <= 1) & (y_grid <= 1) # [B, H, W] |
| 94 | |
| 95 | return img, mask |
| 96 | |
| 97 | return img |
| 98 | |
| 99 | |
| 100 | class Dilate: |