Secrets of the brain. Analyzing MRI data with FreeSurfer and Python

Brain imaging is a revolutionary field in neuroscience that allows researchers to gain unprecedented insight into the structure and function of the human brain. One area where imaging has shown particular promise is in identifying patterns of brain activity associated with various predispositions, such as personality traits, cognitive abilities, and mental disorders. In this article, we will look at how this technology can be used to identify human predispositions, and what discoveries have been made in this area, we will see how, using MRI data, we can obtain information about the basic structures of the brain using the example of its cortex.

A bit of theory

Before we get into the details, let’s start with a quick overview.

There are several methods that can be used for brain imaging, these are magnetic resonance imaging (MRI), functional magnetic resonance imaging (fMRI), positron emission tomography (PET), and electroencephalography (EEG). MRI provides detailed images of brain structure, while fMRI, PET, and EEG are used to measure brain activity.

Now let’s look at how brain data can be used to reveal human predispositions.

One approach is to study the brain activity of people who show a certain propensity and compare it with the brain activity of those who do not. For example, researchers can compare the brain activity of people who score high on the extraversion personality trait with those who score low. By identifying differences in brain activity between the two groups, researchers can gain insight into the neural mechanisms that underlie this type of addiction.

Another approach is to study the brains of people at high risk for a particular addiction, such as those with a family history of mental disorders. By comparing the brain activity of these people with that of a control group, researchers can determine patterns of brain activity associated with this type of inclination. This approach can also be used to study the influence of external factors such as therapy or drugs on the brain activity of people in this group.

Some research results

One of the most exciting discoveries in the field of brain imaging has been the identification of areas of the brain associated with certain cognitive functions such as attention, memory, and decision making. For example, researchers have identified areas of the brain that are activated when people are asked to make decisions that involve risk and uncertainty. These areas have been called the “decision-making network” and are thought to play a key role in our ability to make complex decisions.

Another exciting discovery was the identification of areas of the brain associated with specific mental disorders. For example, researchers have found that people with depression tend to have decreased activity in the prefrontal cortex, an area of ​​the brain that is involved in regulating emotions and making decisions. Similarly, people with anxiety disorders tend to have increased activity in the amygdala, an area of ​​the brain that is involved in processing fear and anxiety.

Visualization has provided researchers with powerful tools to understand human predispositions. By studying the brains of people who exhibit a particular tendency or are at high risk of exhibiting it, researchers can identify patterns in brain activity associated with that factor. These ideas have already led to a better understanding of the neural mechanisms underlying various cognitive functions and mental disorders. As brain imaging technology continues to improve, we can expect even more exciting discoveries in this area.

Let’s move on to practice, below we will learn how we can work with MRI data. The first example will show how to improve visualization, and the second how to extract data about brain regions.

MRI Image Enhancement

We often need to enhance the MRI data for clearer visualization, below we will see some useful examples.

  1. image denoising. MRI often contains a lot of noise, which reduces image quality. The following code uses the library NiftyNet to remove it :

import numpy as np
import nibabel as nib
from niftynet.engine.application_factory import get_application
from import ImageReader

# Load MRI data
reader = ImageReader().initialise({'image': 'path/to/mri.nii.gz'})
data = reader(idx=0)['image_data']

# Apply denoising
app = get_application('denoiser')
app.net_param.batch_size = 1
app.net_param.validation_every_n = np.inf
app.action(data, 'infer')
denoised_data = app.output['denoised_data'][0]

# Save denoised data, reader.output_path), 'path/to/denoised_mri.nii.gz')
  1. Bias Field Correction. Sometimes we have inhomogeneity in the intensity of MRI scans, which can reduce the quality of imaging. The following example uses the library SimpleITK for correction:

import SimpleITK as sitk

# Load MRI data
mri = sitk.ReadImage('path/to/mri.nii.gz')

# Apply bias field correction
corrector = sitk.N4BiasFieldCorrectionImageFilter()
corrected_mri = corrector.Execute(mri)

# Save corrected data
sitk.WriteImage(corrected_mri, 'path/to/corrected_mri.nii.gz')
  1. image registration. Can be used to align multiple MRI scans, which in turn also improves quality. The library will also help us here. SimpleITK:

import SimpleITK as sitk

# Load MRI data
fixed_mri = sitk.ReadImage('path/to/fixed_mri.nii.gz')
moving_mri = sitk.ReadImage('path/to/moving_mri.nii.gz')

# Perform image registration
registration = sitk.ImageRegistrationMethod()
registration.SetOptimizerAsRegularStepGradientDescent(learningRate=1.0, minStep=0.001, numberOfIterations=200)

final_transform = registration.Execute(fixed_mri, moving_mri)

# Apply final transform to moving MRI data
registered_mri = sitk.Resample(moving_mri, fixed_mri, final_transform, sitk.sitkLinear, 0.0)

# Save registered MRI data
sitk.WriteImage(registered_mri, 'path/to/registered_mri.nii.gz')

It should be noted that the parameters used in these examples may need to be adjusted depending on the specific MRI data and the desired result.

Extracting data about brain regions

Now let’s try to work with MRI using such a wonderful tool as free surfer.

  1. Before we can use FreeSurfer, we need to install it. Instruction how to do it. We need to accept the terms of the license and place it in HOME FreeSurfer directory.

  1. With FreeSurfer installed, we can use it for data preprocessing. Here is an example of processing T1-weighted MRI scan:

import os
from nipype.interfaces.freesurfer import ReconAll

subject_id = 'sub-01'

reconall = ReconAll(subject_id=subject_id, directive="all", T1_files=t1w_file, subjects_dir=output_dir)

Option directive="all" tells FreeSurfer to perform all preprocessing steps, and the option T1_files=t1w_file points the way to Т1-weighted MRI scan. Option subject_dir=output_dir specifies where to put the result.

  1. After pre-processing, we can proceed to the analysis. Here is an example of how to extract cortical thickness data:

import os
import numpy as np
from nibabel import load
from nipype.interfaces.freesurfer import SurfaceMetrics

subject_id = 'sub-01'
hemi = 'lh'

# Load the cortical surface
surf_file = os.path.join(output_dir, subject_id, 'surf', f'{hemi}.pial')
surf = load(surf_file)

# Extract cortical thickness data
surface_metrics = SurfaceMetrics(subjects_dir=output_dir)
surface_metrics.inputs.hemi = hemi
surface_metrics.inputs.subject_id = subject_id
thickness_data = np.array(

Here we load the cortical surface for the left hemisphere sub-01 and extract the bark thickness data with SurfaceMetrics. Option hemi='lh' indicates the left hemisphere, and the option curv_measure="thickness" indicates that we want to extract thickness data. The result is stored in a variable thickness_data.

Where to look for data for your own research

There are several sources where you can find the data you need for research and experimentation:

  • OpenNeuro is a free and open platform for the exchange of MRI data and other data.

  • Human Connectome Project is a large-scale project that aims to map the human brain using various imaging techniques.

  • Brain/MINDS – a project that focuses on mapping the human brain with an understanding of the functions of its regions.

  • The Cancer Imaging Archive – is a repository of medical images, including MRI data.


These are just a few examples of how we can use Python and FreeSurfer to analyze MRI data. FreeSurfer contains many other commands and options, so be sure to check out the documentation for more information and do your own research.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *