How to normalize image data from -1 to 1

Hi I have image with values from 0 to 255. What is best way to normalize this image to -1,1 ?

Thank you

This should work:

x = torch.randint(0, 256, (100,)).float()
print(x.min(), x.max())
# > tensor(0.) tensor(255.)
y = 2 * x / 255. - 1
print(y.min(), y.max())
# > tensor(-1.) tensor(1.)
1 Like

Hi one more question, how can I get this normalization back now ? If I have image normalized between -1 an 1 and now I want back to 0 -255, iam trying to revert this equation but not working

You can just undo the normalization:

x = torch.randint(0, 256, (100,)).float()
print(x.min(), x.max())
# > tensor(0.) tensor(255.)
y = 2 * x / 255. - 1
print(y.min(), y.max())
# > tensor(-1.) tensor(1.)

# undo normalization
z = (y + 1) / 2 * 255.
print(z.min(), z.max())
# > tensor(0.) tensor(255.)
2 Likes