0

I have a float array like this [0.1,0.4,1.5,2.22,3] where max value is always 3.0

I want to Quantize that to a byte array from 0 to 255 for each value I want to Quantize it like (byte)((value / 3.0) * 255.0)

Is there a way to do that in numpy very fast rather than iterating every value in Python and rebuilding a new byte array?

Rob The Quant
  • 347
  • 3
  • 15
  • You don't want to use 255.0, you want to use 255.9999. Otherwise your count of 255 will be severely underrepresented. – Mark Ransom Jan 24 '22 at 05:40

1 Answers1

2

Use astype

import numpy as np

value = np.array([0.1, 0.4, 1.5, 2.22, 3])
out = ((value / 3.0) * 255.0).astype(np.ubyte)
print(out)

# Output
array([  8,  34, 127, 188, 255], dtype=uint8)
Corralien
  • 109,409
  • 8
  • 28
  • 52