How to crop the extra row or column of tensor?

I want to know how to crop the tensor in Pytorch. There is a tensor with size of (16, 3,46, 46), what I want to do is to crop the tensor’s size from (16, 3, 46, 46) to (16, 3, 45, 45).
The code is following:

image = torch.randn(16, 3, 45, 45)
b, c, h, w = image.size()
image_pad = torch.nn.functional.pad(image, [0,  w%2, 0,  h%2])  

How can I crop the image_pad (16, 3, 46, 46) to recover the original image (16, 3, 45, 45)?
I used the function tensor.resize_() to do it, it did recover the size of the original image, but I found that it didn’t recover the value of the original image.
I just want to crop the extra row or column of image_pad to recover the original image.

image_pad[:,:,:h,:w] ???

Thanks for your answer! It is really useful.

1 Like