user1767754
user1767754

Reputation: 25144

Numpy fit values between a range

I have an array in numpy of values within the range: [0, 255] (ubyte) and want to remap it to a new range [0.0, 1.0](float)

x = [0, 127, 255]

should become

x = [0.0, 0.5, 1.0]

That post Convert a number range to another range, maintaining ratio is very general way how to remap a range, but doesn't explain how to conveniently do it in numpy.

Upvotes: 1

Views: 2422

Answers (1)

Joe Iddon
Joe Iddon

Reputation: 20434

Just use the division '/' operand on the array:

This applies the operation element-wise, so you can 'divide' the array by 255 which will map the values for you, like so:

import numpy as np
x = np.array([0,127,255], dtype="uint8")
x = x / 255

which gives:

array([0, 0.49803922, 1])

it doesn't give your result of [0,0.5,1] because 127 is not half of 255!

Upvotes: 2

Related Questions