【问题标题】:different result loading binary files matlab and python加载二进制文件matlab和python的不同结果
【发布时间】:2017-07-13 20:02:09
【问题描述】:

我正在尝试从读出板上读取一个二进制文件,该文件将被转换为图像。在 Matlab 中,所有字节都被正确读取并且图像被完全填充。但是在python(使用anaconda的ver2.7)中,每127列有一行零。 Matlab代码为:

fid = fopen(filename);
Rawdata = fread(fid,'uint8');
Data1d = Rawdata(2:2:end).* 256+ Rawdata(1:2:end)  ;
% converts Data1 to a 2D vector, adding a row of zeros to make the reshape
% possible to 3D
Data2d = [reshape(Data1d,4127,1792); zeros(1,1792)];
% reshapes again, but adding a new dimension
Data3d = reshape(Data2d(:),129,32,1792);
% selects the first 128 values in the first dimension 
Data3d = Data3d(1:128,:,:);
Data2d = reshape(Data3d(:),4096,1792);
Data2d = Data2d';
CMVimage = Data2d;   
fclose(fid); %VGM 2017-01-14 the file should be closed.

在 python 中,我尝试了 np.fromfile() 并使用 f.read() 直接从 python 读取 结果相同。

import numpy as np
import matplotlib.pyplot as plt
"""
reads the input .dat file and converts it to an image
Problem: line of zeros every 127 columns in columns: 127,257,368...
curiosly, the columns are in the position of the new byte. 
In matlab it works very well. 
"""


def readDatFile(filename):
""" reads the binary file in python not in numpy
the data is byte type and it is converted to integer. 

    """
    import binascii
    f = open(filename, 'rb')
    data = f.read()
    #dataByte = bytearray(data)

    f.close()
    data_out = []
    for num in data:
        aux = int(binascii.hexlify(num), 16)
        data_out.append(aux) 
        #print aux

    myarray = np.asarray(data_out) 
    return myarray 




def rawConversionNew(filename):
    # reads data from a binary file with tupe uint
#    f = open(filename, 'rb')
#    Rawdata = np.fromfile(f, dtype=np.uint8)
#    f.close()

    Rawdata = readDatFile(filename)

    ## gets the image
    Data1d = 256*Rawdata[1::2] + Rawdata[0::2]               
    Data2d = Data1d.reshape(1792,4127)
    Data2d = Data2d.T 
    Data2d = np.vstack([Data2d,np.zeros((1,1792),dtype=np.uint16)] )
    Data3d = Data2d.reshape(129,32,1792)
    Data3d = Data3d[0:128,:,:]
    #plt.figure()
    #plt.plot(np.arange(Data3d.shape[0]),Data3d[:,1,1])
    #print (Data3d[:,0,0])
    CMVimage = Data3d.reshape(4096,1792).T

  return CMVimage

【问题讨论】:

  • 你确定你的索引是正确的吗?过去我在将 matlab 转换为 python 时遇到了麻烦,这完全取决于数组的索引...
  • 感谢@DavidG。实际上有两个错误,没有将文件标记为二进制(“rb”)和重塑,这在 Matlab 和 numpy 中以不同的方式完成。我试图投票并接受你的回复,但我没有管理。
  • 最好自己写答案,然后将其标记为已接受,因为我并没有真正做太多!

标签: python matlab


【解决方案1】:

实际上有两个错误,没有将文件标记为二进制 (“rb”) 和 reshape,这在 Matlab 和 numpy 中以不同的方式完成。 如果使用 reshape(dim1,dim2,order='F') 完成重塑,则结果是相同的。检查:Matlab vs Python: Reshape

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-31
    • 2015-04-26
    • 2019-01-27
    • 2014-09-28
    • 2019-06-24
    • 1970-01-01
    • 2021-06-22
    • 2021-01-13
    相关资源
    最近更新 更多