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,
David.
"""
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 = Image.open('../../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.RandomHorizontalFlip(p=0.5),
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].imshow(pil_image)
axs[0].set_title('Original Image')
axs[1].imshow(pil_normalized_image)
axs[1].set_title('Normalized Image')
for ax in axs:
ax.axis('off')
plt.show()