2016-07-15 117 views
0

我需要做的是加載一個txt文件併爲成像創建一個3D矩陣。導入一個文本文件並導出一個3D圖像

隨着下面的代碼,當文本文件是一個包含大量數據的大文件時,我收到一個錯誤。

# Load a .txt data output from tomoview into a volume 

import numpy as np 
from tifffile import imsave 
import io 


#number of elements in array 
i = 128 

#open the text file with all headers 
data = io.open('BreastPhantomTest.txt','r',encoding='cp1252') 

#create a list of all lines with data in them - the typical format is for 16 lines of header, 
#followed by 'n' lines of data each 'm' tab delimited data points long 
#where 'n' is the number of points in the scan direction and 'm' is the number of digitization points 
#This repeats for each 'i element. 

#line = data.readlines() ##-- this method will get slow for larger datasets I believe 
datatrimmed=[] 
#assume lines with data start with a non-zero number this should scale up in data size. 
#We can also use this method to get other parameters out of the header. 
for line in data: 
    #line = line.rstrip() 
    if not line[0].isdigit():continue #take only the digits 
    #if not line[0]!='0':continue #take only the lines that don't start with a zero. 
    f = line.split() 
    datatrimmed.append(f) 



m = len(f)  
volume = np.reshape(datatrimmed,(i,m,-1)) #create the volume, leaving the number of scan points to float 
volume1=np.float32(volume) 
imsave('volume.tiff',volume1) 

我收到的錯誤是這樣的:

ValueError: total size of new array must be unchanged as "volume = np.reshape(datatrimmed,(i,m,-1)) #create the volume, leaving the number of scan points to float"

回答

0

這似乎是你的i值是太大了,你正在做的重塑。

P.S. Numpy的loadtxt將爲您處理這項工作。您可以指定要跳過的標題行數。

import numpy as np 

with open('BreastPhantomTest.txt','r', encoding='cp1252') as f: 
    data = np.loadtxt(f, skiprows=16) 

data = data[np.where(data[:, 0] != 0)].astype('float32') # filter out lines starting with 0 

i = 128 
m = data.shape[1] 
assert data.shape[0] <= i, "Your value for i is too big" 
data = data.reshape(i, m, -1) 
+0

是的,這個文件包含了大量的數據,這些數據在一些數據中丟失了,因此矩陣的大小無法精確計算。現在我正在嘗試使用非常古老的方式爲每行數據設置數組,並將它們放入矩陣中。這是一項很大的工作 –