Adjust contrast in the transformation pipeline

Hi I’m trying to modify contrast in the transformation pipeline for data augmentation but I have this error

TypeError: adjust_contrast() missing 1 required positional argument: 'img’

This is my code

transform = transforms.Compose([
    transforms.Grayscale(num_output_channels=1),
    transforms.RandomRotation(degrees= (-15, 15)),
    transforms.ToTensor(),
    transforms.functional.adjust_contrast( contrast_factor= 0.5)
    ])

The issue is that the functional version of contrast expects to take in the input directly rather than returning a callable function. You can work around this by using ColorJitter and only changing the contrast (e.g., torchvision.transforms.ColorJitter(brightness=0, contrast=0.5, saturation=0, hue=0)).

If you want a constant adjustment you can just wrap the current function:

def my_adjust_contrast():
    def _func(img):
        return  transforms.functional.adjust_contrast(img, contrast_factor= 0.5)
    return _func
transform = transforms.Compose([
    transforms.Grayscale(num_output_channels=1),
    transforms.RandomRotation(degrees= (-15, 15)),
    transforms.ToTensor(),
    my_adjust_contrast()
    ])
1 Like