transforms.v2.Normalize method

Hi all,

I’m trying to reproduce the example listed here with no success Getting started with transforms v2

The problem is the way the transformed image appears. If I remove the transforms.Normalize line of the transforms.Compose (see code) then the transformed output looks good, but it does not when using it. I attached an image so you can see what I mean (left image no transform, right image using Normalize). Or is the shown image at the right the way it is supposed a normalized image should appear? In the example of the above link, it does look different.

Looking forward to hearing from you,

Normalization test using torchvision
import torchvision.transforms.v2 as transforms
import torch
from PIL import Image
import matplotlib.pyplot as plt

# Load the image
image ='../../gallery/assets/astronaut.jpg')

# Convert the image to a tensor
to_tensor = transforms.ToImage()
tensor_image = to_tensor(image)

normalize = transforms.Compose([
    transforms.RandomResizedCrop(size=(224, 224), antialias=True),
    transforms.ToDtype(torch.float32, scale=True),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),

normalized_image = normalize(tensor_image)

# Convert the tensors back to PIL Images for display
tensor_to_pil = transforms.ToPILImage()
pil_image = tensor_to_pil(tensor_image)
pil_normalized_image = tensor_to_pil(normalized_image)

# Display the images
fig, axs = plt.subplots(1, 2, figsize=(15, 5))

axs[0].set_title('Original Image')

axs[1].set_title('Normalized Image')

for ax in axs:

This is expected since matplotlib will use the default colormap to visualize the normalized floating point numbers. “Unnormalizing” the image should show the original again.

1 Like

Thank you very much. I just found another answer from you on the same subject in a previous post :sweat_smile: Understanding transform normalize

Great! I was sure I’ve answered it before but couldn’t find the post quickly :slight_smile:

1 Like

I am also facing a problem that is related to normalizing the data. If I don’t normalize the data before feeding it to the model, the output has the same color quality as the original one. However, with normalization, the output image is darker (after de-normalizing). I am attaching the images below.

val_epoch_5_30_gt val_epoch_5_30_second_out

(the first one is the GT, and the second is the output image)

Without normalization the model performs poorly compared to the normalized one.