简体   繁体   中英

Load 3D Niftii images and save all slices for axial, coronal, saggital?

I have some 3D Niftii datasets of brain MRI scans (FLAIR, T1, T2,..). The FLAIR scans for example are 144x512x512 with Voxel Size of 1.1, 0.5, 0.5 and I want to have 2D-slices from axial, coronal and sagittal view, which I use as input for my CNN.

What I want to do: Read in.nii files with nibabel, save them as Numpy array and store the slices from axial, coronal and sagittal as 2D-PNGs.

What I tried:

-Use med2image python library

-wrote own python script with nibabel, Numpy and image

PROBLEM: The axial and coronal pictures are somehow stretched in one direction. Sagittal works out like it should.

I tried to debug the python script and used Matplotlib to show the array, that I get, after

image = nibabel.load(inputfile)
image_array=image.get_fdata()

by using for example:

plt.imshow(image_array[:,:, 250])
plt.show()

and found out, the data is already stretched there.

I could figure out to get the desired output with

header = image.header
sX=header['pixdim'][1]
sY=header['pixdim'][2]
sZ=header['pixdim'][3]
plt.imshow(image_array[:,:, 250],aspect=sX/sZ)

But how can I apply something like "aspect", when saving my image? Or is there a possibility to already load the.nii file with parameters like that, to have data, that I can work with?

It looks like, the pixel dimensions are not taken care of, when nibabel loads the.nii image. But unfortunately there's no way for me to solve this problem..

I found out, it doesn't make a difference for training my ML Model, if the pictures are stretched, or not, since I also do this in Data augmentation. Opening the nifty volumes in Slicer or MRICroGL showed the volumes, as expected, since these programs also take the Header into account. And also the predictions were perfectly fine (even though, the pictures were "stretched", when saved slice-wise somehow)

Still, it annoyed me, to look at stretched pictures and I just implemented some resizing with cv2 :

def saveSlice(img, fname, path):
    img=numpy.uint8(img*255)
    fout=os.path.join(path, f'{fname}.png')
    img = cv2.resize(img, dsize=(IMAGE_WIDTH, IMAGE_HEIGTH), interpolation=cv2.INTER_LINEAR)
    cv2.imwrite(fout, img)
    print(f'[+] Slice saved: {fout}', end='\r')

The results are really good and it works pretty well for me.

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