2017-07-11 84 views
2

我想從一個讀出板讀取二進制文件,將被轉換爲圖像。在Matlab中,所有字節都被正確讀取並且圖像完整地填充。但在Python(ver2.7使用anaconda)中,每127列有一行零。 的Matlab代碼是:不同的結果加載二進制文件的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. 

在蟒我嘗試使用f.read() 具有相同的結果從蟒np.fromfile()和直接讀取。

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

你確定你的索引是正確的?我在過去將matlab轉換爲python時遇到了麻煩,而這一切都歸功於數組索引... – DavidG

+1

謝謝@DavidG。事實上有兩個錯誤,沒有將文件標記爲二進制文件(「rb」)和重塑,這在Matlab和numpy中以不同的方式完成。我嘗試着上傳並接受你的回覆,但我沒有管理。 – vicgarmu

+1

可能最好自己寫答案,然後將其標記爲已接受,因爲我沒有做太多的工作! – DavidG

回答

0

實際上有兩個錯誤,不標記該文件作爲二進制(「RB」)和重塑,這是在Matlab和numpy的不同的方式完成。 如果使用重塑完成整形(dim1,dim2,order ='F'),結果是相同的。檢查:Matlab vs Python: Reshape