Tajinder Singh
Tajinder Singh

Reputation: 1531

Pytorch crop images from Top Left Corner in Transforms

I'm using Pytorch's transforms.Compose and in my dataset I have 1200x1600 (Height x Width) images.

I want to crop the images starting from the Top Left Corner (0,0) so that I can have 800x800 images.

I was looking in Pytorch documentation but I didn't find anything to solve my problem, so I copied the source code of center_crop in my project and modified it as follows:

def center_crop(img: Tensor, output_size: List[int]):
    # .... Other stuff of Pytorch

    # ....
    # Original Pytorch Code (that I commented)
    crop_top = int((image_height - crop_height + 1) * 0.5)
    crop_left = int((image_width - crop_width + 1) * 0.5)
    
    # ----
    # My modifications:
    crop_top = crop_left = 0

    return crop(img, crop_top, crop_left, crop_height, crop_width)

But basically I think this is quite an overkill, if it's possible I'd like to avoid to copy their code and modify it. Isn't there anything that already implements the desired behaviour by default, is there?

Upvotes: 0

Views: 4939

Answers (1)

Tajinder Singh
Tajinder Singh

Reputation: 1531

I used Lambda transforms in order to define a custom crop

from torchvision.transforms.functional import crop

def crop800(image):
    return crop(image, 0, 0, 800, 800)

data_transforms = {
    'images': transforms.Compose([transforms.ToTensor(),
                                  transforms.Lambda(crop800),
                                  transforms.Resize((400, 400))])}

Upvotes: 2

Related Questions