How to use the nibabel.freesurfer function in nibabel

To help you get started, we’ve selected a few nibabel examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github the-virtual-brain / tvb-recon / bnm / recon / io / fs.py View on Github external
def read_annot(self, hemi, annot_name):
        "Read an annotation for given hemisphere and annotation name."
        # TODO annotation class
        return nibabel.freesurfer.read_annot(self.annot_path(hemi, annot_name))
github trislett / TFCE_mediation / tfce_mediation / tmanalysis / STEP_1_tm_models.py View on Github external
data.append(np.hstack((data_lh[mask_lh].T,data_rh[mask_rh].T)))
				data_lh = data_rh = []
		data = np.array(data, dtype=np.float32, order = 'c')
		nonzero = np.zeros_like(data)
		nonzero[:] = np.copy(data)

		#TFCE
		if opts.vertextriangularmesh:
			# 3 Neighbour vertex connectity
			print("Creating adjacency set")
			if opts.vertexsrf:
				v_lh, faces_lh = nib.freesurfer.read_geometry(opts.vertexsrf[0])
				v_rh, faces_rh = nib.freesurfer.read_geometry(opts.vertexsrf[1])
			else:
				v_lh, faces_lh = nib.freesurfer.read_geometry("%s/fsaverage/surf/lh.sphere" % os.environ["SUBJECTS_DIR"])
				v_rh, faces_rh = nib.freesurfer.read_geometry("%s/fsaverage/surf/rh.sphere" % os.environ["SUBJECTS_DIR"])
			adjac_lh = create_adjac_vertex(v_lh,faces_lh)
			adjac_rh = create_adjac_vertex(v_rh,faces_rh)
		elif opts.adjfiles:
			print("Loading prior adjacency set")
			arg_adjac_lh = opts.adjfiles[0]
			arg_adjac_rh = opts.adjfiles[1]
			adjac_lh = np.load(arg_adjac_lh)
			adjac_rh = np.load(arg_adjac_rh)
		elif opts.vertexdist:
			print("Loading prior adjacency set for %s mm" % opts.vertexdist[0])
			adjac_lh = np.load("%s/adjacency_sets/lh_adjacency_dist_%s.0_mm.npy" % (scriptwd,str(opts.vertexdist[0])))
			adjac_rh = np.load("%s/adjacency_sets/rh_adjacency_dist_%s.0_mm.npy" % (scriptwd,str(opts.vertexdist[0])))
		else:
			print("Error")
		if opts.noweight or opts.vertextriangularmesh:
			vdensity_lh = 1
github trislett / TFCE_mediation / tfce_mediation / tmanalysis / STEP_1_tm_models.py View on Github external
else:
			astr = ','.join(a.astype(np.str))
			astr = '['+astr+']'
		if num_missing == 0:
			print("[%d] : %s\t%s" % (counter, roi, astr))
		else:
			print("[%d] : %s\t%s\t\tCONTAINS %d MISSING VARIABLES!" % (counter, roi, astr, num_missing))

	print("\nChecking image lengths [# subjects = %d]" % num_subjects)
	if datatype == 'surface':
		for sf in folders:
			temp_img = ("%s/lh.all.%s.%s.mgh" % (sf,surface,FWHM))
			if not os.path.isfile(temp_img):
				print ("Error: %s not found." % temp_img)
			else:
				temp_num_img = nib.freesurfer.mghformat.load(temp_img).shape[-1]
				if temp_num_img == num_subjects:
					print("%s ...OK" % temp_img)
				else:
					print("Error: Length of %s [%d] does not match number of subjects[%d]" % (temp_img, temp_num_img, num_subjects))
				temp_img = ("%s/rh.all.%s.%s.mgh" % (sf,surface,FWHM))
				temp_num_img = nib.freesurfer.mghformat.load(temp_img).shape[-1]
				if temp_num_img == num_subjects:
					print("%s ...OK" % temp_img)
				else:
					print("Error: Length of %s [%d] does not match number of subjects[%d]" % (temp_img, temp_num_img, num_subjects))
	if datatype == 'volumetric':
		for temp_img in voximgs:
			if not os.path.isfile(temp_img):
				print ("Error: %s not found." % temp_img)
			elif len(nib.load(temp_img).shape) != 4:
				print ("Error: %s is not a 4D image." % temp_img)
github trislett / TFCE_mediation / py_func.py View on Github external
def write_vertStat_img(statname, vertStat, outdata_mask, affine_mask, surf, hemi, bin_mask, TFCEfunc, all_vertex):
	vertStat_out=np.zeros(all_vertex).astype(np.float32, order = "C")
	vertStat_out[bin_mask] = vertStat
	vertStat_TFCE = np.zeros_like(vertStat_out).astype(np.float32, order = "C")
	TFCEfunc.run(vertStat_out, vertStat_TFCE)
	outdata_mask[:,0,0] = vertStat_TFCE * (vertStat[np.isfinite(vertStat)].max()/100)
	fsurfname = "%s_%s_%s_TFCE.mgh" % (statname,surf,hemi)
	os.system("echo %s_%s_%s,%f >> max_TFCE_contrast_values.csv" % (statname,surf,hemi, outdata_mask[np.isfinite(outdata_mask[:,0,0])].max()))
	nib.save(nib.freesurfer.mghformat.MGHImage(outdata_mask,affine_mask),fsurfname)
	outdata_mask[:,0,0] = vertStat_out
	fsurfname = "%s_%s_%s.mgh" % (statname,surf,hemi)
	nib.save(nib.freesurfer.mghformat.MGHImage(outdata_mask,affine_mask),fsurfname)
