我有一些二进制输入文件(扩展名“ .bin”)描述了海洋深度的二维字段,并且均为负浮点数.我已经能够将它们加载到matlab中,如下所示:
f = fopen(filename,'r','b');
data = reshape(fread(f,'float32'),[128 64]);
这个matlab代码为我提供了介于0和-5200之间的双精度值.但是,当我尝试在Python中执行相同操作时,我奇怪地得到了0到1e-37之间的值. Python代码是:
f = open(filename, 'rb')
data = np.fromfile(f, np.float32)
data.shape = (64,128)
奇怪的是,在两种情况下,在(64,128)数组的正确位置显示的土地的掩码值为0.似乎只是关闭的numpy.float32值的大小和符号.
我在Python代码中做错了什么?
解决方法:
numpy.fromfile与平台无关,尤其是在文档中提到了“字节顺序”:
Do not rely on the combination of tofile and fromfile for data storage, as the binary files generated are are not platform independent. In particular, no byte-order or data-type information is saved.
您可以尝试:
data = np.fromfile(f, '>f4') # big-endian float32
和:
data = np.fromfile(f, '
并检查哪一个(大字节序或小字节序)给出正确的值.
标签:binary,arrays,matlab,python,numpy
来源: https://codeday.me/bug/20191111/2018938.html