Skip to content

Denormalize option in torchvision.utils.save_image() #848

Open
@SamSweere

Description

@SamSweere

🚀 Feature

A function to denormalize an image based on mean and standard deviation.

Motivation

When working with images on NN's trained on a specific dataset (for example ImageNet), an image is first normalized to the mean and standard deviation of that dataset. When we want to save such an image later in the process we can use the function torchvision.utils.save_image(). However the image is still normalized and will have a different mean and standard deviation compared to the original image. There is no option to denormalize such an image such that the initial normalization is undone and the saved image has the same mean and std.

Pitch

A extra parameter to the torchvision.utils.save_image() function to denormalize an image based on a mean and standardization array.

Alternatives

One way to tackle the problem currently is to use the transforms.Normalize() function. My current implementation is shown below. One flaw of this implementation is that the image has to be clipped to keep the values between 0 and 1. Thus some information is lost. I am not sure how to do this operation lossless.

def img_denorm(img, mean, std):
    #for ImageNet the mean and std are:
    #mean = np.asarray([ 0.485, 0.456, 0.406 ])
    #std = np.asarray([ 0.229, 0.224, 0.225 ])

    denormalize = transforms.Normalize((-1 * mean / std), (1.0 / std))

    res = img.squeeze(0)
    res = denormalize(res)

    #Image needs to be clipped since the denormalize function will map some
    #values below 0 and above 1
    res = torch.clamp(res, 0, 1)
    
return(res)

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