我有一些二进制输入文件(扩展名为“.bin”),它们描述了海洋深度的二维场,并且都是负 float 。我已经能够按如下方式将它们加载到 matlab 中:
f = fopen(filename,'r','b');
data = reshape(fread(f,'float32'),[128 64]);
此 matlab 代码为我提供了介于 0 和 -5200 之间的 double 值。但是,当我尝试在 Python 中执行相同操作时,我奇怪地得到了介于 0 和 1e-37 之间的值。 Python代码是:
f = open(filename, 'rb')
data = np.fromfile(f, np.float32)
data.shape = (64,128)
奇怪的是,在这两种情况下,land 的掩码值都显示在 (64,128) 数组的正确位置。它似乎只是关闭的 numpy.float32
值的大小和符号。
我在 Python 代码中做错了什么?
最佳答案
numpy.fromfile
不是平台独立的,尤其是文档中提到的“字节顺序”:
Do not rely on the combination of
tofile
andfromfile
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, '<f4') # little-endian float32
并检查哪一个(大端或小端)给出了正确的值。
关于python - 在python和matlab中将浮点二进制文件读入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44335749/