2016-07-15 116 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

是的,这个文件包含了大量的数据,这些数据在一些数据中丢失了,因此矩阵的大小无法精确计算。现在我正在尝试使用非常古老的方式为每行数据设置数组,并将它们放入矩阵中。这是一项很大的工作 –