[英]Convert numpy unit8 raw array directly to float32
In my situation I get a numpy.ndarray
as unit8
of size 4 * n
which represents raw binary data of float32
entities. 在我的情况下,我得到一个numpy.ndarray
作为unit8
4 * n
unit8
,它表示float32
实体的原始二进制数据。 So 4 items together represent one float32
. 所以4个项目一起代表一个float32
。 To get float32
numbers I currently convert uint8
raw data to a binary string and than read from this string the float32
values. 要获取float32
数字,我目前将uint8
原始数据转换为二进制字符串,而不是从此字符串中读取float32
值。
np.fromstring(raw_unit8_data.tostring(), dtype='<f4')
Is there a possibility to do this conversion directly without converting the uint8
data to a string first? 是否有可能直接进行此转换而不首先将uint8
数据转换为字符串?
You could use view
to have NumPy reinterpret the raw data as the appropriate data type. 您可以使用view
让NumPy将原始数据重新解释为适当的数据类型。 For example: 例如:
>>> raw_unit8_data = np.array([32, 14, 135, 241], dtype='uint8')
>>> raw_unit8_data.view('<f4')
array([ -1.33752168e+30], dtype=float32)
This has the advantage of not using any temporary arrays or buffers (we're just changing how the memory is read) and gives the same values as your current method: 这样做的好处是不使用任何临时数组或缓冲区(我们只是改变读取内存的方式),并提供与当前方法相同的值:
>>> np.fromstring(raw_unit8_data.tostring(), dtype='<f4')
array([ -1.33752168e+30], dtype=float32)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.