MCPcopy Index your code
hub / github.com/amazon-science/patchcore-inspection / patchify

Method patchify

src/patchcore/patchcore.py:282–308  ·  view source on GitHub ↗

Convert a tensor into a tensor of respective patches. Args: x: [torch.Tensor, bs x c x w x h] Returns: x: [torch.Tensor, bs * w//stride * h//stride, c, patchsize, patchsize]

(self, features, return_spatial_info=False)

Source from the content-addressed store, hash-verified

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:])

Callers 1

_embedMethod · 0.80

Calls

no outgoing calls

Tested by

no test coverage detected