Skip to content

Task 1: explore fMRI data

elhava edited this page Jun 12, 2023 · 5 revisions

Exploring each fMRI data

Load the fMRI data from the func folder in each participant. The data has been spatially normalized to the MNI152 space. So brain images from different participants were spatially aligned.

  • Examine the size of the data, which is a 4D data set (3D space + 1D time).
  • Explore an instantaneous brain volume to identify some structures
  • Examine the time series of some image voxels
  • Calculate the the time domain signal-to-noise (tSNR) map, where each image voxel has a value of the ratio of the mean of the time series over the standard deviation of the time series of that image voxel.

Some steps to load and investigate fMRI data

One of the most useful libraries for working with fMRI data is "Nilearn". Install the library as follow:

!pip install nilearn
#Load required libraries

import os
import nibabel as nb
import matplotlib.pyplot as plt
from nilearn.plotting import plot_anat

#Load fMRI data using Nibabel Library
data_path = 'path to main images folder'
img_func = nb.load(os.path.join(data_path, 'name of one .nii.gz fmri image'))
print(img_func)

#Plot one slice of a fMRI image
plot_anat(img_func.slicer[..., 0], dim='auto', draw_cross=False, annotate=False,
          cmap='magma', vmax=1250, cut_coords=[33, -20, 20], colorbar=True)

#Plot time series
plt.plot(img_func.get_fdata()[19, 16, 17, :])

#Detrend the time series to remove noises

import numpy as np
from scipy.signal import detrend
from scipy.stats import zscore

#Detrend and zscore the data
data = img_func.get_fdata()
data = detrend(data)
data = np.nan_to_num(zscore(data, axis=0))

#Plot the cleaned signal
plt.plot(data[19, 16, 17, :]);

#Get familiar with MNI 152 template
from nilearn import datasets
from nilearn import plotting

MNI152 = datasets.MNI152_FILE_PATH
plotting.plot_img(MNI152)
print(nb.load(MNI152))

# Resample ROI template to functional image resolution
from nilearn.image import resample_to_img
from nilearn.datasets import load_mni152_template

template = load_mni152_template(resolution=2)

img_resampled = resample_to_img(img_func, template)


#Resample image to MNI 152 template
from nilearn.image import load_img

tmap_img = load_img(img_func)

original_shape = tmap_img.shape
original_affine = tmap_img.affine

resampled_shape = img_resampled.shape
resampled_affine = img_resampled.affine

template_img = load_img(template)
template_shape = template_img.shape
template_affine = template_img.affine
print(
    f"""Shape comparison:
- Original t-map image shape : {original_shape}
- Resampled t-map image shape: {resampled_shape}
- Template image shape       : {template_shape}
"""
)

print(
    f"""Affine comparison:
- Original t-map image affine :
 {original_affine}
- Resampled t-map image affine:
 {resampled_affine}
- Template image affine       :
 {template_affine}
"""
)

Clone this wiki locally