MINC/教程/PythonSliceLoop
外观
在 pyminc 中打开一个体积时,在访问 .data 变量之前不会读取任何数据。这意味着您可以同时打开很多体积,然后选择性地获取一个超平面以节省内存。下面的示例读取了很多体积,以查找每个点的模式(最常见的体素) - 这是一种用于分割的简单体素投票方案。 文本中有一些注释,更详细的解释将在后面给出
#!/usr/bin/env python
# all the imports go here
from pyminc.volumes.factory import *
from numpy import *
from scipy.stats import *
from optparse import OptionParser
if __name__ == "__main__":
# some argument handling
usage = "Usage text"
description = "Description text"
parser = OptionParser(usage=usage, description=description)
parser.add_option("--clobber", dest="clobber",
help="clobber output file",
type="string")
(options, args) = parser.parse_args()
if len(args) < 4:
parser.error("Incorrect number of arguments")
outfilename = args[-1]
propfilename = args[-2]
# clobber check should go here
# create an array of volume handles
volhandles = []
nfiles = len(args)-2
for i in range( nfiles ):
volhandles.append(volumeFromFile(args[i], dtype='ubyte'))
outfile = volumeFromInstance(volhandles[0], outfilename)
proportion = volumeFromInstance(volhandles[0], propfilename)
# hold one slice from all volumes
sliceArray = zeros( (nfiles,
volhandles[0].sizes[1],
volhandles[0].sizes[2]))
# now loop over the slices to get on slice at a time from all volumes - then take the mode
for i in range(volhandles[0].sizes[0]):
print "SLICE: %i" % i
for j in range(nfiles):
t = volhandles[j].getHyperslab((i,0,0),
(1,volhandles[0].sizes[1],
volhandles[0].sizes[2]))
t.shape = (volhandles[0].sizes[1], volhandles[0].sizes[2])
sliceArray[j::] = t
# take the mode
m = mode(sliceArray)
# and write the mode and its proportion to the output files
outfile.data[i::] = m[0]
proportion.data[i::] = m[1] / nfiles
proportion.writeFile()
proportion.closeVolume()
outfile.writeFile()
outfile.closeVolume()
此切片循环中的关键步骤是创建所有 MINC 体积句柄的数组以及一个包含所有体积的一个切片的数组,然后遍历所有切片。 在每个切片处,数组都用每个体积的当前切片重新填充,计算统计信息(在本例中为模式),并将结果插入到输出体积中。