Your cat is not available now, please call back later
CAT'S BLOG

How to print MRI of your Brain

brain.png

Look at this nice and shiny green brain. Probably you have one too!

TL;DR

Scroll to brain-stl section for a working guide

Intro

Okay, you have an MRI scan of your head (or planning to get it), spare time and want to make something cool? I'm going to give you an idea to spend some 3D printer's time on.

View Your Data

First, you need to obtain a CD with DICOM MRI data. Often, you receive one after going through the MRI procedure, on a CD. This is a widely used MRI image format that can be read by lots of programs. If you're curious, here is a list:

  • Weasis (Flatpak, GitHub) is a powerful MRI viewing tool; includes separate views of scans, sliding through the layers, 3D model reconstruction (but no export function (or I just didn't find it)), and manual filter tweaking. You can use it to take a look at your MRI data. It's cool.
  • Slicer is a plugin-powered tool that can be used to process MRI image data semi-automatically. The SlicerSwissSkullStripper plugin can be used to semi-automatically select brain areas on slices, and the export functionality can be used to export a 3D model. Personally, I found this tool a bit overcomplicated when it comes to switching between plugins.
  • InVesalius (Flatpak) is a nice tool that does not require extra plugins. It works in 4 simple steps: import DICOMDIR, manually tweak detection thresholds (see the green image above), build and split the 3D model, and finally export an .STL file. In addition to the automatic threshold, you can manually paint brain areas if an algorithm is not enough.

Most of these programs are designed for semi-manual processing: they give you a rough model with lots of spaghetti pointing from the sides of brain and in place of the nose. The next step is to use MeshLab or Blender to manually clean the model.

ḆЭ NÕŢ AFṞẰĨḎ

of spaghetti

screenshot

Actually, this happens because there is a lot of fat and soft tissue in human body.

Prepare MRI

For simplicity, I'll be working inside the data directory.

Start by unpacking your MRI data into a directory, for example, data/MRI:

# ls MRI_2024-04-11/
100049E1     CDVIEWER.EXE  HELP     INDEX.HTM  LOG4J.XML  README.TXT  RUN.COMMAND  XTR_CONT
AUTORUN.INF  DICOMDIR      IHE_PDI  JRE        PLUGINS    RUN.CMD     RUN.SH

Now you can view it using one of the programs above, or continue making something weird.

Automatic vs Manual

If you prefer, you may spend several hours (or days) in meditation: export a rough model of your brain from one of the programs above and start sculpting in Blender or wherever you like.

Imagine spending several days smoothing your brain like

squish

If you're lazy like me, you may choose another path, and here we go.

First attempt: FreeSurfer

This chapter is dedicated to my first attempt at converting brain MRI to a 3D model. This attempt failed, so if you're looking for a working guide, scroll to the second attempt. That's why this part is unfinished.

You can try it yourself by following the detailed guide, and maybe you will succeed.

FreeSurfer or surfer.nmr.mgh.harvard.edu is free software dedicated to processing MRI data. On paper, it is really cool, as it can segment and detect different parts of the brain, split it apart, and generate a very high-quality 3D model (at the cost of time). Source code is available on GitHub.

Pros:

  • Everybody says that this tool performs magic powered by Unicorns.
  • The license is easy to obtain (free; only basic research info and an e-mail required).
  • You can use a Docker image to run it.

Cons:

  • In my case, the website surfer.nmr.mgh.harvard.edu didn't work at all (even from 3 different GEOIPs, even through nmap).
  • The license registration page does not open either.
  • I had to use Internet Archive to read the docs. But I still could not build it from source because half of the dependencies are hosted on a non-working website.
  • I couldn't make it work.

Prepare docker

Install Docker (or Podman (or whatever)).

You can use docker run commands, but I will create a docker-compose file and shell into the container.

My data is located in the data directory:

# ls .
compose.yml
data
license.txt
env.sh

# ls data
MRI

Add a compose.yml file

services:
  freesurfer:
    image: freesurfer/freesurfer:7.4.1
    container_name: freesurfer-container

    restart: always
    volumes:
      - ./data:/mnt/data

    entrypoint: ["/bin/sh", "-c", "sleep 1000000"]
    tty: true

Note: The version here is 7.4.1. Others didn't work for me and just crashed with errors.

Add data/license.txt file

Obtain a License file and add it to data/license.txt

[REDACTED]
Note

Sometimes people commit their license.txt files on github, I suggest not doing this

Add data/env.sh file that will be used to lazily set up env

To use the shell inside the container, we need to point the environmental variable to a license file.

export FS_LICENSE=/mnt/data/license.txt

Run docker

When you're ready and all files are in place, start the container with docker compose up -d. Give it some time to download 10 GB of FreeSurfer binaries, and after that you'll have a running container with the FreeSurfer runtime.

I suggest you use screen (screen -S myscreen) on Linux to start a shell and keep it running in the background. Just in case you accidentally close the terminal.

Open a shell with docker exec -t freesurfer-container bash, then run cd /mnt/data and source env.sh inside the container. Now you're ready and can move on.

recon-all

First, convert brain data to models using recon-all. Pick a patient name for yourself (anything alphabetical). Not just the patient ID from your CD, but something you come up with (for example, katze).

And start processing:

recon-all -i MRI/DICOMDIR -s katze -parallel -all


mkdir /mnt/data/subjects
touch /mnt/data/logfile

recon-all -i /mnt/data/MRI/DICOMDIR -subjid katze -all -time -log /mnt/data/logfile -nuintensitycor-3T -sd /mnt/data/subjects -parallel -openmp 8

This command should start doing something. Be prepared: it can take up to several hours to read, reconstruct and polish your brain to make it look smooth and nice. Note that this process runs best on hardware with many CPU cores and enough RAM. Personally, I use a VM in Proxmox with 8 vCPUs and 8 GB of RAM.

While waiting for brain reconstruction, you can spend time reading my other posts or playing some games in your browser.

Fail

After trying all Docker images that I found on Docker Hub, the only image that worked was 7.4.1. Worked until a Segmentation fault.

I've spent several days trying to make it work, switching between versions, restarting, yet nothing worked. At that moment, I came across another project on GitHub that uses ML models for segmentation. If you want to play with splitting your brain into functional segments and printing them, have a look at this tool.

Along with segmentation, I found a simple Python utility to convert brain to STL.

brain-stl

To use it, you need Python and (optional) a CUDA-enabled GPU. I ran everything on CPU, and it took me about 5 minutes per model.

Setting up env

If you do not like to --break-system-packages, then start by creating a venv:

python3 -m venv .venv

source .venv/bin/activate

pip install brain_stl

After it installs everything, you're ready.

Note: If something is not working (like a missing library), just install it with pip install <whatever>

You can read documentation on a GitHub page, but I'll outline key points: this tool supports both command line and Python scripts. I'll be using a Python script for simplicity and readability.

Also, you don't need to convert from DICOM to NifTi .nii because it supports both.

Most important parameters are:

  • scan_filepath: path to input data. Either a DICOM directory or .nii file.
  • output_folder: directory for output files. It produces several files along with the brain model.
  • threshold: threshold for tissue detection. 0.5 is fluid, 1.5 is gray matter, 2.5 is white matter. I've used values from 1.5 to 1.75.
  • smooth_iter: number of smoothing iterations for post-processing. I've used 10-20.

Remember to play with parameters. It is better to experiment: each scan is unique, and my parameters may not suit your case.

By default, if no input is set, it downloads open brain model and reconstructs it.

Automate

As I said, I'm lazy, and I do not want to run 100500 commands in a shell and wait, so we're gonna code a bit:

# Input MRI data path, in my case the DICOM directory
INPUT = '/data/MRI'

# Base path for output
OUTPUT_BASE = '/data/brains/output'

# Parameters to use and combine
PARAMS = [
    dict(
        threshold = 1.75,
        smooth_iter = 20,
    ),
    dict(
        threshold = 1.75,
        smooth_iter = 15,
    ),
    dict(
        threshold = 1.65,
        smooth_iter = 20,
    ),
    dict(
        threshold = 1.65,
        smooth_iter = 15,
    ),
    dict(
        threshold = 1.5,
        smooth_iter = 20,
    ),
    dict(
        threshold = 1.5,
        smooth_iter = 15,
    ),
]

# Generate unique name based on parameter values
def make_name(args):
    return '_'.join([ f'{key}-{value}' for key, value in sorted(args.items()) ])

import os
from brain_stl import run_brain_stl

for args in PARAMS:
    print()
    print('- - - - - - - -')
    print()
    print('Pass:', args)
    print()
    print('- - - - - - - -')
    print()

    output_folder = f'{ OUTPUT_BASE }/{ make_name(args) }'
    os.makedirs(output_folder, exist_ok=True)

    run_brain_stl(
        INPUT,
        output_folder=output_folder,
        **args,
    )

Save this script to data/process.py and run it using python3 process.py.

Relax and wait. It will take some time, but not 9 hours, obviously. This tool will convert MRI slices into a 3D model in .stl format, and smoothing steps will make it good enough for a small print.

meanwhile, I'll still advertise my other posts or games.

Actually, my brain has taken a selfie!

screenshot

But, we still need...

Post-processing

Why?

Just look inside and see all this debris.

screenshot

Delete Garbage

We'll start by deleting dangling meshes. Open the model in Blender and switch to Edit Mode.

screenshot

Choose Face Select mode and select any face you like. Then go to Select > Select Linked > Linked, then Select > Invert, and hit <Delete key> > Vertices. This will delete everything except the brain model itself.

screenshot

Remesh

Back to Object Mode. Go to Object > Modifiers > Add Modifier > Generate > Remesh. See how Blender eats up all memory.

screenshot

Play with parameters until you're satisfied with the model's voxel reconstruction.

In addition to Remesh, you can apply the Decimate modifier. And follow up by adding a Subdivision Surface.

These 3 modifiers should help smooth the brain, but remember: it shouldn't look like a sphere.

Internals Cleanup

Remember that messy internal space?

screnshot

You can do the following:

  • Switch to Edit Mode
  • Use edge selection mode
  • Carefully select internal spaghetti and <Delete key> > Vertices or <Delete key> > Collapse Edges & Faces. The last one will merge the cut into a single node.

Btw, an alternative way is just inserting several cubes into your brain.

screenshot

Printing

Open your favourite slicer and plan your print

It looks cursed

screenshot

Print

photo

Hold

photo

ḆЭ NÕŢ AFṞẰĨḎ

photo

Strip excessive supports

photo

Drink Fresh

photo

Last modified at 2026-01-20 23:53:26 UTC