I have a 3D numpy array I want to iterate through. If it's important, this is a .nii filetype (file used to store MRI brain data) and I used the nipy module to load these images, which can then be handled as numpy arrays to do image processing. I want to take the and go through the voxels and only include the voxels that have value < 2. Here is my attempt
import nipy
import numpy
img = nipy.load_image('image.nii.gz')
img_manip = img.get_data()
result = numpy.zeros(shape = img_manip.shape, dtype = img_manip.dtype)
for matrix in img_manip:
for row in matrix:
for item in row:
if item < 2:
result += img_manip
This SEEMS to work,but it's extremely slow, like it's still running now. I'm just wondering, is this the right way to do it? Should I have used np.empty instead? I'm not sure I'm still pretty noob at python.
EDIT: Just an FYI, the shape of img_manip is something like (368, 170, 32) and data type is float64
(Sorry I don't know how to make the code look "pythonic"!)
result = (img_manip < 2).sum() * img_manipthat is different fromimg_manip[img_manip > 2] = 0