Rob The Quant
Rob The Quant

Reputation: 397

Quantize Float Array to Byte Array in Python

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?

Upvotes: 0

Views: 881

Answers (1)

Corralien
Corralien

Reputation: 120509

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)

Upvotes: 2

Related Questions