< MINC < Tutorials

The pyminc version of hello world.

Keeping with other tutorials on how to program with the MINC toolkit, here's a simple example for how to open a volume, add one to every voxel, then write it out again. This being python, the code is nice and short!

#!/usr/bin/env python
from pyminc.volumes.factory import *
from numpy import *
import sys

if __name__ == "__main__":

    # get the input file
    infile = volumeFromFile(sys.argv[1])
    # get the output file using the same dimension info as the input file
    outfile = volumeLikeFile(sys.argv[1], sys.argv[2])

    # add one to the data 
    outfile.data = infile.data + 1

    # write out and close the volumes
    outfile.writeFile()
    outfile.closeVolume()
    infile.closeVolume()

Here's what the code does. The first bits are the imports of different modules - the one non-standard module is pyminc.volumes.factory. Most all creation of pyminc volume instances is done through a set of factory methods. They are:

FunctionDescription
volumeFromFileopens minc volume from an existing file - useful for reading existing data.
volumeLikeFilecreates a new minc volume from an existing file - useful for writing data.
volumeFromInstancecreates a new minc volume from an existing instance (python object)
volumeFromDescriptioncreates a new minc volume by specifying the dimensions, sizes, starts, etc.

The next line of the code assigns the output files data to be the input files data plus 1. Every pyminc volume has a data attribute, which is a numpy array. Note that the data is not actually read until the data attribute is accessed. The last bits then write the output file to disk and closes both volumes.

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.