コード例 #1
0
ファイル: image.py プロジェクト: dengemann/NeuroSynth
	def __init__(self, imgfile, datafile=None, subject=None, group=None, convert=True):
		
		self.name = imgfile.split('/')[-1].split('.')[0]
		self.json = imageutils.img_to_json(imgfile)
		# If image is in Analyze format, write NIFTI copy
		if convert and re.match('img', imgfile):
			img = NiftiImage(imgfile)
			img.save('%s.nii.gz' % self.name)
コード例 #2
0
    def __init__(self, dims=(91, 109, 91)):
        self.dims = dims
        resources = os.path.join(os.path.dirname(__file__), 'resources')

        self.mask_img = NiftiImage(
            os.path.join(resources, 'images',
                         'scalped_avg152T1_graymatter_smoothed.img'))
        self.atlas = NiftiImage(
            os.path.join(resources, 'images', 'MNI152_T1_2mm_brain.nii.gz'))
        self.full = np.float64(self.mask_img.data.ravel())
        self.in_mask = (self.full != 0)
        self.ind_in_mask = self.full
        self.ind_in_mask[self.in_mask] = range(np.sum(self.in_mask))
コード例 #3
0
    def __init__(self,
                 imgfile,
                 datafile=None,
                 subject=None,
                 group=None,
                 convert=True):

        self.name = imgfile.split('/')[-1].split('.')[0]
        self.json = imageutils.img_to_json(imgfile)
        # If image is in Analyze format, write NIFTI copy
        if convert and re.match('img', imgfile):
            img = NiftiImage(imgfile)
            img.save('%s.nii.gz' % self.name)
コード例 #4
0
ファイル: mri.py プロジェクト: gorlins/PyMVPA
 def handle_arg(arg):
     """Helper which would read in NiftiImage if necessary
     """
     if isinstance(arg, basestring):
         arg = NiftiImage(arg)
         argshape = arg.data.shape
         # Assure that we have 3D (at least)
         if len(argshape)<3:
             arg.data = arg.data.reshape((1,)*(3-len(argshape)) + argshape)
     if isinstance(arg, N.ndarray):
         if len(arg.shape) != 3:
             raise ValueError, "For now just handling 3D volumes"
     return arg
コード例 #5
0
ファイル: lightbox.py プロジェクト: heqing-psychology/PyMVPA
 def handle_arg(arg):
     """Helper which would read in NiftiImage if necessary
     """
     if isinstance(arg, basestring):
         arg = NiftiImage(arg)
         argshape = arg.data.shape
         # Assure that we have 3D (at least)
         if len(argshape) < 3:
             arg.data = arg.data.reshape((1, ) * (3 - len(argshape)) +
                                         argshape)
     if isinstance(arg, np.ndarray):
         if len(arg.shape) != 3:
             raise ValueError, "For now just handling 3D volumes"
     return arg
コード例 #6
0
    def __init__(self, under_image, over_image):
        """
        Provide the underlay and overlay NiftiImages.  Can also
        provide filename strings.

        Example:

        stat = OverlayMap('anat.nii.gz','stat.nii.gz')
        """
        # we've got traits
        HasTraits.__init__(self)

        # load in the image
        if isinstance(under_image, NiftiImage):
            # use it
            self.__under_image = under_image
        elif isinstance(under_image, str):
            # load from file
            self.__under_image = NiftiImage(under_image)
        else:
            raise ValueError("under_image must be a NiftiImage or a file.")

        # TODO: set the extent and spacing of the under image

        # set the over data
        if isinstance(over_image, str):
            # load from file
            over_image = NiftiImage(over_image)

        if isinstance(over_image, NiftiImage):
            # TODO: make sure it matches the dims of under image
            # TODO: set the extent
            
            # save just the dat
            self.__over_image = over_image.data.T

        elif isinstance(over_image, np.ndarray):
            # just set it
            # assumes it matches the dims and extent of the under image
            self.__over_image = over_image

        else:
            raise ValueError("over_image must be a NiftiImage, ndarray, or file.")

        self.__over_image = np.ma.masked_invalid(self.__over_image)

        self.configure_traits()
        pass
コード例 #7
0
    def _load_images(self):
        # shortcut
        imagefile = self.header.images.imagefile
        #self.nlevels = len(self._levels_by_id)

        # Set offset if defined in XML file
        # XXX: should just take one from the qoffset... now that one is
        #       defined... this origin might be misleading actually
        self._origin = np.array((0, 0, 0))
        if imagefile.attrib.has_key('offset'):
            self._origin = np.array(
                [int(x) for x in imagefile.get('offset').split(',')])

        # Load the image file which has labels
        if self._force_image_file is not None:
            imagefilename = self._force_image_file
        else:
            imagefilename = imagefile.text
        imagefilename = reuse_absolute_path(self._filename, imagefilename)

        try:
            self._image = NiftiImage(imagefilename)
        except RuntimeError, e:
            raise RuntimeError, \
                  " Cannot open file %s due to %s" % (imagefilename, e)
コード例 #8
0
        def getImage(self,filename):

            if str(filename).endswith('nii') or str(filename).endswith('nii.gz'):
                nim = NiftiImage(str(filename))
                shape = nim.data.shape

                img_data = nim.data

                miny = np.amin(img_data)
                arr = img_data.astype(float)
                arr -= miny
                maxy = np.amax(arr)
                arr = arr / (maxy/2)
                arr -= 1
                arr = sk.img_as_ubyte(arr)

                img_data = arr

            elif str(filename).endswith('hdr'):
                # Use the header to figure out the shape of the data
                # then load the raw data and reshape the array

                img_data = np.frombuffer(open(str(filename).replace('.hdr', '.dat'), 'rb').read(),
                                            np.uint8)\
                            .reshape((shape[2], shape[1], shape[0]))

            return (img_data,shape)
コード例 #9
0
def load_datadb_tutorial_data(path=os.path.join(
      pymvpa_datadbroot, 'tutorial_data', 'tutorial_data', 'data'),
    roi='brain'):
    """Loads the block-design demo dataset from PyMVPA dataset DB.

    Parameters
    ----------
    path : str
      Path of the directory containing the dataset files.
    roi : str or int or tuple or None
      Region Of Interest to be used for masking the dataset. If a string is
      given a corresponding mask image from the demo dataset will be used
      (mask_<str>.nii.gz). If an int value is given, the corresponding ROI
      is determined from the atlas image (mask_hoc.nii.gz). If a tuple is
      provided it may contain int values that a processed as explained
      before, but the union of a ROIs is taken to produce the final mask.
      If None, no masking is performed.
    """
    from nifti import NiftiImage
    from mvpa.datasets.mri import fmri_dataset
    from mvpa.misc.io import SampleAttributes
    if roi is None:
        mask = None
    elif isinstance(roi, str):
        mask = os.path.join(path, 'mask_' + roi + '.nii.gz')
    elif isinstance(roi, int):
        nimg = NiftiImage(os.path.join(path, 'mask_hoc.nii.gz'))
        tmpmask = nimg.data == roi
        mask = NiftiImage(tmpmask.astype(int), nimg.header)
    elif isinstance(roi, tuple) or isinstance(roi, list):
        nimg = NiftiImage(os.path.join(path, 'mask_hoc.nii.gz'))
        tmpmask = np.zeros(nimg.data.shape, dtype='bool')
        for r in roi:
            tmpmask = np.logical_or(tmpmask, nimg.data == r)
        mask = NiftiImage(tmpmask.astype(int), nimg.header)
    else:
        raise ValueError("Got something as mask that I cannot handle.")
    attr = SampleAttributes(os.path.join(path, 'attributes.txt'))
    ds = fmri_dataset(samples=os.path.join(path, 'bold.nii.gz'),
                      targets=attr.targets, chunks=attr.chunks,
                      mask=mask)
    return ds
