0

I have always work with images with extensions .png, .jpg, .jpeg Now, I have seen medical images with extension .nii.gz

I'm using python and I have read it with the following code:

path = "./Task01_BrainTumour/imagesTr"
path_list = glob.glob(path+'/*.gz') #list with all paths of image.nii.gz
    
img = nib.load(path_list[0]).get_data() #load a single image

Now the image is an array of float32 and it has the following shape (240, 240, 155, 4). I have read online that (240, 240, 155, 4) indicates that the image has size (240,240), 155 indicates the depth of the image object, namely there are 155 layers in every image object. However, this information related to the layer/depth is not clear to me, what does it mean that an image has some layers? Finally, 4 indicates the channel of the image.

I would like to convert these images in the classical format (240,240,3) for rgb or (240,240) in grayscale. I don't know if it is possible to do that.

Azzurra
  • 51
  • 6
  • While i got no idea what `nii` is, the `.gz` suffix suggests gzip compressed file. You may want `gunzip` it first – Marcin Orlowski Aug 07 '21 at 09:39
  • You've not told us where you have been to, but from http://justsolve.archiveteam.org/wiki/NII points to https://nifti.nimh.nih.gov for all the gory details. That first page, also has links to C and python code. – Bib Aug 07 '21 at 10:03
  • Are you able to open the file in some medical image viewer? If so, at least you will have a better idea on the 155 and 4. I guess 155 is the number of frames or slices, it could be a short video clip, or it could be a 3D volume (CT or MRI) – Guang Aug 17 '21 at 23:13

1 Answers1

0

You're halfway there.

It looks like you're using the Brain Tumours data from the Medical Segmentation Decathlon, and NiBabel to read the images. You can install e.g. scikit-image to save the JPGs.

from pathlib import Path
import numpy as np
import nibabel as nib
from skimage import io


def to_uint8(data):
    data -= data.min()
    data /= data.max()
    data *= 255
    return data.astype(np.uint8)


def nii_to_jpgs(input_path, output_dir, rgb=False):
    output_dir = Path(output_dir)
    data = nib.load(input_path).get_fdata()
    *_, num_slices, num_channels = data.shape
    for channel in range(num_channels):
        volume = data[..., channel]
        volume = to_uint8(volume)
        channel_dir = output_dir / f'channel_{channel}'
        channel_dir.mkdir(exist_ok=True, parents=True)
        for slice in range(num_slices):
            slice_data = volume[..., slice]
            if rgb:
                slice_data = np.stack(3 * [slice_data], axis=2)
            output_path = channel_dir / f'channel_{channel}_slice_{slice}.jpg'
            io.imsave(output_path, slice_data)
fepegar
  • 595
  • 5
  • 15