github pelednoam / mmvt / src / misc / show_meg_pysurfer.py View on Github external
stc2 = read_stc(stc2_fname)

    data1 = stc1['data'][:, time_point]
    data2 = stc2['data'][:, time_point]
    data = data1 - data2
    print(data.shape)
    vertices = stc1['vertices']

    brain.add_data(data, colormap=colormap, vertices=vertices,
                   smoothing_steps=10, time=time,
                   hemi=hemi)
    mlab.show()

if (plot_labels):
    aparc_file = '/home/npeled/subjects/mg78/label/{}.laus250.annot'.format(hemi)
    labels, ctab, names = nib.freesurfer.read_annot(aparc_file)
    d = np.load('/home/npeled/mmvt/mg78/labels_data_laus250_{}.npz'.format(hemi))
    data = np.diff(d['data'][:, time]).squeeze()
    vtx_data = data[labels]
    brain.add_data(vtx_data, colormap=colormap, alpha=.8)
    mlab.show()
github nipy / mindboggle / mindboggle / labels / multiatlas.py View on Github external
name of VTK file containing number of different label counts
    labelvotes_file : string
        name of VTK file containing number of votes per majority label

    """
    from os import path, getcwd
    import nibabel as nb
    import pyvtk
    from mindboggle.labels.multiatlas import vote_labels
    from mindboggle.utils.io_file import string_vs_list_check

    # Load multiple label sets
    print("Load annotation files...")
    label_lists = []
    for annot_file in annot_files:
        labels, colortable, names = nb.freesurfer.read_annot(annot_file)
        label_lists.append(labels)
    print("Annotations loaded.")

    # Vote on labels for each vertex
    labels_max, label_votes, label_counts, \
    consensus_vertices = vote_labels(label_lists)

    # Check type to make sure the filename is a string
    # (if a list, return the first element)
    surface_file = string_vs_list_check(surface_file)

    # Save files
    VTKReader = pyvtk.VtkData(surface_file)
    Vertices =  VTKReader.structure.points
    Faces =     VTKReader.structure.polygons
github nipy / mindboggle / mindboggle / labels / multiatlas.py View on Github external
name of VTK file containing number of different label counts
    labelvotes_file : string
        name of VTK file containing number of votes per majority label

    """
    from os import path, getcwd
    import nibabel as nb
    import pyvtk
    from mindboggle.labels.multiatlas import vote_labels
    from mindboggle.utils.io_file import string_vs_list_check

    # Load multiple label sets
    print("Load annotation files...")
    label_lists = []
    for annot_file in annot_files:
        labels, colortable, names = nb.freesurfer.read_annot(annot_file)
        label_lists.append(labels)
    print("Annotations loaded.")

    # Vote on labels for each vertex
    labels_max, label_votes, label_counts, \
    consensus_vertices = vote_labels(label_lists)

    # Check type to make sure the filename is a string
    # (if a list, return the first element)
    surface_file = string_vs_list_check(surface_file)

    # Save files
    VTKReader = pyvtk.VtkData(surface_file)
    Vertices =  VTKReader.structure.points
    Faces =     VTKReader.structure.polygons
github trislett / TFCE_mediation / tfce_mediation / tmanalysis / STEP_1_vertex_tfce_multiple_regression.py View on Github external
def run(opts):

	scriptwd = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
	surface = opts.surface[0]
	FWHM = opts.fwhm[0]

	#load surface data
	img_data_lh = nib.freesurfer.mghformat.load("lh.all.%s.%s.mgh" % (surface,FWHM))
	data_full_lh = img_data_lh.get_data()
	data_lh = np.squeeze(data_full_lh)
	affine_mask_lh = img_data_lh.get_affine()
	n = data_lh.shape[1] # num_subjects
	outdata_mask_lh = np.zeros_like(data_full_lh[:,:,:,1])
	img_data_rh = nib.freesurfer.mghformat.load("rh.all.%s.%s.mgh" % (surface,FWHM))
	data_full_rh = img_data_rh.get_data()
	data_rh = np.squeeze(data_full_rh)
	affine_mask_rh = img_data_rh.get_affine()
	outdata_mask_rh = np.zeros_like(data_full_rh[:,:,:,1])
	if not os.path.exists("lh.mean.%s.%s.mgh" % (surface,FWHM)):
		mean_lh = np.sum(data_lh,axis=1)/data_lh.shape[1]
		outmean_lh = np.zeros_like(data_full_lh[:,:,:,1])
		outmean_lh[:,0,0] = mean_lh
		nib.save(nib.freesurfer.mghformat.MGHImage(outmean_lh,affine_mask_lh),"lh.mean.%s.%s.mgh" % (surface,FWHM))
		mean_rh = np.sum(data_rh,axis=1)/data_rh.shape[1]