1

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.

user1767754
  • 23,311
  • 18
  • 141
  • 164

1 Answers1

2

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!

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
  • This code is also wrong! Funny how difficult seems to be just having a division. Aside from `np` not being defined, you will have casting issues because NumPy will think `x` is an array of `int` and then you should not use the `/=` operator but split to `x = x / 255`, which will force automatic type coercion correctly. – norok2 Sep 28 '17 at 18:18
  • @norok2 sorry! I always run code on my computer then type out the code on SO, I had the lines `import numpy as np` and `np.array([...], dtype="uint8")` which I think will fix both the problems you have picked up. Let me know if you spot anything else wrong as I am new to `numpy` as well. Thank You – Joe Iddon Sep 28 '17 at 18:22
  • explicit call of the `dtype` will not fix the casting issue, what will is replacing `x /= 255` with `x = x / 255` – norok2 Sep 28 '17 at 18:24
  • @norok2 I will update the answer. But would appreciate if you could explain further what you mean by a 'casting issue' – Joe Iddon Sep 28 '17 at 18:25
  • after creation `x` is an array of `int` and if you use the `/=` operator, it will try to calculate the operation in-place. However, the result of `/` cannot be safely casted to `int` (in this case you would get `0` everywhere except where `x == 255` if NumPy wouldn't throw a `TypeError` meanwhile), so what you want to do is to compute `x / 255` separately (which will not happen in-place) and then bind the result again to `x` (which will render the previous array unaccessible). – norok2 Sep 28 '17 at 18:26