Quantize Float Array to Byte Array in Python

633 views Asked by At

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?

1

There are 1 answers

1
Corralien On BEST ANSWER

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)