0

I did see a couple of tuts related to Nibabel, that work fine when you are reading only one nii image, but I need to read 167 files from the same folder, and I don't understand how to do it. I tried using glob as we use it for OpenCV, but it doesn't work similarly with Nibabel.

data = glob.glob('path to my data' + '*.nii.gz')
print(len(data))
print(data)
data = np.asarray(data)
print(data)
John
  • 47
  • 5
  • "*I tried using glob*", please provide a code to explain what have you done and how you did it [MWE](https://stackoverflow.com/help/minimal-reproducible-example). – Bilal May 14 '22 at 18:52
  • Please also include the error or unexpected behavior from what you tried to do – pcamach2 May 14 '22 at 19:28
  • I have added code to the description of this question. In both the cases, for a list and the numpy array it outputs sort of a list that contains the locations of all the 167 nifti files on my device. However, if I use the same code with the exact path of an individual file, it works pefecyly as it should ( for individual files I won't be using glob) I want to get a numpy array pr that contains actual pictures, and not their locations. – John May 15 '22 at 10:09
  • 1
    @John the output of `glob` in your case is a list of the file names, to read them, loop the list, join the path with each single image name, and read your images one by one. – Bilal May 19 '22 at 22:09

1 Answers1

0

As one of the comments above mentions, the data you describe only contains the image filenames not their pixels.

Once you have a list of filenames (or some containers where each filename string is an element) data you can do this:

import numpy as np;
import nibabel as nb;

if "imdata" not in locals():    

    for i in range ( len ( data ) ):

        imname = data [ i ];

        if "imdata" not in locals():
            imdata = nb.load ( imname ).get_fdata().flatten();
            imlen  = len ( imdata );
            imdata = imdata.reshape ( 1, imlen );
        else:
            imdata = np.append ( imdata, nb.load ( imname ).get_fdata().flatten().reshape ( 1, imlen ), axis=0 );

This will work if the images are the same size -- you will get a matrix of #images x #pixelsperimage. You can also do this in 3D or 4D of course, depending on what you need to do with the image data.

The use of locals() is a bit much, for me it was handy when I wrote this for not having to re-load images inside the same session.

alle_meije
  • 2,424
  • 1
  • 19
  • 40