Complete the code to define a custom transform class that converts an image to grayscale.
import torchvision.transforms as transforms class ToGrayScale: def __call__(self, img): return img.[1]('L')
The convert method is used to change the image mode, and 'L' mode means single channel grayscale.
Complete the code to apply the custom transform to an image.
from PIL import Image img = Image.open('sample.jpg') transform = ToGrayScale() gray_img = transform.[1](img)
The __call__ method allows the instance to be called like a function. Using transform(img) calls __call__ internally.
Fix the error in the custom transform that should normalize a tensor image.
import torch class NormalizeTensor: def __init__(self, mean, std): self.mean = mean self.std = std def __call__(self, tensor): return (tensor - self.mean) / [1]
Normalization subtracts the mean and divides by the standard deviation stored in self.std.
Fill both blanks to complete a custom transform that randomly flips an image horizontally with 50% chance.
import random from PIL import Image class RandomHorizontalFlip: def __call__(self, img): if random.random() [1] 0.5: return img.[2](Image.FLIP_LEFT_RIGHT) return img
The condition checks if a random number is greater than 0.5 to flip. The transpose() method with Image.FLIP_LEFT_RIGHT flips the image horizontally.
Fill all three blanks to create a custom transform that converts an image to tensor and normalizes it.
import torchvision.transforms.functional as F class ToTensorNormalize: def __init__(self, mean, std): self.mean = mean self.std = std def __call__(self, img): tensor = F.[1](img) tensor = F.[2](tensor, self.mean, [3]) return tensor
to_tensor converts the image to a tensor. normalize applies normalization using mean and standard deviation. The standard deviation is passed as self.std.