跳轉到內容

MINC/教程/PythonSliceLoop

來自華夏公益教科書,開放的書籍,開放的世界

使用 pyminc 的切片迴圈示例

[編輯 | 編輯原始碼]

在 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 體積控制代碼的陣列以及一個包含所有體積的一個切片的陣列,然後遍歷所有切片。 在每個切片處,陣列都用每個體積的當前切片重新填充,計算統計資訊(在本例中為模式),並將結果插入到輸出體積中。

華夏公益教科書