2017-07-11 1 views
2

イメージに変換される読み込みボードからバイナリファイルを読み込もうとしています。 Matlabでは、すべてのバイトが正しく読み込まれ、イメージは完全に読み込まれます。しかし、Python(ver2.7はanacondaを使用しています)には、127列毎にゼロの行があります。 MATLABコードは:Pythonで別の結果バイナリファイルをロードするmatlabとpython

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. 

Iは、(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 
+0

インデックス作成は正しいですか?私は過去にPythonにmatlabを変換するのに苦労しました。そして、それは配列の索引付けまですべてでした... – DavidG

+1

ありがとう@DavidG。実際には2つのエラーがありました。ファイルにバイナリ( "rb")とラベルを付けることはありませんでした。これはMatlabとnumpyで異なる方法で行われました。私はupvoteして回答を受け入れましたが、私は管理しませんでした。 – vicgarmu

+1

おそらく自分で答えを書いて、私が実際にはあまりしなかったので、それを受け入れてマークするのが最も良いでしょう! – DavidG

答えて

0

は、バイナリとしてファイル(「RB」)とMATLABとnumpyの中に異なる方法で行われリシェイプを標識ではない、実際には2個のエラーがありました。 reshape(dim1、dim2、order = 'F')を使用して再構成を行うと、結果は同じになります。確認:Matlab vs Python: Reshape

関連する問題