Reputation: 625
So I have been trying to find a way to normalize some PIL image pixel values between -1 and 1. I searched through documentation and didn't find solution. Only normalization in documentation is transforms.Normalize
which normalizes with mean and std. So I am stuck on how to do it. This is my code:
train_transform = transforms.Compose([
transforms.RandomHorizontalFlip(p=0.5),
transforms.Resize(40),
transforms.RandomCrop(32),
# Normalize(-1, 1) # Something like that
])
How can I normalize tensor between 2 numbers? For example:
[[1,2,3]
[3,2,1]]
Between -1 and 1
[[-1, 0, 1],
[1, 0, -1]]
Upvotes: 2
Views: 8057
Reputation: 8527
Try:
transform = transforms.Compose([
transforms.RandomHorizontalFlip(p=0.5)
transforms.Resize(40),
transforms.RandomCrop(32),
transforms.ToTensor(),
transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))])
ToTensor will scale image pixels from [0,255] to [0,1] values
Normalize will first subtract the mean so [0,1] values will transform to range [-0.5,0.5], and then will divide with std and [-0.5,0.5] will reach [-1,1] range
Upvotes: 10