Scale a numpy array with from -0.1 - 0.2 to 0-255

17,218

Solution 1

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')

Solution 2

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.

Share:
17,218
Jose Ramon
Author by

Jose Ramon

Updated on June 30, 2022

Comments

  • Jose Ramon
    Jose Ramon almost 2 years

    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?

  • Jose Ramon
    Jose Ramon about 6 years
    Yes indeed the max is 0.2 and not 0.3. Thanks I will check it out.
  • Fred
    Fred about 6 years
    0.3 is the right number in that code. Check again the generalized version
  • Paul Panzer
    Paul Panzer about 6 years
    It's probably a bit better (though ugly) to use s.th. like 255.999 to have equal bin sizes.
  • Fred
    Fred about 6 years
    Probably better to just use np.round