[Neuroimaging] Looping through 3D NIFTI Image: Help

Christopher Markiewicz markiewicz at stanford.edu
Fri Jan 4 12:29:26 EST 2019


Hi Arnav,


First, welcome! Just so you know, Neurostars (https://neurostars.org) is going to be a better place than StackOverflow to ask neuroscience/neuroinformatics questions. This list is also a good place, but I suspect Neurostars gets a wider audience.


Anyway, I'm interpreting your question as asking how to find the number of non-zero voxels in an image, multiplied by the voxel volume.


I would do it as follows:


-----


import numpy as np

import nibabel as nb

path = '...'
img = nb.load(path)

data = img.get_fdata(dtype=np.float32)

# Use a test that accounts for floating point imprecision; you may want a tighter threshold
non_zero_voxels = np.abs(data) > 1e-5


# NIfTI allows for non-mm spatial units

xyz_units = img.header.get_xyzt_units()[0]

factor = 1

if xyz_units == 'meter':

    factor = int(1e9)

elif xyz_units == 'micron':

    factor = 1e-9

# If missing, assume mm


# Voxel volume in mm^3

voxel_vol = np.prod(img.header.get_zooms()[:3]) * factor

non_zero_volume = non_zero_voxels.sum() * voxel_vol


-----


As a sanity check, human brains are generally around 1.5L, so if you're not seeing something on the order of 1-2 million mm^3, you might want to check on your data. If the numbers are off by more than a factor of 2 or so, you might have bad headers or your data might not be masked to 0 outside the brain.


For more information on working with nibabel images, I would highly recommend the documentation: http://nipy.org/nibabel/nibabel_images.html


Chris

________________________________
From: Neuroimaging <neuroimaging-bounces+markiewicz=stanford.edu at python.org> on behalf of Arnav Lohe <arnavlohe15 at gmail.com>
Sent: Friday, January 4, 2019 11:56:03 AM
To: neuroimaging at python.org
Subject: [Neuroimaging] Looping through 3D NIFTI Image: Help

Dear Neuroimaging List Members,

My name is Arnav Lohe, and I am a junior at Rutgers University working on a neuroimaging project. I want to write an original piece of code to calculate the total tissue volume in a (.nii) MRI image, and to do this I need to loop through the multidimensional array. The loop is what I do not know how to do. I tried triple indexing, I tried converting the .nii image into a numpy array, and got nowhere with my approaches. Does someone know how to loop through the individual voxels and extract the numerical information inside each one?

https://stackoverflow.com/questions/54031899/how-can-i-loop-through-3d-nifti-image-in-python

I have also posted this to StackOverflow, all additional relevant details should be there.

Sincerely,
Thanking you,
Arnav Lohe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/neuroimaging/attachments/20190104/fa3b8269/attachment.html>


More information about the Neuroimaging mailing list