How to change an image which has dimensions (512, 512, 3) to a tensor of size ([1, 3, 224, 224])

Viewed 768

I was trying to implement a paper where the input dimensions are meant to be a tensor of size ([1, 3, 224, 224]). My current image size is (512, 512, 3).

How do I resize and convert in order to input to the model?

1 Answers

Assuming image already converted to torch.Tensor and has shape (512, 512, 3), one of possible ways:

from torchvision.transforms import Resize

image = image.permute((2, 0, 1))  # convert to (C, H, W) format

image = image.unsqueeze(0)  # add fake batch dimension

resize = Resize((224, 224))

new_image = resize(image)

Now new_image.shape equals to (1, 3, 224, 224)

Related