简体   繁体   中英

How to read multiple Nifti files from the same folder with Nibabel?

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM