def volumeToSurface(image, interpolation='linear'): fsaverageL = r"E:\brain\BNatlas\BN_Atlas_freesurfer\fsaverage\fsaverage_LR32k\fsaverage.L.inflated.32k_fs_LR.surf.gii" fsaverageR = r"E:\brain\BNatlas\BN_Atlas_freesurfer\fsaverage\fsaverage_LR32k\fsaverage.R.inflated.32k_fs_LR.surf.gii" textureL = surface.vol_to_surf( image, fsaverageL, inner_mesh= r"E:\brain\BNatlas\BN_Atlas_freesurfer\fsaverage\fsaverage_LR32k\fsaverage.L.white.32k_fs_LR.surf.gii" ) textureR = surface.vol_to_surf( image, fsaverageR, inner_mesh= r"E:\brain\BNatlas\BN_Atlas_freesurfer\fsaverage\fsaverage_LR32k\fsaverage.R.white.32k_fs_LR.surf.gii" ) #textureL = surface.vol_to_surf(image,fsaverageL,radius=4,interpolation=interpolation,kind='line',mask_img='Mask.nii') #textureR = surface.vol_to_surf(image,fsaverageR,radius=4,interpolation=interpolation,kind='line',mask_img='Mask.nii') newL = nib.GiftiImage( header=nib.load(r"E:\brain\GS\surface\NC_tmap.nii.L.func.gii").header) newR = nib.GiftiImage( header=nib.load(r"E:\brain\GS\surface\NC_tmap.nii.R.func.gii").header) dataArrayL = nib.gifti.gifti.GiftiDataArray(textureL.astype(np.float32)) dataArrayR = nib.gifti.gifti.GiftiDataArray(textureR.astype(np.float32)) newL.add_gifti_data_array(dataArrayL) newR.add_gifti_data_array(dataArrayR) return newL, newR
def annot_to_gifti(atlas): """ Converts FreeSurfer-style annotation file `atlas` to in-memory GIFTI image Parameters ---------- annot : os.PathLike Surface annotation file (.annot) Returns ------- gifti : nib.gifti.GiftiImage Converted gifti image """ labels, ctab, names = nib.freesurfer.read_annot(atlas) darr = nib.gifti.GiftiDataArray(labels, intent='NIFTI_INTENT_LABEL', datatype='NIFTI_TYPE_INT32') labeltable = nib.gifti.GiftiLabelTable() for key, label in enumerate(names): (r, g, b), a = (ctab[key, :3] / 255), (1.0 if key != 0 else 0.0) glabel = nib.gifti.GiftiLabel(key, r, g, b, a) glabel.label = label.decode() labeltable.labels.append(glabel) return nib.GiftiImage(darrays=[darr], labeltable=labeltable)
def make_binary_gifti(img, label, out): img = nib.load(img) arr = img.agg_data().ravel() labeltable = img.labeltable.get_labels_as_dict() mask = np.where(arr == label, label, 0) darray = nib.gifti.GiftiDataArray(mask, intent='NIFTI_INTENT_LABEL', datatype='NIFTI_TYPE_INT32') # get only the labels that appear in the mask mask_labels = np.unique(mask) retained_labels = [ x for x in img.labeltable.labels if x.key in mask_labels ] new_labels = nib.gifti.GiftiLabelTable() for i in retained_labels: new_labels.labels.append(i) img = nib.GiftiImage(darrays=[darray], labeltable=new_labels) img.to_filename(out) return out
def annot_to_gifti(annot_file, out): """Converts FreeSurfer-style annotation file `atlas` to a label.gii Based on Ross' code: https://github.com/rmarkello/abagen/blob/28e238cf6a12ecb3a8fde0abb70ab0b6e9108394/abagen/images.py#L53-L79 Parameters ---------- annot_file : os.PathLike Surface annotation file (.annot) out : str File name of output .label.gii """ labels, ctab, names = nib.freesurfer.read_annot(annot_file) darr = nib.gifti.GiftiDataArray(labels, intent='NIFTI_INTENT_LABEL', datatype='NIFTI_TYPE_INT32') labeltable = nib.gifti.GiftiLabelTable() for key, label in enumerate(names): (r, g, b), a = (ctab[key, :3] / 255), (1.0 if key != 0 else 0.0) glabel = nib.gifti.GiftiLabel(key, r, g, b, a) glabel.label = label.decode() labeltable.labels.append(glabel) img = nib.GiftiImage(darrays=[darr], labeltable=labeltable) img.to_filename(out) return out
def annot_to_func(annot_file, out, n=10): """Create a mock func.gii from an annotation file All timepoints (darrays) in .func.gii are duplicates of the annotation array. This enables a way to verify that expected data is correctly extracted (e.g., label 1 should extract a timeseries of all 1's, etc). Parameters ---------- annot_file : str Freesurfer annotation file (.annot) out : str File name of output .func.gii n : int, optional Number of timepoints to generate, by default 100 """ annot = nib.freesurfer.read_annot(annot_file) darrays = [] for i in range(n): x = nib.gifti.GiftiDataArray(annot[0], intent='NIFTI_INTENT_TIME_SERIES', datatype='NIFTI_TYPE_FLOAT32') darrays.append(x) img = nib.GiftiImage(darrays=darrays) img.to_filename(out) return out
def relabel_gifti(atlas, background=BACKGROUND, offset=None): """ Updates GIFTI images so label IDs are consecutive across hemispheres Parameters ---------- atlas : (2,) tuple-of-str Surface label files in GIFTI format (lh.label.gii, rh.label.gii) background : list-of-str, optional If provided, a list of IDs in `atlas` that should be set to 0 (the presumptive background value). Other IDs will be shifted so they are consecutive (i.e., 0--N). Default: `abagen.images.BACKGROUND` offset : int, optional What the lowest value in `atlas[1]` should be not including background value. If not specified it will be purely consecutive from `atlas[0]`. Default: None Returns ------- relabelled : (2,) tuple-of-nib.gifti.GiftiImage Re-labelled `atlas` files """ out = tuple() minval = 0 for hemi in atlas: # get necessary info from file img = load_gifti(hemi) data = img.agg_data() labels = img.labeltable.labels lt = {v: k for k, v in img.labeltable.get_labels_as_dict().items()} # get rid of labels we want to drop if background is not None: for val in background: idx = lt.get(val, 0) if idx == 0: continue data[data == idx] = 0 labels = [f for f in labels if f.key != idx] # reset labels so they're consecutive and update label keys data = _relabel(data, minval=minval, bgval=0) ids = np.unique(data) for n, i in enumerate(ids): labels[n].key = i minval = len(ids) - 1 if offset is None else int(offset) - 1 # make new gifti image with updated information darr = nib.gifti.GiftiDataArray(data, intent='NIFTI_INTENT_LABEL', datatype='NIFTI_TYPE_INT32') labeltable = nib.gifti.GiftiLabelTable() labeltable.labels = labels img = nib.GiftiImage(darrays=[darr], labeltable=labeltable) out += (img, ) return out
def save_metric(self, data, path): """ Save vertex-wise data as a .func.gii at path """ if not self.n_points == data.shape[0]: raise RuntimeError("Incorrect data shape") if not path.endswith('.func.gii'): print("appending .func.gii extension") path += '.func.gii' gii = nibabel.GiftiImage() gii.add_gifti_data_array( nibabel.gifti.GiftiDataArray(data.astype(NP_FLOAT))) nibabel.save(gii, path)
def spm_write_vol(image_volume_info, image_voxels, image_name, file_type): """ Writes an image volume to disk @image_volume_info - a structure containing image volume information (see spm_vol) @image_voxels - a one, two or three dimensional matrix containing the image voxels @image_name - name of the file to save the image in """ if file_type == ".nii" or file_type == ".nii.gz": data = image_voxels affine = image_volume_info.affine image_volume_info = nib.Nifti1Image(data, affine) nib.save(image_volume_info, image_name + file_type) else: data = image_voxels gi = nib.GiftiImage() gi.add_gifti_data_array(nib.gifti.GiftiDataArray(image_voxels)) nib.gifti.giftiio.write(gi, image_name + file_type)