How I can slice the images and the masks in python on certain range and store them

Hello

I am trying to segment certain area in the brain. after I see different slices of the brain and the mask (as appears below) I found that not all slices are useful in my case. so I decided to do the segmentation in certain slices that the are is visible on it.

so my target dominations of the image is [256, 256, the range from 130- 140]
and target mask [256,256, the range 130-140]

My question is how I can slice the images and the masks in python and store them so i can work on their segmentation.

Any clarification will help

#check the image
fig, ax = plt.subplots(1, 6, figsize=[18, 3])
n = 0
slice = 100
for _ in range(6):
    ax[n].imshow(image[:, :, slice], 'gray')
    ax[n].set_xticks([]) 
    ax[n].set_yticks([])
    ax[n].set_title('Slice number: {}'.format(slice), color='g')
    n += 1
    slice += 10
fig.subplots_adjust(wspace=0, hspace=0)
plt.show()

#check the mask
fig, ax = plt.subplots(1, 6, figsize=[18, 3])
n = 0
slice = 100
for _ in range(6):
    ax[n].imshow(mask[:, :, slice], 'gray')
    ax[n].set_xticks([]) 
    ax[n].set_yticks([])
    ax[n].set_title('Slice number: {}'.format(slice), color='r')
    n += 1
    slice += 10
fig.subplots_adjust(wspace=0, hspace=0)
plt.show()

Hello,

You can load an image with my_img = nilearn.image.load_img($PATH_TO_IMAGE), get the data in matrix form with my_img_data = my_img.get_fdata(), and then get your parts of interest with my_img_data_useful = my_img_data[:,:,130:140]. How you store them is up to you; you can make 4D matrix, where it is 256X256X10XN_subjects, or perhaps a dictionary would be better. You can also save out just the important slices as NIFTIs with my_img_data_useful.to_filename($PATH_TO_OUTPUT_NAME)

Best,
Steven

1 Like

This is helpful :slight_smile:
appreciated , thanks

I got this error when I tried to save the file after the slicing process.

my_img =nli.load_img(MRI_path)
my_img_data = my_img.get_fdata()
my_img_data.shape
(170, 256, 256, 1)

my_img_data_useful = my_img_data[:,:,130:140]

my_img_data_useful.shape
(170, 256, 10, 1)

my_img_data_useful = np.rot90(my_img_data_useful.squeeze(), 1) #rotate the imgae 90 degree

my_img_data_useful.shape
(256, 170, 10)

type(my_img_data_useful)
numpy.ndarray

my_img_data_useful.to_filename(PATH_TO_OUTPUT_NAME)

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [88], in <cell line: 2>()
      
----> 2 my_img_data_useful.to_filename(PATH_TO_OUTPUT_NAME)

AttributeError: 'numpy.ndarray' object has no attribute 'to_filename'

You can use nibabel: nifti_file = nibabel.Nifti1Image(my_img_data_useful, affine), where affine is the affine matrix for your original image.

1 Like