在 Python 中将浮点数组量化为字节数组

Quantize Float Array to Byte Array in Python

我有一个这样的浮点数组 [0.1,0.4,1.5,2.22,3] 其中最大值始终为 3.0

我想将其量化为从 0 到 255 的字节数组 对于每个值,我想将其量化为 (byte)((value / 3.0) * 255.0)

有没有一种方法可以在 numpy 中非常快速地做到这一点,而不是迭代 Python 中的每个值并重建一个新的字节数组?

使用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)