Skip to content

add nn.CenterCrop1d and nn.CenterCrop2d #1331

@bodokaiser

Description

@bodokaiser

There are some models which use "crop layers" (e.g. U-Net, ParseNet) so I think it wouldn't be bad to have a CenterCropNd layer.

As F.pad supports negative padding we just need to calculate padding offsets on top.

import torch

from torch.nn import functional as F
from torch.autograd import Variable

def center_crop(x, height, width):
    crop_h = torch.FloatTensor([x.size()[2]]).sub(height).div(-2)
    crop_w = torch.FloatTensor([x.size()[3]]).sub(width).div(-2)

    return F.pad(x, [
        crop_w.ceil().int()[0], crop_w.floor().int()[0],
        crop_h.ceil().int()[0], crop_h.floor().int()[0],
    ])

variable = Variable(torch.randn(1, 3, 60, 40))

print(center_crop(variable, 20, 20).size())
print(center_crop(variable, 20, 40).size())

I can send a PR on interest.

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureA request for a proper, new feature.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions