Пример #1
0
def read_ppms():
    """
    Open PPMs (White Matter, Gray Matter, CSF, Rest)
    """
    Pdict = {}
    for tissue in tissues: 
        fname = tissue+'PostMap_1000.img'
        im = load_image(os.path.join(datadir, fname))
        Pdict[tissue] = im.get_data()/1000.
    affine = im.get_affine()
    return Pdict, affine
Пример #2
0
def load_probmap(id): 
    """
    Example: 
      pm = load_probmap('PostMap_1000.img')
    """
    pm = Probmap()
    for tissue in tissues: 
        fname = tissue+id
        im = load_image(join(datadir, fname))
        tmp = im.get_data().copy()
        pm[tissue] = tmp
    pm.normalize()
    return pm 
Пример #3
0
if len(sys.argv)>1: 
    similarity = sys.argv[1]
    if len(sys.argv)>2: 
        interp = sys.argv[2]
        if len(sys.argv)>3: 
            optimizer = sys.argv[3]

# Print messages
print ('Source brain: %s' % source)
print ('Target brain: %s' % target)
print ('Similarity measure: %s' % similarity)
print ('Optimizer: %s' % optimizer)

# Get data
print('Fetching image data...')
I = load_image(source_file)
J = load_image(target_file)

# Perform affine registration
# The output is an array-like object such that 
# np.asarray(T) is a customary 4x4 matrix 
print('Setting up registration...')
tic = time.time()
T = register(I, J, 
             similarity=similarity, 
             interp=interp, 
             optimizer=optimizer)
toc = time.time()
print('  Registration time: %f sec' % (toc-tic))

Пример #4
0
import numpy as np
from os.path import join

from nipy.io.imageformats import Nifti1Image, load as load_image, save as save_image
from nipy.utils import example_data
from nipy.neurospin.registration import FmriRealign4d
from pylab import * 

# Create Nifti1Image instances from both input files
rootpath = 'D:\\home\\Alexis\\data\\eccv'

mask = load_image(join(rootpath, 'mask.nii'))
xyz = np.where(mask.get_data()>0)

run = 'run1'

im_raw = load_image(example_data.get_filename('fiac','fiac0',run+'.nii.gz'))
im_npy = load_image(join(rootpath, 'npy_ra'+run+'.nii.gz'))
im_spm = load_image(join(rootpath, 'ra'+run+'.nii'))

raw = im_raw.get_data()
npy = im_npy.get_data()
spm = im_spm.get_data()

TR = 2.5

def compare(x, y, z):
    t = TR*np.arange(raw.shape[3])
    plot(t, raw[x,y,z,:], 'r')
    plot(t, spm[x,y,z,:], 'g')
    plot(t, npy[x,y,z,:], 'b')
Пример #5
0
from nipy.utils import example_data

from os.path import join, split
import sys


# Optinal argument
iterations = 1
if len(sys.argv)>1: 
    iterations = int(sys.argv[1])

# Input images are provided with the nipy-data package
runs = ['run1', 'run2']
runnames = [example_data.get_filename('fiac','fiac0',run+'.nii.gz') \
                for run in runs]
images = [load_image(runname) for runname in runnames]

# Create Image4d instances -- this is a local class representing a
# series of 3d images
runs = [image4d(im, tr=2.5, slice_order='ascending', interleaved=True) \
            for im in images]

# Correct motion within- and between-sessions
# By default 2 within-loops and 5 between-loops will be performed
transforms = realign4d(runs, within_loops=iterations, between_loops=2*iterations)

# Resample data on a regular space+time lattice using 4d interpolation
corr_runs = [resample4d(runs[i], transforms=transforms[i]) for i in range(len(runs))]

# Save images 
for i in range(len(runs)):
Пример #6
0
        P = posterior[tissue][posterior.mask()]
        Z = P.sum()
        tmp = data*P
        mu = tmp.sum(1)/Z
        mu_ = mu.reshape(2,1)
        sigma = np.dot(tmp, data.T)/Z - np.dot(mu_, mu_.T)
        gaussians[tissue] = Gaussian(mu, sigma)
    return gaussians

# Main Program
# Load prior probability map 
print('Loading data...')
prior = load_probmap('_1000Prior.img')

# Load image data and apply masking
im1 = load_image(join(datadir, 'BiasCorIm.img'))
im2 = load_image(join(datadir, 'DistanceMap.img'))
data = np.asarray([im.get_data()[prior.mask()] for im in [im1,im2]])

# Save image data in nifti for visualization with `anatomist`
if save_images: 
    print('Saving prior image...')
    save_image(im1, join(savedir, 'BiasCorIm.nii'))
    im = Image(prior.brain_ppm(), affine=im1.get_affine())
    save_image(im, join(savedir, 'Prior_Brain.nii'))

# Allocate posterior probability map and initialize it from the prior
posterior = Probmap(prior)

# EM algorithm: refine posterior map
print('Starting EM...')
Пример #7
0
        tmp.remove(',')
    cvect = map(float, tmp)


# Input files
fmri_files = [example_data.get_filename('fiac','fiac0',run) for run in ['run1.nii.gz','run2.nii.gz']]
design_files = [example_data.get_filename('fiac','fiac0',run) for run in ['run1_design.npz','run2_design.npz']]
mask_file = example_data.get_filename('fiac','fiac0','mask.nii.gz') 

# Get design matrix as numpy array
print('Loading design matrices...')
X = [np.load(f)['X'] for f in design_files]

# Get multi-session fMRI data 
print('Loading fmri data...')
Y = [load_image(f) for f in fmri_files]

# Get mask image
print('Loading mask...')
mask = load_image(mask_file)

# GLM fitting 
print('Starting fit...')
##glm = LinearModel(Y, X, mask=mask, model='ar1')
glm = LinearModel(Y, X, mask=mask)

# Compute the required contrast
print('Computing test contrast image...')
nregressors = X[0].shape[1] ## should check that all design matrices have the same 
c = np.zeros(nregressors)
c[0:4] = cvect
Пример #8
0
import numpy as np
from os.path import join

from nipy.io.imageformats import load as load_image, save as save_image
from nipy.neurospin.registration import FmriRealign4d
from pylab import * 


# Create Nifti1Image instances from both input files
rootpath = 'D:\\home\\Alexis\\data\\karla'

run = 'fms070149316-0032.nii'
raw = load_image(join(rootpath, run))
spm = load_image(join(rootpath, 'spm5_ra'+run))
npy = load_image(join(rootpath, 'new_ra'+run))

raw = raw.get_data()
spm = spm.get_data()
npy = npy.get_data()

def compare(x, y, z):
    plot(raw[x,y,z,:], 'g')
    plot(spm[x,y,z,:], 'r')
    plot(npy[x,y,z,:], 'b')


compare(39, 22, 18)


Пример #9
0
	H[0,1,:] = Hxy[:]
	H[1,0,:] = Hxy[:]
	Hxz = nd.gaussian_filter(data, sigma=sigma, order=[1,0,1])
	H[0,2,:] = Hxz[:]
	H[2,0,:] = Hxz[:]
	Hyz = nd.gaussian_filter(data, sigma=sigma, order=[0,1,1])
	H[1,2,:] = Hyz[:]
	H[2,1,:] = Hyz[:]
	return H
	

#datadir = 'D:\home\Alexis\data\delphine\zozo'
datadir = 'D:\Alexis\data\patient_03S0908'

# Read input image 
im = load_image(join(datadir, 'BiasCorIm.img'))
data = im.get_data()
data = data.astype('float')
sigma = 3
lda = 1

# Compute hessian 
print('Computing Hessian...')
H = hessian(data, sigma=sigma)

# Singular value decomposition
print('Computing singular values...') 
S = svd(H)

# Anisotropy measure 
print('Computing FA...') 
Пример #10
0
import numpy as np
from os.path import join, split
import sys
import time
from glob import glob

from nipy.io.imageformats import load as load_image, save as save_image
from nipy.neurospin.registration import FmriRealign4d

# Create Nifti1Image instances from both input files
rootpath = "D:\\home\\Alexis\\data\\karla"
runnames = glob(join(rootpath, "fms*.nii"))
runs = [load_image(run) for run in runnames]

## DEBUG
"""
idx = [4,5,6,7]
runs = [runs[i] for i in idx]
runnames = [runnames[i] for i in idx]
"""
print runnames

# Do the job
R = FmriRealign4d(runs, tr=2.4, slice_order="ascending", interleaved=False)
R.correct_motion()
corr_runs = R.resample()

# Save images
for i in range(len(runs)):
    aux = split(runnames[i])
    save_image(corr_runs[i], join(aux[0], "new_ra" + aux[1]))
Пример #11
0
from os.path import join
import numpy as np


"""
Example of running affine matching on the 'sulcal2000' database
"""

##rootpath = 'D:\\data\\sulcal2000'
rootpath = '/neurospin/lnao/Panabase/roche/sulcal2000'
        
print('Scanning data directory...')

# Get data
print('Fetching image data...')
I = load_image(join(rootpath,'nobias_anubis'+'.nii'))
J = load_image(join(rootpath,'ammon_TO_anubis'+'.nii'))

# Setup registration algorithm
matcher = IconicMatcher(I.get_data(), J.get_data(), 
                        I.get_affine(), J.get_affine()) ## I: source, J: target

# Params
size = 5
nsimu = 1
depth = 10

import pylab as pl

# Simulations 
for i in range(nsimu): 
Пример #12
0
import numpy as np
import scipy.ndimage as nd
from os.path import join
from nipy.io.imageformats import Nifti1Image as Image, load as load_image, save as save_image
import time
import pylab

id = 5
subjects = ["test", "016", "020", "023_1", "031", "03S0908"]
datadir = join("D:\home\AR203069\data\delphine", subjects[id])
tissues = ["CSF", "GM", "WM"]

# Read input image
im = load_image(join(datadir, "BiasCorIm.img"))

# Compute brain posterior probability map
P = np.zeros(im.get_shape())
for tissue in tissues:
    tmp = load_image(join(datadir, tissue + "PostMap_1000.img"))
    P += tmp.get_data()
P /= 1000.0
##P = np.gaussian_filter(P, sigma=3)
S = 2 * (P - 0.5)
del P

# Compute gradient norm image
G = nd.gaussian_gradient_magnitude(im.get_data(), sigma=3)

# Speed function
Gn = G / float(G.max())
Пример #13
0
# Clean brain tissue maps 
print('Decrease brain tissue probabilities outside brain...')
brain_prior = np.zeros(ppm['REST'].shape)

crude_brain = 2

## Morphology-based crude brain
if crude_brain == 1: 
    tmp = closing(ppm['REST'], size=6)
    threshold = .5
    brain_prior[mask] = np.minimum(1.-tmp[mask]/threshold, 1.)
    del tmp 
## Template-base crude brain
elif crude_brain in [2,3]: 
    im = load_image(os.path.join(datadir, 'MaskInitAnnot.img'))
    brain_prior = im.get_data()
    if crude_brain == 3: 
        brain_prior = gaussian_filter(brain_prior+.0, size=1)
        brain_prior /= brain_prior.max()


## Clean using crude brain mask 
ppm = geometry_cleaner(ppm, brain_prior, mask)
ppm, mask = normalize(ppm)

# Smooth using log opinion pool 
print('Performing log opinion pool smoothing...')
for tissue in tissues: 
    ppm[tissue] = log_opinion_pool(ppm[tissue], mask, size=1)
ppm, mask = normalize(ppm)
Пример #14
0
normalize = None
if len(sys.argv)>5: 
	normalize = sys.argv[5]
optimizer = 'powell'
if len(sys.argv)>6: 
	optimizer = sys.argv[6]

# Print messages
print ('Source brain: %s' % source)
print ('Target brain: %s' % target)
print ('Similarity measure: %s' % similarity)
print ('Optimizer: %s' % optimizer)

# Get data
print('Fetching image data...')
I = load_image(join(rootpath,'nobias_'+source+'.nii'))
J = load_image(join(rootpath,'nobias_'+target+'.nii'))

# Perform affine normalization 
print('Setting up registration...')
tic = time.time()
T = affine_register(I, J, 
		    similarity=similarity, interp=interp, 
		    normalize=normalize, optimizer=optimizer)
toc = time.time()
print('  Registration time: %f sec' % (toc-tic))


# Resample source image
print('Resampling source image...')
tic = time.time()