Hello Everyone,
I’m trying to extract time series from preprocessed neuroimages, the following script is the python code I use to do as said, the input directory addresses the preproc neuroimages, I use Schaefer atlas for ROI definition and parcellation, and at last save the extracted time series into a CSV file in the output directory I’ve given.
I needed an elite to confirm If this script is valid.
Thanks and Regards.
Saeed.
Code:
import os
import nilearn.image as nimg
import pandas as pd
import numpy as np
import glob
from nilearn import datasets
from nilearn.input_data import NiftiLabelsMasker
data_dir = 'D:/Project_001/Data'
output_dir = 'D:/Project_001/TimeSeries/'
os.makedirs(output_dir, exist_ok=True)
fmri_files = glob.glob(os.path.join(data_dir, '*.nii.gz'))
schaefer_atlas = datasets.fetch_atlas_schaefer_2018(n_rois=400, yeo_networks=17, resolution_mm=2)
atlas_img = schaefer_atlas.maps
atlas_labels = schaefer_atlas.labels
masker = NiftiLabelsMasker(labels_img=atlas_img, standardize=True, detrend=True, low_pass=0.08, high_pass=0.009, t_r=2)
for fmri_file in fmri_files:
subject_id = os.path.basename(fmri_file).split('.')[0]
fmri_img = nimg.load_img(fmri_file)
time_series = masker.fit_transform(fmri_img)
time_series_output_path = os.path.join(output_dir, f'time_series_{subject_id}.csv')
df_time_series = pd.DataFrame(time_series, columns=atlas_labels)
df_time_series.to_csv(time_series_output_path, index=False)
print(f"Extracted time series for Subject {subject_id} saved to {time_series_output_path}")