Video version of this blog post

Introduction

When working in the healthcare field, there are two types of files that can be used. The first are dicom files, which are files that represent a 2D slice of a body part that you wish to study. Then there’s the 3D representation of the body, which is a collection of 2D slices built from multiple dicoms or even regular images or arrays.

In previous articles, we discussed the differences between dicom and nifti, as well as how to create nifti files from dicoms. So, in this article, we’ll go over how to generate these nifti files from a standard array.

Why do we need to do this conversion?

You may wonder why we need to perform such conversions. The answers are as follows:

Tools you need

You will need two libraries for this task: numpy and nibabel. Nibabel is a library designed specifically for nifti extensions, but the conversion array/nifti requires a numpy array as input.

To install them, you can use pip as always (or conda):

  pip install numpy
  
  pip install nibabel 
  

Methodology

There are two steps to this process that you must complete:

  converted_array = numpy.array(normal_array, dtype=numpy.float32)

I chose float 32 as the type because I needed it, but you can use any type you need.

The other parameters aren’t required right now, but there is one that you might need later: ‘header’. This parameter will take the header of your file, if you have one. Which is the metadata (patient and image information).

  nifti_file = nibabel.Nifti1Image(converted_array, affine)

With:

  affine = numpy.eye(4)

Your nifti file is now ready to use; you can use it right away or save it to use later.

Another command in the nibabel library called ‘save’ can be used to save the file.

 nibabel.save(nifti_file, path_to_save)

Here is the full script:

    import numpy as np
    import nibabel as nib

    converted_array = numpy.array(normal_array, dtype=numpy.float32) # You need to replace normal array by yours
    affine = numpy.eye(4)
    nifti_file = nibabel.Nifti1Image(converted_array, affine)

    nibabel.save(nifti_file, path_to_save) # Here you put the path + the extionsion 'nii' or 'nii.gz'

I hope you found this article useful, because we will need these conversions when we discuss data augmentation for 3D volumes in the next article.