15

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
  • 5,572
  • 25
  • 76
  • 152

2 Answers2

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