def dscalar_from_cifti(img, data, name): import numpy as np import nibabel as nb # Clear old CIFTI-2 extensions from NIfTI header and set intent nifti_header = img.nifti_header.copy() nifti_header.extensions.clear() nifti_header.set_intent('ConnDenseScalar') # Create CIFTI-2 header scalar_axis = nb.cifti2.ScalarAxis(np.atleast_1d(name)) axes = [ nb.cifti2.cifti2_axes.from_index_mapping(mim) for mim in img.header.matrix ] if len(axes) != 2: raise ValueError( f"Can't generate dscalar CIFTI-2 from header with axes {axes}") header = nb.cifti2.cifti2_axes.to_header( axis if isinstance(axis, nb.cifti2.BrainModelAxis) else scalar_axis for axis in axes) new_img = nb.Cifti2Image(data.reshape(header.matrix.get_data_shape()), header=header, nifti_header=nifti_header) return new_img
def sg_filter_cii(cii_file, polyorder=3, deriv=0, window_length=210, tr=1): """sg_filter_cii temporally filters cii file contents""" # cii data cii_in = nb.load(cii_file) window = np.int(window_length / tr) if window % 2 == 0: window += 1 data = cii_in.get_data() data_filt = savgol_filter(data.T, window_length=window, polyorder=polyorder, deriv=deriv, axis=1, mode='nearest').T data_filt = data - data_filt + data_filt.mean(axis=0) cii_out = nb.Cifti2Image(dataobj=data_filt, header=cii_in.header, nifti_header=cii_in.nifti_header, extra=cii_in.extra) out_name = os.path.splitext(cii_file)[0] + '_sg.nii' out_file = os.path.abspath(out_name) nb.save(cii_out, out_file) return out_file
def csave(filename, cdata, chead, cnhdr=None, cxtra=None, cfmap=None, returnImg=False): ''' Saves a cifti image from a collection of cifti substructures to file. Parameters ---------- filename: str string containing output file path cdata: numpy ndarray array containing data to be saved, can be 1D (single timepoint) or 2D (timeseries) chead: Cifti2Header cifti header data, generally extracted from a previously read cifti file cnhdr: Nifti2Header (optional) nifti header data, also generally extracted from a previously read cifti file cxtra: dict (optional) extra cifti metadata, generally empty cfmap: dict (optional) file map, generally contains the string 'image' returnImg: bool optionally return the compiled cifti object ''' cout = nb.Cifti2Image(dataobj=cdata, header=chead, nifti_header=cnhdr, extra=cxtra, file_map=cfmap) cout.to_filename(filename) if returnImg is True: return cout
def save(self, fout): """ Write self.data to image `fout`. Parameters ---------- fout : str absolute path to output neuroimaging file. must be a DLABEL file!! Returns ------- None """ if self.ischanged: cp = Cifti2Parser() cp.parse(string=eT.tostring(self.tree)) header = cp.header else: header = self.header if fout[-11:] != ".dlabel.nii": # TODO: improve input handling fout += ".dlabel.nii" new_img = nib.Cifti2Image(self.data, header=header, nifti_header=self.nifti_header) nib.save(new_img, fout)
def save_individual_matrices(matrices, subjects, output_dir, clean=False, pconn_dummy=False): """ Take a list of (correlation) matrices, optionally clean them (if we are only interested in the first row and column) and save them as individual NIfTI (and, optionally CIFTI) files """ n_matrices = len(matrices) if n_matrices != len(subjects): print( "ERROR: Mismatch between number of matrices ({}) and number of subjects ({})." .format(n_matrices, len(subjects))) exit(1) n = 0 if clean: clean_matrices = [ ] # If we want clean matrices it makes sense to return a list of cleaned matrices if pconn_dummy: img_dummy = nib.load(pconn_dummy) create_dir_if_not_exist(output_dir) for matrix in matrices: fname = os.path.join(output_dir, "{}.nii".format(subjects[n].rstrip('.txt'))) print("Saving matrix {}/{} to {} ({} %)".format( n + 1, n_matrices, fname, round(((n + 1) / n_matrices) * 100, 2))) if clean: matrix_to_save = clean_matrix(matrix) clean_matrices.append(matrix_clean) else: matrix_to_save = matrix if pconn_dummy: img_new_fname = os.path.join(output_dir, "{}.pconn.nii".format(subjects[n])) img_new = nib.Cifti2Image(matrix, header=img_dummy.header, file_map=img_dummy.file_map) print(" - Saving pconn to {}".format(img_new_fname)) img_new.to_filename(img_new_fname) save_matrix(matrix_to_save, fname) n += 1 if clean: return clean_matrices
def to_cifti(self, default_axis=None): """ Create a CIFTI image from the data :param default_axis: What to use as an axis along any undefined dimensions - By default an error is raised - if set to "scalar" a ScalarAxis is used with names of "default {index}" - if set to "series" a SeriesAxis is used :return: nibabel CIFTI image """ if any(ax is None for ax in self.axes): if default_axis is None: raise ValueError( "Can not store to CIFTI without defining what is stored along each dimension" ) elif default_axis == 'scalar': def get_axis(n: int): return cifti2_axes.ScalarAxis( [f'default {idx + 1}' for idx in range(n)]) elif default_axis == 'series': def get_axis(n: int): return cifti2_axes.SeriesAxis(0, 1, n) else: raise ValueError( f"default_axis should be set to None, 'scalar', or 'series', not {default_axis}" ) new_axes = [ get_axis(sz) if ax is None else ax for ax, sz in zip(self.axes, self.arr.shape) ] else: new_axes = list(self.axes) data = self.arr if data.ndim == 1: # CIFTI axes are always at least 2D data = data[None, :] new_axes.insert(0, cifti2_axes.ScalarAxis(['default'])) return nib.Cifti2Image(data, header=new_axes)
def average_bar_ciis(file_1, file_2): """no reversal or shifting necessary for the bar files """ # cii data ciis = [nb.load(cii_file) for cii_file in [file_1, file_2]] data = [cii_in.get_data() for cii_in in ciis] m_data = np.mean(np.array(data), axis=0) cii_out = nb.Cifti2Image(dataobj=m_data, header=ciis[0].header, nifti_header=ciis[0].nifti_header, extra=ciis[0].extra) out_name = (os.path.splitext(file_1)[0] + '_av.nii').replace( 'BAR1', 'BOTHBARS') out_file = os.path.abspath(out_name) nb.save(cii_out, out_file) return out_file
def test_DerivativesDataSink_dtseries_json_hack(tmp_path): cifti_fname = str(tmp_path / "test.dtseries.nii") axes = (nb.cifti2.SeriesAxis(start=0, step=2, size=20), nb.cifti2.BrainModelAxis.from_mask(np.ones((5, 5, 5)))) hdr = nb.cifti2.cifti2_axes.to_header(axes) cifti = nb.Cifti2Image(np.zeros(hdr.matrix.get_data_shape(), dtype=np.float32), header=hdr) cifti.nifti_header.set_intent("ConnDenseSeries") cifti.to_filename(cifti_fname) source_file = tmp_path / "bids" / "sub-01" / "func" / "sub-01_task-rest_bold.nii.gz" source_file.parent.mkdir(parents=True) source_file.touch() dds = bintfs.DerivativesDataSink( in_file=cifti_fname, base_directory=str(tmp_path), source_file=str(source_file), compress=False, out_path_base="", space="fsLR", grayordinates="91k", RepetitionTime=2.0, ) res = dds.run() out_path = Path(res.outputs.out_file) assert out_path.name == "sub-01_task-rest_space-fsLR_bold.dtseries.nii" old_sidecar = out_path.with_name( "sub-01_task-rest_space-fsLR_bold.dtseries.json") new_sidecar = out_path.with_name("sub-01_task-rest_space-fsLR_bold.json") assert old_sidecar.exists() assert "grayordinates" in json.loads(old_sidecar.read_text()) assert new_sidecar.exists() assert "RepetitionTime" in json.loads(new_sidecar.read_text())
def average_phase_encoded_ciis(file_1, file_2, shift=9): """second data file will be reversed and shifted by twice the haemodynamic delay """ # cii data ciis = [nb.load(cii_file) for cii_file in [file_1, file_2]] data = [cii_in.get_data() for cii_in in ciis] data[1] = data[1][::-1] data[1] = np.roll(data[1], shift, axis=0) m_data = np.mean(np.array(data), axis=0) cii_out = nb.Cifti2Image(dataobj=m_data, header=ciis[0].header, nifti_header=ciis[0].nifti_header, extra=ciis[0].extra) out_name = os.path.splitext(file_1)[0] + '_av.nii' out_file = os.path.abspath(out_name) nb.save(cii_out, out_file) return out_file
def make_parcellation_ciis(sub, cii_out_dir, subject_list, lh_labels, rh_labels, net_names): print(sub) sub_idx = np.where(subject_list == sub)[0][0] # lh sub_lh = lh_labels[:, sub_idx] # rh sub_rh = rh_labels[:, sub_idx] sub_rh[sub_rh != 0] = sub_rh[sub_rh != 0] + 17 bihemi_labels = np.concatenate([sub_lh, sub_rh]) # read parcellation template dscalar_template = nb.load( '/gpfs/milgram/project/holmes/HOLMES_UKB/external/CBIG_private/stable_projects/brain_parcellation/Schaefer2018_LocalGlobal/Parcellations/HCP/fslr32k/cifti/Schaefer2018_200Parcels_17Networks_order.dlabel.nii' ) for idx in np.arange(1, 18): sub_labels = nb.Cifti2Image(dataobj=np.asarray([bihemi_labels]), header=dscalar_template.header) tmp_labels = sub_labels.dataobj[0] tmp_labels[tmp_labels != idx] = 0 write_labels = np.array([list(tmp_labels)]) cur_name = net_names[idx - 1] cii_write = nb.cifti2.Cifti2Image(dataobj=write_labels, header=sub_labels.header) out_path = os.path.join( cii_out_dir, '{}_{}_kong_indiv_parcellation.dscalar.nii'.format(sub, cur_name)) nb.save(cii_write, out_path) labelfile = '/gpfs/milgram/project/holmes/kma52/topo_herit/data/HCP/hcp_net17_lhrh_colortable.txt' dlabel_out = out_path.replace('dscalar.nii', 'dlabel.nii') print(dlabel_out) add_colors = 'wb_command -cifti-label-import ' + out_path + ' ' + labelfile + ' ' + dlabel_out os.system(add_colors) return (dlabel_out)
def psc_cii(cii_file, method='median'): """psc_cii performs percent signal change conversion on cii file contents""" # cii data cii_in = nb.load(cii_file) data = cii_in.get_data() if method == 'mean': data_m = data.mean(axis=0) elif method == 'median': data_m = np.median(data, axis=0) data_conv = 100.0 * (data - data_m) / data_m cii_out = nb.Cifti2Image(dataobj=data_conv, header=cii_in.header, nifti_header=cii_in.nifti_header, extra=cii_in.extra) out_name = os.path.splitext(cii_file)[0] + '_psc.nii' out_file = os.path.abspath(out_name) nb.save(cii_out, out_file) return out_file
# load func data func_img = nib.load(func_file) func_data = func_img.get_fdata() func_header = func_img.header # extract and integrate ROIs roi_array = np.squeeze(roi_data) for index, label in enumerate(roi_array): if label == label_mt_R or label == label_mst_R or label == label_v4t_R or label == label_fst_R or label == label_mt_L or label == label_mst_L or label == label_v4t_L or label == label_fst_L: continue else: roi_array[index] = 0 roi_data = np.expand_dims(roi_array, axis=1).reshape(1, -1) # save new roi new_roi_img = nib.Cifti2Image(roi_data, roi_header) nib.cifti2.save(new_roi_img, '/nfs/e2/workingshop/masai/rdmdec_workdir/new_roi.dlabel.nii') # mask func data for index, label in enumerate(roi_array): if not label == 0: continue else: for surf in func_data: surf[index] = 0 # save new func new_func_img = nib.Cifti2Image(func_data, func_header) nib.cifti2.save( new_func_img,
plot_vert = vert_to_plot for idx in plot_subjects: #tri_idxs = np.triu_indices(n=lh_vert_dice.shape[0], k=1) plot_subj = hcp_df.id[idx] #plot_idx = np.where(np.isin(hcp_df_order.id, str(plot_subj)))[0][0] bihemi_labels = np.concatenate([lh_labels[:, idx], rh_labels[:, idx]]) idx_arr = np.arange(len(bihemi_labels)) bihemi_labels[~np.isin(idx_arr, neigh_vert_df.vert.values)] = 0 # read parcellation template dscalar_template = nb.load( '/gpfs/milgram/project/holmes/HOLMES_UKB/external/CBIG_private/stable_projects/brain_parcellation/Schaefer2018_LocalGlobal/Parcellations/HCP/fslr32k/cifti/Schaefer2018_200Parcels_17Networks_order.dlabel.nii' ) sub_labels = nb.Cifti2Image(dataobj=np.asarray([list(bihemi_labels)]), header=dscalar_template.header) out_path = os.path.join( base_dir, 'figures/kma_{}_vert{}_sub_labels.dscalar.nii'.format( plot_subj, plot_vert)) nb.save(sub_labels, out_path) out_path labelfile = '/gpfs/milgram/project/holmes/kma52/topo_herit/data/HCP/hcp_net17_lhrh_colortable.txt' dlabel_out = out_path.replace('dscalar.nii', 'dlabel.nii') add_colors = 'wb_command -cifti-label-import ' + out_path + ' ' + labelfile + ' ' + dlabel_out os.system(add_colors) # make black ROI border bihemi_labels[~np.isin(idx_arr, neigh_vert_df.vert.values)] = 0 bihemi_labels[np.isin(idx_arr, neigh_vert_df.vert.values)] = 1 sub_labels = nb.Cifti2Image(dataobj=np.asarray([list(bihemi_labels)]),
def write_to_cifti(result, hdr, n_rows, script_name): hdr_axis0 = hdr.get_axis(0) hdr_axis0.size = n_rows hdr_axis1 = hdr.get_axis(1) cifti_out = nb.Cifti2Image(result, (hdr_axis0, hdr_axis1)) nb.save(cifti_out, f'{script_name}_results.dtseries.nii')
def output_cifti(cifti_file, cifti, proc_data, output_dir): base_file_dt = os.path.splitext(os.path.basename(cifti_file))[0] base_file = os.path.splitext(base_file_dt)[0] cifti_out = nb.Cifti2Image(proc_data, cifti.header) cifti_out.set_data_dtype('<f4') nb.save(cifti_out, output_dir + '/' + base_file + '_filt.dtseries.nii')
# 1, 91282 # first_column = np.zeros(91282).reshape((-1,1)) # Head_data = np.where(Head_data > 0.25, Head_data, 0).reshape((-1,1)) # Upperlimbs_data = np.where(Upperlimbs_data > 0.25, Upperlimbs_data, 0).reshape((-1,1)) # Lowerlimbs_data = np.where(Lowerlimbs_data > 0.25, Lowerlimbs_data, 0).reshape((-1,1)) # pmap_matrix = np.c_[first_column, Head_data, Upperlimbs_data, Lowerlimbs_data] # # max_pmap_data = np.argmax(pmap_matrix, axis = 1).reshape((1,-1)) # # header = nib.load(Head_file).header # save_path = 'pmap.dscalar.nii' # image = nib.Cifti2Image(max_pmap_data, header) # nib.cifti2.save(image, save_path) Head_data = np.squeeze(Head_data) Upperlimbs_data = np.squeeze(Upperlimbs_data) Lowerlimbs_data = np.squeeze(Lowerlimbs_data) first_column = np.zeros(91282) Head_data = np.where(Head_data > 0.25, Head_data, 0) Upperlimbs_data = np.where(Upperlimbs_data > 0.25, Upperlimbs_data, 0) Lowerlimbs_data = np.where(Lowerlimbs_data > 0.25, Lowerlimbs_data, 0) pmap_matrix = np.c_[first_column, Head_data, Upperlimbs_data, Lowerlimbs_data] max_pmap_data = np.argmax(pmap_matrix, axis=1)[None, :] header = nib.load(Head_file).header save_path = 'max_pmap.dscalar.nii' image = nib.Cifti2Image(max_pmap_data, header) nib.cifti2.save(image, save_path)
def write_dense_image(dscalars, fout, palette='magma', palette_params=None): """ Create a new DSCALAR neuroimaging file. Parameters ---------- dscalars : numpy.ndarray dense (i.e., whole-brain vertex/voxel-wise) scalar array of length 91282 fout : str absolute path to output neuroimaging file with *.dscalar.nii* extension (if an extension is provided) palette : str, default 'magma' name of color palette palette_params : dict or None, default None additional (key: value) pairs passed to "wb_command -cifti-palette". for more info, see https://humanconnectome.org/software/workbench-command/-cifti-palette Returns ------- None Notes ----- For a list of available color palettes, see the wbplot.constants module or visit: https://www.humanconnectome.org/software/workbench-command/-metric-palette. The file defined by wbplot.config.DSCALAR_FILE is used as a template to achieve this. Thus the `dscalars` array provided to this function must be contain 59412 elements (i.e., it must include both cortical hemispheres). Note the subcortex is not currently supported. In standard bilateral cortical dscalar files, elements [0,29695] correspond to the left hemisphere and elements [29696,59411] correspond to the right hemisphere. Thus, you can simply pad the other elements with NaN if you want only a single hemisphere to be plotted. Example usage of `palette_params`: palette_params = dict() palette_params["disp-zero"] = True palette_params["disp-positive"] = True palette_params["disp-negative"] = False palette_params["inversion"] = "POSITIVE_WITH_NEGATIVE" The above, passed to this function, would invert the color palette and display only positive- and zero-valued scalars (when `fout` is opened in wb_view). Note that if you wish to define vmin and vmax by hand, you should do one of the following: >> palette_params = { "pos-user": (pos_min, pos_max), "neg-user": (neg_min, neg_max)} where pos_min is the minimum positive value shown, pos_max is the maximum positive value shown, neg_min is the minimum negative (ie, most negative) value shown, and neg_max is the maximum negative (ie, least negative) value shown or >> palette_params = { "pos-percent": (pos_min, pos_max), "neg-percent": (neg_min, neg_max)} where pos_min, pos_max, neg_min, and neg_max are the same as before but expressed as *percentages* of the positive and negative values Raises ------ ValueError : palette_params contains an invalid key,value pair """ # TODO: add function for users to map from 32k unilateral to CIFTI subset # TODO: implement subcortex if fout[-12:] != ".dscalar.nii": # TODO: improve input handling fout += ".dscalar.nii" new_data = np.copy(dscalars) # Load template dscalar file of = nib.load(constants.DSCALAR_FILE) temp_data = np.asanyarray(of.dataobj) # Write new data to file data_to_write = new_data.reshape(np.shape(temp_data)) new_img = nib.Cifti2Image(dataobj=data_to_write, header=of.header, nifti_header=of.nifti_header) prefix = fout.split(".")[0] cifti_palette_input = prefix + "_temp.dscalar.nii" nib.save(new_img, cifti_palette_input) # Use Workbench's command line utilities to change color palette mode = "MODE_AUTO_SCALE" # default mode (not DMN, haha) disp_zero = disp_neg = disp_pos = True if palette_params: args = list(palette_params.keys()) if "pos-percent" in args and "neg-percent" in args: mode = "MODE_AUTO_SCALE_PERCENTAGE" elif "pos-user" in args and "neg-user" in args: mode = "MODE_USER_SCALE" if "disp-pos" in args: disp_pos = palette_params["disp-pos"] if "disp-neg" in args: disp_neg = palette_params["disp-neg"] if "disp-zero" in args: disp_zero = palette_params["disp-zero"] cmd = "wb_command -cifti-palette {} {} {}".format(cifti_palette_input, mode, fout) cmd += " -palette-name {}".format(palette) cmd += " -disp-zero {}".format(disp_zero) cmd += " -disp-pos {}".format(disp_pos) cmd += " -disp-neg {}".format(disp_neg) # Update command with provided parameters. NOTE these must be consistent # with the format expected by "wb_command -cifti-palette": see # https://www.humanconnectome.org/software/workbench-command/-cifti-palette if palette_params: for k, v in palette_params.items(): if k in ["disp-zero", "disp-pos", "disp-neg"]: continue if hasattr(v, '__iter__'): if len(v) != 2: raise ValueError( "palette params must be a dict with values which are " "either strings, numbers, or tuples") cmd += " -{} {} {}".format(k, v[0], v[1]) else: cmd += " -{} {}".format(k, v) # We're ready to change palette and save new file to `fout` system(cmd) # Remove file which was only used temporarily remove(cifti_palette_input)
################################ # Plot vertex-level heritability ################################ dscalar_template = nb.load('/gpfs/milgram/project/holmes/kma52/topo_herit/ref_files/Schaefer2018_400Parcels_17Networks_order.dscalar.nii') vert_num = len(dscalar_template.dataobj[0])/2 l_data_write = np.zeros(int(vert_num)) l_data_write[l_h2_df.Var5] = l_h2_df.Var1 r_data_write = np.zeros(int(vert_num)) r_data_write[r_h2_df.Var5] = r_h2_df.Var1 # combine LH/RH h2-multi values, save dscalar.nii dat_arr = np.array([list(np.concatenate([l_data_write, r_data_write]))]) sub_labels = nb.Cifti2Image(dataobj=dat_arr, header=dscalar_template.header) out_path = os.path.join(fig_dir, 'dice_vertex_heritability_vert_radius_rr.dscalar.nii') nb.save(sub_labels, out_path) out_path mat_dat = sio.loadmat(os.path.join(base_dir, 'data/HCP/HCP_S1200_1029sub_17net_parcellation.mat')) net_names = [x[0] for x in labels['network_name'][0]] net_dict = {i+1:name for i,name in enumerate(net_names)} lh_net_mode = pd.DataFrame(mat_dat['lh_labels']).mode(1) rh_net_mode = pd.DataFrame(mat_dat['rh_labels']).mode(1) r_h2_df = pd.read_csv(os.path.join(vert_dir, 'all_verts_dice_R_network_topo_h2_rr.csv')) l_h2_df = pd.read_csv(os.path.join(vert_dir, 'all_verts_dice_L_network_topo_h2_rr.csv'))
def generate_map(self): # Make the directory of probabilistic maps probabilistic_map_dir = os.path.join(self.ciftify_data_dir, '..', 'probabilistic_map') if not os.path.exists(probabilistic_map_dir): os.makedirs(probabilistic_map_dir) # Read subjects information subject_list = [] all_ciftify_folders = os.listdir(self.ciftify_data_dir) for foldername in all_ciftify_folders: if 'sub-M' in foldername: subject_list.append(foldername) subject_num = len(subject_list) # Read contrasts contrast_dict = {} for contrast in self.contrast_list: contrast_dict[contrast] = [] # Read data of every contrasts for subject in subject_list: print('Reading subject {} ...'.format(subject)) raw_subject_dir = os.path.join(self.raw_data_dir, subject) session_list = os.listdir(raw_subject_dir) for session in session_list: print('Reading session {} ...'.format(session)) results_dir = os.path.join( self.ciftify_data_dir, subject, 'MNINonLinear', 'Results', session + '_' + 'task-' + self.task, session + '_' + 'task-' + self.task + '_' + 'hp200' + '_' + 's4' + '_' + 'level2' + '.feat') for contrast_name in contrast_dict.keys(): print('Reading contrast {} ...'.format(contrast_name)) zstat_file = os.path.join( results_dir, subject + '_' + session + '_' + 'task-' + self.task + '_' + 'level2' + '_' + 'zstat' + '_' + contrast_name + '_' + 'hp200' + '_' + 's4' + '.dscalar.nii') current_data = nib.load(zstat_file).get_fdata() current_data_threshold = np.where( current_data > self.z_threshold, 1, 0) contrast_dict[contrast_name].append(current_data_threshold) # Calculate every contrast to probabilistic style data for contrast_name in contrast_dict.keys(): print('Calculating contrast {} ...'.format(contrast_name)) contrast_dict[contrast_name] = (sum( contrast_dict[contrast_name])) / subject_num # Save probabilistic maps for contrast_name in contrast_dict.keys(): print('Saving probabilistic map of {} ...'.format(contrast_name)) save_path = os.path.join(probabilistic_map_dir, contrast_name + '.dscalar.nii') image = nib.Cifti2Image(contrast_dict[contrast_name], self.header) nib.cifti2.save(image, save_path) print(' ########## Work Completed ########## ')
def save_pconn(data, pconn_dummy, output_file): img_dummy = nib.load(pconn_dummy) img_new = nib.Cifti2Image(data, header=img_dummy.header, file_map=img_dummy.file_map) img_new.to_filename(output_file)
def save_ciftifile(data, filename, template): ex_cii = nib.load(template) ex_cii.header.get_index_map(0).number_of_series_points = 1 nib.save(nib.Cifti2Image(data.reshape((1, 91282)), ex_cii.header), filename)
# iterate every run allfile = os.listdir(rootPath) for file in allfile: if 's0&roi.dtseries.nii' in file: print(file) # load func data func_img = nib.load(rootPath + '/' + file) func_data = func_img.get_fdata() func_header = func_img.header avg_all = [] shape = func_data.shape cnt = np.count_nonzero(func_data[0]) for i in range(0, shape[0]): avg = np.sum(func_data[i]) / cnt func_data[i] = np.where(func_data[i], np.ones(shape[1])*avg, 0) avg_all.append(avg) # save new func new_func_img = nib.Cifti2Image(func_data, func_header) nib.cifti2.save(new_func_img, savePath + '/' + 'AVG' + file) run_id = file[13] plt.title('ROI Average of run' + str(run_id)) plt.plot(range(0,shape[0]), avg_all, color='green') plt.xlabel('time') plt.ylabel('roi_avg') plt.show() print(file + ' finished!')