Center crop in PyTorch?

Hi, all

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


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]

you could also use F.pad with negative number for cropping, but you will have to figure out the amount of padding manually:


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?

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

this method is helpful