Skip to content

Module 4 MRI QA and 3D Print Prep

Jared Tanner edited this page Feb 26, 2026 · 38 revisions

View FreeSurfer Output

If you do not know how to view the FreeSurfer output on HiPerGator, watch this video for an extended walk-through (I recommend watching at 1.5 speed). This was recorded in a previous semester so update paths accordingly! Also, logging in to HiPerGator and interacting with files and applications has changed somewhat, but this should be close enough to figure out.

https://youtu.be/kEZKqIcwIKE

FreeSurfer Quality Assessment

There are many ways to assess the quality of FreeSurfer outputs. These would only be a small part of that assessment. We will not cover editing and reprocessing files, although that might need to be done in some instances. There are fairly standardized methods for doing that but we won't cover them.

What we will do for quality assessment is use two semi-automated tools to provide a way to view the images and outputs. These will also provide some metrics of quality that can be considered in analyses.

Doing the first tutorial requires you to have completed the two recon-all commands. Some students had issues with running out of memory. Rather than keeping trying over and over, I've made the two processed brains available to students who need these. Copy (don't move) the two sub- directories into your directory (probably best in your ADNI_bids [or whatever you called it]/derivatives/freesurfer directory).

The processed brains are in /blue/psy4930/share/data/Module4

Again, only copy those if your processing for Module 3 failed and I already gave you credit for it.

  1. This tutorial will cover the two quality checking methods: https://youtu.be/Ws_hHB8We4A?si=f8ZXF8q3-asGkfpv

Key commands are as follows (this assumes you are in your freesurfer output directory where the recon-all command saved the processed images). This will need to be changed to match what you called your subjects (some of you have done 011_S_6303 or sub-6303 or something like that -- pay attention to names and paths). Again, remember that where files are in the video might not match where yours are. Update paths to match where your data are.

Do not run this on the login terminal.

If you want to copy and paste commands or text to and from HiPerGator Desktop, watch this video for a guide: https://youtu.be/ySCf4VEERMk. I also go through that briefly in the video linked previously.

#This mkdir command assumes you are where you want to make this directory. I was in my freesurfer output directory so you'll want to run something like this first (update as appropriate to match where your freesurfer output directory is):

cd /blue/psy4930/share/students/jjtanner/Module3/ADNI_bids/derivatives/freesurfer

mkdir fsqc_out

apptainer run -B $PWD:/in -B $PWD/fsqc_out:/out /blue/psy4930/share/data/neurotools/fsqc.sif --subjects_dir /in --subjects sub-6303 sub-6367 --output_dir /out --skullstrip-html --surfaces-html --screenshots-html --fornix-html

#In the previous command $PWD is a variable that prints (calls) your current directory. Only use this if you are in the directory where the data are. Otherwise put in the full path (usually safer). Something like: apptainer run -B /blue/psy4930/share/students/jjtanner/Module3/ADNI_bids/derivatives/freesurfer:/in

#Pay attention to spaces in the apptainer command. There are places where there are no spaces. Also, pay attention to the dashes. Some of them are single and some are double.

Important: If you receive an error like this when trying to run the fsqc.sif container, you either have an incomplete FreeSurfer processing or your lh.pial and rh.pial files are named something different.

