Пример #1
0
    def set_zooms(self, zooms):
        ''' Set zooms into header fields

        See docstring for ``get_zooms`` for examples
        '''
        hdr = self._header_data
        zooms = np.asarray(zooms)
        if len(zooms) != len(hdr['delta']):
            raise HeaderDataError('Expecting %d zoom values for ndim' %
                                  hdr['delta'])
        if np.any(zooms < 0):
            raise HeaderDataError('zooms must be positive')
        delta = hdr['delta']
        delta[:] = zooms[:]
Пример #2
0
    def __init__(self, binaryblock=None, check=True):
        ''' Initialize header from binary data block

        Parameters
        ----------
        binaryblock : {None, string} optional
            binary block to set into header.  By default, None, in
            which case we insert the default empty header block
        check : bool, optional
            Whether to check content of header in initialization.
            Default is True.
        '''
        if binaryblock is None:
            self._header_data = self._empty_headerdata()
            return
        # check size
        if len(binaryblock) != self.template_dtype.itemsize:
            raise HeaderDataError('Binary block is wrong size')
        hdr = np.ndarray(shape=(),
                         dtype=self.template_dtype,
                         buffer=binaryblock)
        #if goodRASFlag, discard delta, Mdc and c_ras stuff
        if int(hdr['goodRASFlag']) < 0:
            hdr = self._set_affine_default(hdr)
        self._header_data = hdr.copy()
        if check:
            self.check_fix()
        return
Пример #3
0
    def _write_data(self, mghfile, data, header):
        ''' Utility routine to write image

        Parameters
        ----------
        mghfile : file-like
           file-like object implementing ``seek`` or ``tell``, and
           ``write``
        data : array-like
           array to write
        header : analyze-type header object
           header
        '''
        shape = header.get_data_shape()
        if data.shape != shape:
            raise HeaderDataError('Data should be shape (%s)' %
                                  ', '.join(str(s) for s in shape))
        offset = header.get_data_offset()
        out_dtype = header.get_data_dtype()
        array_to_file(data, mghfile, out_dtype, offset)
Пример #4
0
def save(img, filename, dtype_from='data'):
    """Write the image to a file.

    Parameters
    ----------
    img : An `Image` object
    filename : string
        Should be a valid filename.
    dtype_from : {'data', 'header'} or dtype specifier, optional
        Method of setting dtype to save data to disk. Value of 'data' (default),
        means use data dtype to save.  'header' means use data dtype specified
        in header, if available, otherwise use data dtype.  Can also be any
        valid specifier for a numpy dtype, e.g. 'i4', ``np.float32``.  Not every
        format supports every dtype, so some values of this parameter or data
        dtypes will raise errors.

    Returns
    -------
    image : An `Image` object
        Possibly modified by saving.

    See Also
    --------
    load_image : function for loading images
    Image : image object

    Examples
    --------
    Make a temporary directory to store files

    >>> import os
    >>> from tempfile import mkdtemp
    >>> tmpdir = mkdtemp()

    Make some some files and save them

    >>> import numpy as np
    >>> from nipy.core.api import Image, AffineTransform
    >>> from nipy.io.api import save_image
    >>> data = np.zeros((91,109,91), dtype=np.uint8)
    >>> cmap = AffineTransform('kji', 'zxy', np.eye(4))
    >>> img = Image(data, cmap)
    >>> fname1 = os.path.join(tmpdir, 'img1.nii.gz')
    >>> saved_img1 = save_image(img, fname1)
    >>> saved_img1.shape
    (91, 109, 91)
    >>> fname2 = os.path.join(tmpdir, 'img2.img.gz')
    >>> saved_img2 = save_image(img, fname2)
    >>> saved_img2.shape
    (91, 109, 91)
    >>> fname = 'test.mnc'
    >>> saved_image3 = save_image(img, fname)
    Traceback (most recent call last):
       ...
    ValueError: Sorry, we cannot yet save as format "minc"

    Finally, we clear up our temporary files:

    >>> import shutil
    >>> shutil.rmtree(tmpdir)

    Notes
    -----
    Filetype is determined by the file extension in 'filename'.  Currently the
    following filetypes are supported:

    * Nifti single file : ['.nii', '.nii.gz']
    * Nifti file pair : ['.hdr', '.hdr.gz']
    * SPM Analyze : ['.img', '.img.gz']
    """
    # Try and get nifti
    dt_from_is_str = isinstance(dtype_from, basestring)
    if dt_from_is_str and dtype_from == 'header':
        # All done
        io_dtype = None
    elif dt_from_is_str and dtype_from == 'data':
        io_dtype = img.get_data().dtype
    else:
        io_dtype = np.dtype(dtype_from)
    # make new image
    ni_img = nipy2nifti(img, data_dtype=io_dtype)
    ftype = _type_from_filename(filename)
    if ftype.startswith('nifti1'):
        ni_img.to_filename(filename)
    elif ftype == 'analyze':
        try:
            ana_img = nib.Spm2AnalyzeImage.from_image(ni_img)
        except HeaderDataError:
            raise HeaderDataError('SPM analyze does not support datatype %s' %
                                  ni_img.get_data_dtype())
        ana_img.to_filename(filename)
    else:
        raise ValueError('Sorry, we cannot yet save as format "%s"' % ftype)
    return img