Skip to content

[Feature proposal] Apply adjust_contrast transformation for grayscale tensors #3670

Open
@ukky17

Description

@ukky17

Motivation

Currently, adjust_contrast function in torchvision.transformations.functional_tensor only works for 3-channel (=RGB) tensors. However, I would like to change the contrast of a 1-channel (= grayscale) tensor.

Pitch

Just like the 3-channel case, the desired function changes the image contrast. I.e., contrast_factor = 0 gives a uniform gray image, 1 gives the original image while 2 increases the contrast by a factor of 2.

Additional context

This feature can be implemented by slightly modifying the adjust_contrast function in torchvision.transformations.functional_tensor like this;

def adjust_contrast(img: Tensor, contrast_factor: float) -> Tensor:
    if contrast_factor < 0:
        raise ValueError('contrast_factor ({}) is not non-negative.'.format(contrast_factor))

    _assert_image_tensor(img)

    _assert_channels(img, [1, 3])

    dtype = img.dtype if torch.is_floating_point(img) else torch.float32

    num_channels = _get_image_num_channels(img)
    if num_channels == 1:
        gray_img = img.to(dtype)
    elif num_channels == 3:
        gray_img = rgb_to_grayscale(img).to(dtype)

    mean = torch.mean(gray_img, dim=(-3, -2, -1), keepdim=True)

    return _blend(img, mean, contrast_factor)

cc @vfdev-5

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions