| 275 | |
| 276 | # Image handling classes. |
| 277 | class PatchMaker: |
| 278 | def __init__(self, patchsize, stride=None): |
| 279 | self.patchsize = patchsize |
| 280 | self.stride = stride |
| 281 | |
| 282 | def patchify(self, features, return_spatial_info=False): |
| 283 | """Convert a tensor into a tensor of respective patches. |
| 284 | Args: |
| 285 | x: [torch.Tensor, bs x c x w x h] |
| 286 | Returns: |
| 287 | x: [torch.Tensor, bs * w//stride * h//stride, c, patchsize, |
| 288 | patchsize] |
| 289 | """ |
| 290 | padding = int((self.patchsize - 1) / 2) |
| 291 | unfolder = torch.nn.Unfold( |
| 292 | kernel_size=self.patchsize, stride=self.stride, padding=padding, dilation=1 |
| 293 | ) |
| 294 | unfolded_features = unfolder(features) |
| 295 | number_of_total_patches = [] |
| 296 | for s in features.shape[-2:]: |
| 297 | n_patches = ( |
| 298 | s + 2 * padding - 1 * (self.patchsize - 1) - 1 |
| 299 | ) / self.stride + 1 |
| 300 | number_of_total_patches.append(int(n_patches)) |
| 301 | unfolded_features = unfolded_features.reshape( |
| 302 | *features.shape[:2], self.patchsize, self.patchsize, -1 |
| 303 | ) |
| 304 | unfolded_features = unfolded_features.permute(0, 4, 1, 2, 3) |
| 305 | |
| 306 | if return_spatial_info: |
| 307 | return unfolded_features, number_of_total_patches |
| 308 | return unfolded_features |
| 309 | |
| 310 | def unpatch_scores(self, x, batchsize): |
| 311 | return x.reshape(batchsize, -1, *x.shape[1:]) |
| 312 | |
| 313 | def score(self, x): |
| 314 | was_numpy = False |
| 315 | if isinstance(x, np.ndarray): |
| 316 | was_numpy = True |
| 317 | x = torch.from_numpy(x) |
| 318 | while x.ndim > 1: |
| 319 | x = torch.max(x, dim=-1).values |
| 320 | if was_numpy: |
| 321 | return x.numpy() |
| 322 | return x |