I have an numpy array in python that represent an image its size is 28x28x3 while the max value of it is 0.2 and the min is -0.1. I want to scale that image between 0-255. How can I do so?
Asked
Active
Viewed 2.5k times
15
-
You may want to check the answers here: https://stackoverflow.com/questions/21030391/how-to-normalize-an-array-in-numpy – Leonardo Gonzalez Apr 19 '18 at 13:38
2 Answers
24
new_arr = ((arr + 0.1) * (1/0.3) * 255).astype('uint8')
This first scales the vector to the [0, 1] range, multiplies it by 255 and then converts it to uint8
, which is a common format for images (opencv uses it, for example)
In general you can use:
new_arr = ((arr - arr.min()) * (1/(arr.max() - arr.min()) * 255)).astype('uint8')

Milan Cermak
- 7,476
- 3
- 44
- 59

Fred
- 1,462
- 8
- 15
-
-
1`0.3` is the right number in that code. Check again the generalized version – Fred Apr 19 '18 at 13:40
-
It's probably a bit better (though ugly) to use s.th. like `255.999` to have equal bin sizes. – Paul Panzer Apr 19 '18 at 13:59
-
4
You can also use uint8 datatype while storing the image from numpy array.
import numpy as np
from PIL import Image
img = Image.fromarray(np.uint8(tmp))
tmp is my np array of size 255*255*3.

BHT
- 41
- 4