chaw359
chaw359

Reputation: 525

How to get images intensity matrix from Nifti images with Nibabel?

I'm new with NiBabel. I want to know how to get intensity matrix from a Nifti images with this library. I use the following script to get voxels:

import nibabel as ni
example_img = ni.load('myImage.nii')

data = example_img.get_data()

I thought at beginning that data contains the voxels' intensity, but when I've printed it, I've seen negative values, it seems strange to have a negative intensity within an image, don't you think?

I need to get the voxels' intensity within a nifti image, is it possible with nibabel? If not, can you propose me an other solution?

Upvotes: 4

Views: 3001

Answers (4)

seralouk
seralouk

Reputation: 33127

No. You can have negatives and nan.

These represent voxels outside the brain. The intensity is just the output of

data = example_img.get_fdata()

Note: use get_fdata and not get_data, to always get floating point numpy arrays.

Upvotes: 2

msrepo
msrepo

Reputation: 63

In addition to what seralouk has said in the earlier answer,, Since we are dealing with 'nii' nifti images, it is possible for voxel value to be negative. For example, if it were a CT scan, then each voxel stores values in Hounsfield unit, in which case 0 represents attenuation through water, whereas attenuation through air is -1000.

Upvotes: 0

SeanM
SeanM

Reputation: 135

Another direct method to use is nltools :: Brain_Data function to extract the data directly into an 1d array. Although not Nibabel but is similar to your logic.

from nltools.data import Brain_Data
img = Brain_Data('myImage.nii')
data = img.data

Upvotes: 0

Toby
Toby

Reputation: 21

Not sure how you're getting negative voxel values, but here's a way to display a NifTi image as a matrix:

import nibabel as ni
img = ni.load('myImage.nii')

data = example_img.get_data()

mat = []

for i in range(img.shape[0]):
  plane = []
  for j in range(img.shape[1]):
    row = []
    for k in range(img.shape[2]):
        row.append(data[i][j][k])
    plane.append(row)
  mat.append(plane)

Now you can print out/store in a text file the variable "mat".

Upvotes: 2

Related Questions