Home > front end >  How to I reshape the 2D array like this? (By using tensor)
How to I reshape the 2D array like this? (By using tensor)

Time:07-14

I want to reshape like reshaping an image. Like 32 * 32 to 16 * 16. (By using torch.tensor) Like decreasing the resolution? Can anyone help me?

CodePudding user response:

If you have an image (stored in a tensor) and you want to decrease it's resolution, then you are not reshaping it, but rather resizing it.
To that end, you can use pytorch's interpolate:

import torch
from torch.nn import functional as nnf

y = nnf.interpolate(x[None, None, ...], size=(16, 16), mode='bicubic', align_corners=False, antialias=True)

Notes:

  1. nnf.interpolate operates on batches of multi-channel images, that is, it expects its input x to have 4 dimensions: batch-channels-height-width. So, if your x is a single image with a single channel (e.g., an MNIST digit) you'll have to create a singleton batch dimension and a singleton channel dimension.
  2. Pay close attention to align_corners and antialias -- make sure you are using the right configuration for your needs.

For more information regarding aliasing and alignment when resizing images you can look at ResizeRight.

CodePudding user response:

you can use resize from torchvision transforms:

import torchvision.transform as T
T.Resize(16)(your_image)

you can also chain it to other transforms

preprocess = T.Compose([
   T.Resize(N),
   T.CenterCrop(N),
   T.ToTensor(),
   T.Normalize(
       mean=mean,
       std=std
   )
])
preprocess(your_image)
  • Related