Ejemplo n.º 1
0
 def to_files(self, files=None):
     ''' Write image to files passed, or self._files
     '''
     if files is None:
         files = self._files
         if files is None:
             raise ValueError('Need files to write data')
     data = self.get_data()
     # Adapt header to possible two<->one file difference
     is_pair = files['header'] != files['image']
     hdr = self.get_header().for_file_pair(is_pair)
     slope, inter, mn, mx = adapt_header(hdr, data)
     hdrf = allopen(files['header'], 'wb')
     hdr.write_to(hdrf)
     if is_pair:
         imgf = allopen(files['image'], 'wb')
     else: # single file for header and image
         imgf = hdrf
         # streams like bz2 do not allow seeks, even forward.  We
         # check where to go, and write zeros up until the data part
         # of the file
         offset = hdr.get_data_offset()
         diff = offset-hdrf.tell()
         if diff > 0:
             hdrf.write('\x00' * diff)
     write_data(hdr, data, imgf, inter, slope, mn, mx)
     self._header = hdr
     self._files = files
Ejemplo n.º 2
0
 def from_filespec(klass, filespec):
     ret = super(Spm99AnalyzeImage, klass).from_filespec(filespec)
     import scipy.io as sio
     matf = ret._files['mat']
     try:
         matf = allopen(matf)
     except IOError:
         return ret
     mats = sio.loadmat(matf)
     if 'mat' in mats: # this overrides a 'M', and includes any flip
         mat = mats['mat']
         if mat.ndim > 2:
             warnings.warn('More than one affine in "mat" matrix, '
                           'using first')
             mat = mat[:,:,0]
         ret._affine = mat
         return ret
     elif 'M' in mats: # the 'M' matrix does not include flips
         hdr = ret._header
         if hdr.default_x_flip:
             ret._affine = np.dot(np.diag([-1,1,1,1]), mats['M'])
         else:
             ret._affine = mats['M']
     else:
         raise ValueError('mat file found but no "mat" or "M" in it')
     return ret
Ejemplo n.º 3
0
 def from_files(klass, files):
     fname = files['header']
     header = klass._header_maker.from_fileobj(allopen(fname))
     affine = header.get_best_affine()
     ret =  klass(None, affine, header)
     ret._files = files
     return ret
Ejemplo n.º 4
0
 def get_data(self):
     ''' Lazy load of data '''
     if not self._data is None:
         return self._data
     if not self._files:
         return None
     try:
         fname = self._files['image']
     except KeyError:
         return None
     self._data = read_data(self._header, allopen(fname))
     return self._data
Ejemplo n.º 5
0
 def to_files(self, files=None):
     super(Spm99AnalyzeImage, self).to_files(files)
     if self._affine is None:
         return
     import scipy.io as sio
     matfname = self._files['mat']
     mfobj = allopen(matfname, 'wb')
     mat = self._affine
     hdr = self._header
     if hdr.default_x_flip:
         M = np.dot(np.diag([-1,1,1,1]), mat)
     else:
         M = mat
     # use matlab 4 format to allow gzipped write without error
     sio.savemat(mfobj, {'M': M, 'mat': mat}, format='4')
     mfobj.close()
Ejemplo n.º 6
0
def load(filespec, *args, **kwargs):
    ''' Load file given filespec, guessing at file type

    Parameters
    ----------
    filespec : string or file-like
       specification of filename or file to load
    *args
    **kwargs
       arguments to pass to image load function

    Returns
    -------
    img : ``SpatialImage``
       Image of guessed type

    '''
    # Try and guess file type from filename
    if isinstance(filespec, basestring):
        fname = filespec
        for ending in ('.gz', '.bz2'):
            if filespec.endswith(ending):
                fname = fname[:-len(ending)]
                break
        if fname.endswith('.nii'):
            return nifti1.load(filespec, *args, **kwargs)
        if fname.endswith('.mnc'):
            return minc.load(filespec, *args, **kwargs)
    # Not a string, or not recognized as nii or mnc
    try:
        files = nifti1.Nifti1Image.filespec_to_files(filespec)
    except ValueError:
        raise RuntimeError('Cannot work out file type of "%s"' %
                           filespec)
    hdr = nifti1.Nifti1Header.from_fileobj(
        vu.allopen(files['header']),
        check=False)
    magic = hdr['magic']
    if magic in ('ni1', 'n+1'):
        return nifti1.load(filespec, *args, **kwargs)
    return spm2.load(filespec, *args, **kwargs)