コード例 #10
0
def handler(points, mr, gofscale, gof, sigma):
    from pdf2py import readwrite
    from meg import density
    from mri import transform
    from scipy import ndimage
    from nifti import NiftiImage
    from numpy import float32, int16, array

    report = {}
    fids = eval(mr.description)
    lpa = fids[0]
    rpa = fids[1]
    nas = fids[2]
    # self.points = array([[0,0,0],[10,0,0],[0,20,0]])#DEBUG-----------------
    xyz = transform.meg2mri(lpa, rpa, nas, dipole=points)
    # readwrite.writedata(xyz, os.path.dirname(mripath)+'/'+'xyz')
    print "lpa, rpa, nas", lpa, rpa, nas
    print mr.pixdim

    # do some scaling of the dips using the GOF as a weight.
    VoxDim = mr.voxdim[::-1]
    xyzscaled = (xyz / VoxDim).T
    print xyzscaled
    d = density.calc(xyz)
    gofscale = float32(gofscale)
    print "gofscale", gofscale
    s = gof - gofscale
    sf = (1 / (1 - gofscale)) * s
    ds = d * sf

    # apply a 1D gaussian filter
    z = density.val2img(mr.data, ds, xyzscaled)
    # sigma = float32(self.sigmaval.GetValue())
    print "sigma", sigma
    # sigma = 3
    print "filtering 1st dimension"
    f = ndimage.gaussian_filter1d(z, sigma * 1 / VoxDim[0], axis=0)
    print "filtering 2nd dimension"
    f = ndimage.gaussian_filter1d(f, sigma * 1 / VoxDim[1], axis=1)
    print "filtering 3rd dimension"
    f = ndimage.gaussian_filter1d(f, sigma * 1 / VoxDim[2], axis=2)

    scaledf = int16((z.max() / f.max()) * f * 1000)
    print "writing nifti output image"
    overlay = NiftiImage(int16(scaledf))

    overlay.setDescription(mr.description)
    overlay.setFilename(mr.filename + "dd")
    overlay.setQForm(mr.getQForm())

    return overlay
コード例 #11
0
    def save(self, image):
        nifti_image = NiftiImage(image.data)
        spacing = image.spacing.tolist()
        spacing.reverse()
        nifti_image.pixdim = spacing
        #        logging.warning("Image direction and origin will not be saved")
        nifti_image.save(self._filename)

        # Save gradient direction file if saving NIfTI
        if "mr_diffusion_sequence" in image.metadata:
            gradients = [[], [], []]
            b_values = []
            for diffusion in image.metadata["mr_diffusion_sequence"]:
                gradient = diffusion.diffusion_gradient_direction_sequence[
                    0].diffusion_gradient_orientation
                b_value = diffusion.diffusion_bvalue

                for index, value in enumerate(gradient):
                    gradients[index].append(str(value))
                b_values.append(str(b_value))

            gradients = "\n".join(
                [" ".join(direction) for direction in gradients])
            b_values = " ".join(b_values)

            base_name = os.path.splitext(self._filename)[0]
            if base_name.endswith(".nii"):
                base_name = os.path.splitext(base_name)[0]

            gradients_file = open("{0}.bvec".format(base_name), "w")
            gradients_file.write(gradients)
            gradients_file.close()

            bvalues_file = open("{0}.bval".format(base_name), "w")
            bvalues_file.write(b_values)
            bvalues_file.close()
コード例 #12
0
    def load_data(self, index=0):
        # pynifti does not appear to have a hook in nifti.clib.nifti_image_read,
        # nor is it possible to feed it a buffer filled with the content of the
        # file
        if self._report_progress is not None:
            self._report_progress(0.)

        image = NiftiImage(self._filename)
        data = image.data

        if self._report_progress is not None:
            self._report_progress(1.)

        while data.shape[0] == 1 and len(data.shape) > 3:
            data = data.reshape(data.shape[1:])
        return data
コード例 #13
0
    def LoadVolumeData(self, data_set):
        if data_set.endswith('nii') or data_set.endswith('nii.gz'):
            try:
                from nifti import NiftiImage
            except ImportError:
                print "Apparently you don't have PyNIfTI installed, see http://www.siafoo.net/snippet/310 for instructions"
                exit(1)
            nim = NiftiImage(data_set)

            img_data = nim.data
            img_header = nim.header
            print nim.data.shape

            if len(nim.data.shape) == 3:  # single volume
                pass
            elif len(nim.data.shape) == 4:  # multiple volume
                alldata = numpy.array(nim.data[0])
                print alldata.shape
                for i in range(1, len(nim.data)):
                    #self.addVol( nim.data[i] )
                    #alldata = numpy.append( alldata, nim.data[i], axis=0)
                    alldata = numpy.add(alldata, nim.data[i])
                print alldata.shape
                img_data = alldata
            elif len(nim.data.shape) == 5:  # tensor field volume
                alldata = numpy.array(nim.data[0][0])
                print alldata.shape
                for i in range(1, len(nim.data)):
                    #self.addVol( nim.data[i] )
                    #alldata = numpy.append( alldata, nim.data[i][0], axis=0)
                    alldata = numpy.add(alldata, nim.data[i][0])
                print alldata.shape
                img_data = alldata

        elif data_set.endswith('hdr'):
            # Use the header to figure out the shape of the data
            # then load the raw data and reshape the array
            shape = [int(x) for x in open(data_set).readline().split()]
            img_data = numpy.frombuffer(open(data_set.replace('.hdr', '.dat'), 'rb').read(),
                  numpy.uint8)\
              .reshape((shape[2], shape[1], shape[0]))

        self.addVol(img_data, img_header)
        return 0
コード例 #14
0
def run():
    if not 'screenshots' in os.listdir('./'):
        os.mkdir('./screenshots')

    #load Matlab data
#    import scipy.io
#    mri = scipy.io.loadmat('brainweb_128.mat')
#    activity = scipy.io.loadmat('L.mat')
#    v1 = uint16( activity['L']*(2**16*(1.0/dynrange)/activity['L'].max()) )
#    v2 = uint16( mri['t1_128']*(2**16/mri['t1_128'].max()) )

    #load Nifty data
    from nifti import NiftiImage
    v1 = NiftiImage('./activity_128.nii').data
    v2 = 0*v1

    #create volume renderer and initialize it
    V = VolumeRender((N,N,N),(512,512))
    V.show()
    V.set_volume1(v1)
    V.set_volume2(v2)

    #set visualization parameters
    V.set_density1(0.05)
    V.set_brightness1(5.4)
    V.set_transferOffset1(-0.02)
    V.set_transferScale1(1.27)
    V.set_density2(0.46)
    V.set_brightness2(0.5)
    V.set_transferOffset2(0.06)
    V.set_transferScale2(1.31)

    sleep(10)

    for im_frame in range(126):
        v1b = double(v1)
        v1b[:,im_frame:im_frame+thickness,:] = dynrange*double(v1[:,im_frame:im_frame+thickness,:])
        V.set_volume1(uint16(v1b))
        V.dump_screenshot("./screenshots/example2_%d.png"%im_frame)

    while 1:
        pass
コード例 #15
0
    def LoadVolumeData(self, data_set):

        if data_set.endswith('nii') or data_set.endswith('nii.gz'):
            try:
                from nifti import NiftiImage
            except ImportError:
                print "Apparently you don't have PyNIfTI installed, see http://www.siafoo.net/snippet/310 for instructions"
                exit(1)
            nim = NiftiImage(data_set)
            img_data = nim.data
        elif data_set.endswith('hdr'):
            # Use the header to figure out the shape of the data
            # then load the raw data and reshape the array
            shape = [int(x) for x in open(data_set).readline().split()]
            img_data = numpy.frombuffer(open(data_set.replace('.hdr', '.dat'), 'rb').read(),
                                        numpy.uint8)\
                        .reshape((shape[2], shape[1], shape[0]))

        img = vtkImageImportFromArray()
        img.SetArray(img_data)

        return img
コード例 #16
0
    def _load_images(self):
        resolution = self._resolution
        header = self.header
        images = header.images
        # Load present images
        # XXX might be refactored to avoid duplication of
        #     effort with PyMVPAAtlas
        ni_image = None
        resolutions = []
        if self._force_image_file is None:
            imagefile_candidates = [
                reuse_absolute_path(self._filename,
                                    i.imagefile.text,
                                    force=True) for i in images
            ]
        else:
            imagefile_candidates = [self._force_image_file]

        for imagefilename in imagefile_candidates:
            try:
                ni_image_ = NiftiImage(imagefilename, load=False)
            except RuntimeError, e:
                raise RuntimeError, " Cannot open file " + imagefilename

            resolution_ = ni_image_.pixdim[0]
            if resolution is None:
                # select this one if the best
                if ni_image is None or \
                       resolution_ < ni_image.pixdim[0]:
                    ni_image = ni_image_
                    self._image_file = imagefilename
            else:
                if resolution_ == resolution:
                    ni_image = ni_image_
                    self._image_file = imagefilename
                    break
                else:
                    resolutions += [resolution_]
コード例 #17
0
            Group(Item('scene', editor=SceneEditor(scene_class=MayaviScene), 
                       height=500, width=500, show_label=False)),
            Group(
                Group(Item('over_low', label="Lower Thresh"),
                      Item('over_hi', label="Upper Thresh"),
                      label="Overlay Properties",
                      show_border=True),
            ),
            Group(
                HGroup(Item('x_visible'),
                       Item('y_visible'),
                       Item('z_visible'),
                       Item('colormap'),
                       label="Plane visibility + colormap",
                       show_border=True),
            ),
        ),
        resizable=True,
        title='Overlay Viewer')
    

if __name__ == "__main__":

    # let's try it out
    # XXX: This will break without files there
    stat = OverlayMap(under_image=NiftiImage('/home/thorsten/struct_brain.nii.gz'),
                      over_image=NiftiImage('/home/thorsten/struct_brain.nii.gz'))
    #stat = OverlayMap(under_image=NiftiImage('TT_icbm452.nii.gz'),
    #                  over_image=NiftiImage('stats.nii.gz'))

コード例 #18
0
def run():
    if not 'screenshots' in os.listdir('./'):
        os.mkdir('./screenshots')
    #load Matlab data


#    import scipy.io
#    mri = scipy.io.loadmat('brainweb_128.mat')
#    activity = scipy.io.loadmat('L.mat')
#    v1 = uint16( activity['L']*(2**16*(1.0/dynrange)/activity['L'].max()) )
#    v2 = uint16( mri['t1_128']*(2**16/mri['t1_128'].max()) )

#load Nifty data
    from nifti import NiftiImage
    v1 = NiftiImage('./activity_128.nii').data
    v2 = 0 * v1

    #create volume renderer and initialize it
    V = VolumeRender((N, N, N), (512, 512))
    V.show()
    V.set_volume1(v1)
    V.set_volume2(v2)

    #set visualization parameters
    V.set_density1(0.05)
    V.set_brightness1(7.1)
    V.set_transferOffset1(-0.04)
    V.set_transferScale1(1.1)
    V.set_density2(0.05)
    V.set_brightness2(0.3)
    V.set_transferOffset2(0.05)
    V.set_transferScale2(1)

    #visualize a dynamic scene and save screenshots
    N_frames = N * image_steps
    d_rotation_x = 0.0
    d_rotation_y = 0.5
    d_zoom = 0.004

    im_frame_prev = 0
    frame = 0
    t_frame = 0
    while 1:
        frame += 1
        if frame < 1460:
            t_frame += 1
            if frame < 150 + 250:
                V.rotate(d_rotation_x, d_rotation_y)
            if (frame > 150 + 150 and frame < 150 + 500):
                V.zoom(d_zoom)
            if frame > 150 + 250:
                V.rotate(d_rotation_x / 4, d_rotation_y / 4)
            im_frame = t_frame / image_steps
            if not im_frame == im_frame_prev:
                im_frame_prev = im_frame
                if (im_frame < (N - thickness)):
                    v1b = double(v1)
                    v1b[:, :,
                        im_frame:im_frame + thickness] = dynrange * double(
                            v1[:, :, im_frame:im_frame + thickness])
                    #v1b = v1b*(2**16/v1b.max())
                    V.set_volume1(uint16(v1b))
        if frame > 1500:
            t_frame -= 1
            im_frame = t_frame / image_steps
            if not im_frame == im_frame_prev:
                im_frame_prev = im_frame
                if (im_frame < (N - thickness)):
                    v1b = double(v1)
                    v1b[:, :,
                        im_frame:im_frame + thickness] = dynrange * double(
                            v1[:, :, im_frame:im_frame + thickness])
                    #v1b = v1b*(2**16/v1b.max())
                    V.set_volume1(uint16(v1b))
        if (frame > 2550 + 100):
            break
        elif (frame > 2550 + 75):
            V.zoom(-d_zoom * 3.5)
        elif frame > 2550:
            V.rotate(d_rotation_x, d_rotation_y)
            V.zoom(-d_zoom * 3.5)
        V.dump_screenshot("./screenshots/%d.png" % frame)
        sleep(0.003)

    while 1:
        pass
コード例 #19
0
from nifti import NiftiImage
from datetime import datetime
prima=datetime.now()
#FLAGS
#############################
background_threshold=25     #
reverse_YAxis=True          #
#############################



nim=NiftiImage("cervello")
print "Processing '%s'" %nim.filename,
nim.load()

d=nim.extent #genearatin a 4-uple containing the dimension of nifti image (x,y,z,time)
O=(d[0]/2,d[1]/2)
print "(%dx%dx%d)\n" %(d[0],d[1],d[2])
print "--------------------------------------------------------------------------------"
print

bb=nim.bbox


#ASSUMING IMAGE HAS TIME SIZE=1  -> program will work just on first istant on 4-dimensional images
print "\tLeft Pole\tRight Pole\tAverage Pole"


for z in range(bb[0][0],bb[0][1]) : #bottom-up scroll
    y=bb[1][0]
    found=False
コード例 #20
0
ファイル: lightbox.py プロジェクト: heqing-psychology/PyMVPA
        pl.show()

    plotter.fig.plotter = plotter
    return plotter.fig


if __name__ == "__main__":
    # for easy debugging
    import os
    from mvpa.base import cfg
    impath = os.path.join('datadb', 'tutorial_data')
    plot_lightbox(
        #background = NiftiImage('%s/anat.nii.gz' % impath),
        background='%s/anat.nii.gz' % impath,
        background_mask=None,
        overlay=NiftiImage('%s/bold.nii.gz' % impath).data.squeeze()[0],
        overlay_mask='%s/mask_brain.nii.gz' % impath,
        #
        do_stretch_colors=False,
        add_colorbar=True,
        cmap_bg='gray',
        cmap_overlay='hot',  # YlOrRd_r # pl.cm.autumn
        #
        fig=None,
        # vlim describes value limits
        # clim color limits (same by default)
        vlim=[100, None],
        #vlim_type = 'symneg_z',
        interactive=True,
        #
        #nrows = 2,
コード例 #21
0
def write_nifti_file(settings, basename):
    """Write data <basename>.nii."""
    nim = NiftiImage(get_data(settings))
    filename = basename + '.nii'
    print 'Writing data to the nifti file ' + filename + '.'
    nim.save(filename)
コード例 #22
0
def write_nifti_file(settings, basename):
    """Write data <basename>.nii."""
    nim = NiftiImage(get_data(settings))
    filename = basename+'.nii'
    print 'Writing data to the nifti file '+filename+'.'    
    nim.save(filename)