Beispiel #1
0
    def __del__(self):
        # enforce del on extensions wrapper so Python GC doesn't try
        # to free it up later on causing writes to freed memory.
        del self.extensions

        if self.__nimg:
            ncl.nifti_image_free(self.__nimg)
Beispiel #2
0
    def __newFromArray(self, data, hdr=None):
        """Create a `nifti_image` struct from a ndarray.

        :Parameters:
          data: ndarray
            Source ndarray.
          hdr: dict
            Optional dictionary with NIfTI header data.

        .. warning::
          This is an internal method. Neither its availability nor its API is
          guarenteed.
        """
        if hdr == None:
            hdr = {}

        # check array
        if len(data.shape) > 7:
            raise ValueError, \
                  "NIfTI does not support data with more than 7 dimensions."

        # create template nifti header struct
        niptr = ncl.nifti_simple_init_nim()
        nhdr = ncl.nifti_convert_nim2nhdr(niptr)

        # intermediate cleanup
        ncl.nifti_image_free(niptr)

        # convert virgin nifti header to dict to merge properties
        # with supplied information and array properties
        hdic = nhdr2dict(nhdr)

        # copy data from supplied header dict
        for k, v in hdr.iteritems():
            hdic[k] = v

        # finally set header data that is determined by the data array
        # convert NumPy to nifti datatype
        hdic['datatype'] = Ndtype2niftidtype(data)

        # make sure there are no zeros in the dim vector
        # especially not in #4 as FSLView doesn't like that
        hdic['dim'] = [ 1 for i in hdic['dim'] ]

        # set number of dims
        hdic['dim'][0] = len(data.shape)

        # set size of each dim (and reverse the order to match nifti format
        # requirements)
        for i, s in enumerate(data.shape):
            hdic['dim'][len(data.shape)-i] = s

        # set magic field to mark as nifti file
        hdic['magic'] = 'n+1'

        self._rebuildNimgFromHdrAndDict(nhdr, hdic)