Coding

How to Convert Nifti Files into STL Files Using Python?

Tools: Python, Nibabel, NumPy, NumPy-stl, Scikit-image

Mohammed El Amine Mokhtari
2 min readOct 30, 2022

--

Video downloaded from Pexels

The original article on my website can be found here.

Introduction

We discussed the difference between Dicom and Nifti files in this article, and we stated that they are 3D representations of the patient. The Nifti files can also be used to represent the case’s segmentation (masks, annotations)!

What are STL files?

So, for segmentation files, we can find a variety of file types, including STL (Standard Triangle Language).

Install the dependencies

NumPy, Nibabel, scikit-image, and numpy-stl are the packages we’ll need for this project. Using pip, we can install them all:

pip install numpy
pip install numpy-stl
pip install scikit-image
pip install nibabel

If you want to learn more about these libraries, you can do so by visiting their documentation:

Extract the NumPy array from the Nifti file

To convert the Nifti file to STL, we should first extract the NumPy array from the file so that we can use the numpy-stl library to do the conversion.

Preprocessing the Numpy array

We need to apply some processing after extracting the NumPy array from the Nifti file to create the 3D mesh from the NumPy array. From here, these operations are taken over from Mr. P Solver’s job.

Export the STL file

After completing the processing, you need just to save the 3D mesh as an STL file.

Captured by the author

The code can be found here.

--

--

Mohammed El Amine Mokhtari
Mohammed El Amine Mokhtari

Written by Mohammed El Amine Mokhtari

I'm a computer vision research assistant, YouTuber and online content creator. Co-founder at: https://pycad.co/

Responses (2)