[WARNING: warnings.py:  109]: /app/fsqc/fsqc/fsqcMain.py:1203: UserWarning: Could not find /in/sub-6303/surf/lh.pial for subject sub-6303
  warnings.warn(

In that case, rename the 4 files. In my case (update paths as needed), it was like this:

cd /blue/psy4930/share/students/jjtanner/Module3/ADNI_bids/derivatives/freesurfer/sub-6303/surf/
mv lh.pial.T1 lh.pial
mv rh.pial.T1 rh.pial
cd /blue/psy4930/share/students/jjtanner/Module3/ADNI_bids/derivatives/freesurfer/sub-6367/surf/
mv lh.pial.T1 lh.pial
mv rh.pial.T1 rh.pial

Assessing Structural MRI Image Quality with CAT12

If you follow along with the video https://youtu.be/Ws_hHB8We4A?si=f8ZXF8q3-asGkfpv , update paths accordingly. Also, do Step 1 below first.

This tutorial covers how to assess T1-weighted image quality using the CAT12 toolbox. This process runs on MATLAB using SPM12 (Statistical Parametric Mapping) and should be performed on NIfTI files that have been converted from DICOMs. You can run this pipeline either in parallel with FreeSurfer or prior to it, using the output to decide if the data quality is sufficient for further processing.

Step 1: File Preparation in HiPerGator

Set up your directory structure and copy your NIfTI files to be processed.

  1. Navigate to your user directory: /blue/psy4930/$USER or /blue/psy4930/share/students/$USER, and go into your BIDS folder.
  2. Create a new directory named CAT12 inside your derivatives folder (e.g., derivatives/CAT12). This will serve as both your input and output directory.
  3. Locate the original T1 NIfTI files for the participants you want to process.
  4. Copy (do not move) these NIfTI files into the newly created CAT12 folder. You can do this through the file explorer GUI or using the cp command in the terminal. Note: You do not need the associated JSON files for this step.

Step 2: Launching MATLAB

CAT12 requires significant computational resources, so we will request burst access for this job.

  1. Return to the HiPerGator OnDemand dashboard.
  2. Go to Interactive Apps and select MATLAB.
  3. Configure your session with the following settings:
    • MATLAB Version: R2025b
    • CPU Cores: 6
    • RAM: 24 GB
    • Account: Class account
    • QoS / Burst Access: Use the -b flag (Burst access prevents using up the dedicated class cores)
    • Time: 8 hours
    • Partition: Default
  4. Click Launch and wait for the resources to become available (this may take a few minutes due to burst access). Once ready, click to launch the MATLAB interface. If using 2025b, it takes up to a few minutes to launch and be fully ready to interact with. Be patient during this time. Once the "Initializing" is no longer showing up in the lower left of the Matlab window, you are ready to proceed.

Step 3: Setting Up SPM12 and CAT12 Paths

To use CAT12, MATLAB needs to know where the SPM12 software is located.

  1. Once MATLAB is open, click Set Path in the top menu, then click Add Folder.
  2. Navigate to the root directory /, then follow the path to: /blue/psy4930/share/data/neurotools/. If you cannot see this location, click on the Applications menu in the top left corner of the Matlab window, click on Xfce Terminal, type cd /blue/psy4930 and then press enter/return. In the MATLAB Set Path window, try to navigate again to /blue/psy4930/share/data/neurotools/
  3. Select the spm12 folder to add it to your path.
  4. If using version 2025b, check the box to Save path for future sessions. If MATLAB prompts you with a warning asking if you want to save in a new location, click OK and then Save into your home directory ~/ or into /blue/psy4930/$USER. Close the path window.

If you receive an error, uncheck that box, and just click Apply and then OK. Close the path window. You will be able to use SPM but will likely need to add the path to it again if you start a new MATLAB session. If you requested the 8 hours suggested above, this step will complete before that time limit.

Step 3 Alternative: Errors with SPM

If you type spm and there is an error opening the software, go back to Step 3 and make sure you added the spm12 directory to the Matlab path and saved it. If everything looks good there and you still cannot open SPM12, try this instead.

Copy the SPM12 and CAT12 software from the shared class drive into your own user directory.

  1. Log into the HiPerGator OnDemand service via your web browser.

  2. Open a Terminal session.

  3. Copy and paste the following commands into your terminal, pressing Enter after each line. This will create a neurotools folder in your directory, copy the zipped software files, unzip them, and move CAT12 into the SPM12 toolbox folder:

    mkdir -p /blue/psy4930/$USER/neurotools
    cd /blue/psy4930/$USER/neurotools
    
    cp /blue/psy4930/share/data/neurotools/spm12.zip   .
    cp /blue/psy4930/share/data/neurotools/cat12_latest.zip .
    
    unzip -q spm12.zip   -d spm12
    unzip -q cat12_latest.zip -d cat12
    
    mv /blue/psy4930/$USER/neurotools/cat12 /blue/psy4930/$USER/neurotools/spm12/toolbox/cat12
  4. Now go back to Step 3 above and add this to the Matlab path if that's where you copied and extracted the files: /blue/psy4930/{YOUR_GATORLINK}/neurotools/spm12

  5. Remove the /blue/psy4930/share/data/neurotools/spm12 path.

  6. If using MATLAB 2025b, see 4. under Step 3. Otherwise, if using an older version of MATLAB, click Save. If MATLAB prompts you with a warning asking if you want to save in a new location, click OK and then Save into your home directory ~/ or into /blue/psy4930/$USER. Close the path window.

  7. Proceed with Steps 4 and 5.

Step 4: Running the CAT12 Pipeline

  1. In the MATLAB Command Window, type spm (all lowercase) and press Enter.
  2. When the SPM menu appears, click on PET & VBM. SPM12 will initialize in the background.
  3. In the new SPM12 window, click the Toolbox dropdown menu and select cat12.
  4. Click on Segment. The Batch Editor window will open.
  5. In the Batch Editor, you will see a setting showing the job will split into separate processes based on your requested cores (e.g., 6).
  6. Under the Volumes section, double-click to specify your files.
  7. Navigate to your /blue/psy4930/share/students/$USER/.../derivatives/CAT12 directory. This could instead be /blue/psy4930/$USER/.../derivatives/CAT12. Make sure you are where you have the data!
  8. Select the T1 NIfTI files you copied earlier (Shift-click to select multiple) and click Done.
  9. (Optional but recommended) Scroll down to the Atlas settings and change Atlas: Hammers - Free Academic Use to Yes.
  10. Leave all other settings as default.
  11. Click the green Play button (Run Batch) at the top of the window to start processing.

Step 5: Monitoring and Reviewing Results

  1. The processing will begin, utilizing the cores you requested (e.g., 3 cores per participant if running 2 brains).
  2. This process takes approximately 50 to 60 minutes per brain. You can safely close your browser tab, leave the job running, and return later to check the progress via the MATLAB output logs.
  3. Once the job finishes successfully, close MATLAB. Closing MATLAB will automatically kill the active HiPerGator session and free up resources.
  4. To view your visual reports, start a new HiPerGator Desktop session (e.g., 6GB RAM, 2 hours, class account).
  5. Navigate back to your derivatives/CAT12 folder. You will see four new folders generated by the pipeline: mri, report, label, and surf.
  6. Open the report folder. You can open the generated PDF or drag the JPEG file directly into a web browser like Chrome to view it.

Interpreting the CAT12 Report

The generated visual report contains several important metrics that can be used as covariates in your research analyses:

  • Image Quality Rating (IQR): A weighted average score of the scan's overall quality.
  • Euler Number: Another helpful metric for assessing image quality.
  • Tissue Volumes: The relative percentages and volumes of Gray Matter, White Matter, and Cerebrospinal Fluid (CSF) compared to total head size. High CSF percentages (e.g., 34% vs 23%) and enlarged ventricles can indicate atrophy, older age, or conditions like dementia.
  • Cortical Thickness: Measurements of the overall thickness of the cortex (e.g., 2.34mm vs 2.16mm) alongside visual thickness maps.

For the homework, submit the PDF or JPEG of the image quality report

Preparing for 3D Printing

This is more for fun, but will give you additional experience with containers and scripting (if you choose to script).

Watch this video and follow along. I show both running the processing "live" and in a script (script is the last part of the video). You can do either method or both, for the experience.

If you use the script, it's in /blue/psy4930/share/data/Module4

Please copy (not move) it from there into somewhere in your own directory. Then edit it to match your paths and files. Make sure to change the email address in it too!

https://youtu.be/ROm5F_075ac

At the end of this you will have 1 or 2 .stl files that are 3D models of human brains. These could be imported into 3D modeling software, or, with some additional minor preparation, are ready for 3D printing.

Here is the script's contents with commands used in the video. If you put these into terminal to run this live (only do that in an interactive session or in the Terminal in a HiPerGator Desktop), it's best to have each command as one line (example after this next section). Remember that paths listed here will need to be updated to match where your data are.

#!/bin/bash
#SBATCH --job-name=3dprintprep-student
#SBATCH --mail-type=END,FAIL
#SBATCH --mail-user=USER@ufl.edu          # EDIT: Change to your email
#SBATCH --ntasks=1
#SBATCH --mem=8gb 
#SBATCH --time=00:40:00
#SBATCH --account=psy4930
#SBATCH --qos=psy4930
#SBATCH --output=3dprintprep_%j.log

pwd; hostname; date

# ====================================================================================================================
# STUDENT CONFIGURATION AREA. YOU SHOULD ONLY NEED TO CHANGE INFO HERE AND YOUR EMAIL ADDRESS ABOVE.
# ====================================================================================================================
# 1. Enter your GatorLink username
USERNAME="your_username" 

# 2. List the subjects you want to process (separated by space). For the homework you shouldn't need to change this.
SUBJECTS="sub-6367 sub-6303"

# 3. Verify these paths match your module structure
BASE_DIR="/blue/psy4930/share/students/${USERNAME}/Module3/ADNI_bids/derivatives/freesurfer"
# ====================================================================================================================

OUT_DIR="${BASE_DIR}/3dprint"
FS_LICENSE_PATH="/apps/freesurfer/license/license.txt"

# Create output directory and enter base directory
mkdir -p "$OUT_DIR"
cd "$BASE_DIR" || { echo "Error: Could not find directory $BASE_DIR"; exit 1; }

# Load FreeSurfer module for the host environment
module load freesurfer/7.4.1

echo "Step 1: Running Surface QC and Shape Preparation..."

# Run the preparation container
# -B /apps is required for the container to see the license file
apptainer run \
--env FREESURFER_HOME=/opt/freesurfer \
--env FS_LICENSE=${FS_LICENSE_PATH} \
--env PATH=/opt/freesurfer/bin:$PATH \
-B "$PWD":/in \
-B "$OUT_DIR":/out \
-B /apps \
-B "$FREESURFER_HOME":/opt/freesurfer \
/blue/psy4930/share/data/neurotools/fsqc.sif \
--subjects_dir /in \
--subjects $SUBJECTS \
--output_dir /out \
--shape

echo "Step 2: Converting processed surfaces to STL files..."

# Convert results to STL
if [ -d "${OUT_DIR}/brainprint" ]; then
    for SUBJ in $SUBJECTS; do
        echo "Converting ${SUBJ} to STL..."
        
        apptainer run \
        -B "${OUT_DIR}/brainprint/${SUBJ}/surfaces/":/in \
        -B "${OUT_DIR}":/out \
        /blue/psy4930/share/data/neurotools/3dprintprep.sif \
        /in \
        /out/${SUBJ}.stl
    done
    
    # Ensure others in the group can access the output files
    chmod -R 775 "${OUT_DIR}"
    echo "Processing complete. Check ${OUT_DIR} for your .stl files."
else
    echo "ERROR: ${OUT_DIR}/brainprint not found. Preparation likely failed."
    exit 1
fi

date

Here is an example of the apptainer run commands as a single line. It looks like it's multiple lines but that's just because of text wrapping with the constraints of the text box here

#Run fsqc to create the brain "shape" files
apptainer run --env FREESURFER_HOME=/opt/freesurfer --env PATH=/opt/freesurfer/bin:$PATH -B $PWD:/in -B $PWD/3dprint/:/out -B $FREESURFER_HOME:/opt/freesurfer /blue/psy4930/share/data/neurotools/fsqc.sif --subjects_dir /in --subjects sub-6367 sub-6303 --output_dir /out --shape

#Convert those "shape" files to stl, combine them, and perform smoothing of the surface.

apptainer run -B /blue/psy4930/share/students/jjtanner/Module3/ADNI_bids/derivatives/freesurfer/brainprint/sub-6367/surfaces/:/in -B /blue/psy4930/share/students/jjtanner/Module3/ADNI_bids/derivatives/freesurfer/3dprint:/out /blue/psy4930/share/data/neurotools/3dprintprep.sif /in /out/sub-6367.stl

apptainer run -B /blue/psy4930/share/students/jjtanner/Module3/ADNI_bids/derivatives/freesurfer/brainprint/sub-6303/surfaces/:/in -B /blue/psy4930/share/students/jjtanner/Module3/ADNI_bids/derivatives/freesurfer/3dprint:/out /blue/psy4930/share/data/neurotools/3dprintprep.sif /in /out/sub-6303.stl

What you submit

The goal will be to use two semi-automated software packages to run quality assessment on T1 NIfTI files and on FreeSurfer processed images.

What you submit

  1. The fsqc-results.html and fsqc-results.csv files in the fsqc output directory you created.
  2. The two .jpg or .pdf reports from the CAT12 processing (this processing is run on the original T1 NIfTI images and not any FreeSurfer-processed ones). These should be in your CAT12 output directory you created within the report subdirectory.
  3. You only need to do the 3D printing preparation on one brain. If you ran a script, submit the .log file and/or a screenshot of the open .stl file (in Paraview on HiPerGator or, you can download the file and open in Preview on a Mac or 3D Viewer or similar on Windows).

Clone this wiki locally