Torchvision.transforms set fillcolor for centercrop

Hi Torch Community,

This is my first post! :slight_smile:

How do I set the fillcolor for a CenterCrop to something other than (0,0,0)?

The example below shows using an affine transform and setting the fillcolor to be a custom color. However, I cannot set for CenterCrop to be anything other than PIL (0,0,0). Random crop has this ability with fill.

    white = (255, 255, 255)
    data_transforms = transforms.Compose([
        transforms.ToPILImage(),
        #transforms.RandomCrop((75, 75), fill=white),
        transforms.CenterCrop(300),
        transforms.RandomAffine((-30, 30), translate=(0.05, 0.05), fillcolor=white),
        transforms.ToTensor()
    ])

Hi,

yes if you are right, you cant add the padding. I donโ€™t know why you want to pad and not resize in this case but here is something that should work:

import torchvision.transforms.functional as F

class PadCenterCrop(object):
    def __init__(self, size, pad_if_needed=False, fill=0, padding_mode='constant'):
        if isinstance(size, (int, float)):
            self.size = (int(size), int(size))
        else:
            self.size = size
        self.pad_if_needed = pad_if_needed
        self.padding_mode = padding_mode
        self.fill = fill

    def __call__(self, img):

        # pad the width if needed
        if self.pad_if_needed and img.size[0] < self.size[1]:
            img = F.pad(img, (self.size[1] - img.size[0], 0), self.fill, self.padding_mode)
        # pad the height if needed
        if self.pad_if_needed and img.size[1] < self.size[0]:
            img = F.pad(img, (0, self.size[0] - img.size[1]), self.fill, self.padding_mode)

        return F.center_crop(img, self.size)
1 Like

Code works brilliantly! I confirm I was able to handle different PIL values! Thank you for the help.