导入文本文件并导出3D图像

时间:2016-07-15 03:18:59

标签: python numpy plot 3d

我需要做的是加载一个txt文件并制作一个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:新数组的总大小必须保持不变为" volume =   np.reshape(datatrimmed,(i,m,-1))#create音量,离开   要浮动的扫描点数"

1 个答案:

答案 0 :(得分:0)

似乎你对我的价值对于你正在做的重塑来说太大了。

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)