pytorch / pytorch/vision

[Feature proposal] Apply `adjust_contrast` transformation for grayscale tensors

Open
#3,670 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement module: transforms
Dominant language
Python
Stars
17.9k
Forks
7.3k
Avg merge
1d 15h
Merged PRs (30d)
13

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in torchvision.transformations.functional_tensor.adjust_contrast and read the current channel handling. Done means grayscale tensors are accepted while preserving RGB behavior, with contrast factors 0, 1, and 2 producing the uniform gray, unchanged, and enhanced results described in the issue.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, pytorch
Domain
computer-vision
Issue type
Feature
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.