Center crop in PyTorch?

Hi, all

I want to crop the image after using nn.ConvTranspose2d, but I can not find some relative function…

3 Likes

seems that there aren’t such methods, try something like this:

def crop(variable,tw,th):
        w, h = variable.size
        x1 = int(round((w - tw) / 2.))
        y1 = int(round((h - th) / 2.))
        return variable[x1:x1+tw,y1:y1+th]
2 Likes

you could also use F.pad with negative number for cropping, but you will have to figure out the amount of padding manually: http://pytorch.org/docs/nn.html#torch.nn.functional.pad

Hi,

Has center cropping (and/or negative padding) been added to torch.nn API in the recent versions?

I am having a similar use case as the OP and would prefer to use the nn API rather F.pad.

I found some old threads (here and here) about adding these features but couldn’t find anything readily in the docs. Any pointers would be helpful.

Thank you!

@smth Any heads up on this?
TIA.

Maybe (transforms.CenterCrop) func should suffice for your usecase.

center_crop
this method is helpful