Saving slices of NIFTI image as .JPG

#1

Hi, Not sure this is the right forum to ask this question, but I’ve been trying in vain to find some example code that saves slices of a NIfTI file into JPG format. More specifically I’m trying to get the middle axial slices as JPG slices to feed into a convolutional neural network.

Thanks…

#2

This snippet of R code will do it:

library(oro.nifti); # for readNIfTI()

in.img <- readNIfTI(“c:/Users/USER/Downloads/conteMNI_transformed.nii.gz”, reorient=FALSE); # any input nifti; this is from https://www.dropbox.com/s/e61lrwn76ydwtji/conteMNI_transformed.nii.gz?dl=0

jpeg(“d:/temp/slice.jpg”); # path and name of jpeg to create

image(in.img[,29], col=gray(0:64/64), xlab="", ylab="", axes=FALSE, useRaster=TRUE); # draw slice k=29

dev.off(); # release the jpeg image file

#3

Thank you! I’ll give that a go.
Kind regards.

#4

I would be very cautious analyzing medical images that have been converted to JPG format. 3 concerns jump immediately to mind. First, JPEG only support 8-bit precision, whereas modern scanners use 16-bit ADC. A large fMRI signal may be only a fraction of this range (e.g. 1-2%), so downsampling the data is a concern. For CT scans (where intensity is calibrated), you could select a specific window center and width (brightness and contrast) to just select soft tissue. However, most image intensity is relative for most MRI sequences and homogeneity issues make it hard to select a global downsampling. A second issue with JPEG is that it is inherently lossy, with blocking artifacts and compression tricks that are intentionally designed to be hard for the human eye to spot. A third issue is that MRI scans have a lot of information that can be leveraged by retaining 3D spatial information that can be lost when only looking at 2D slices. I understand that a lot of neural networks have been tuned for JPEG, as this is a common format on the web for sharing photographs. However, I do think it is worth preserving the richness of your dataset if you want to have the best performance for machine learning.