How to resize and save a slice from a nii file as a PNG image in Python?

  • Python
  • Thread starter BRN
  • Start date
  • Tags
    File
In summary, I solved the problem by cropping the image with the 'Mathshow ()' function and saving it in the correct size.
  • #1
BRN
108
10
Hello everyone,

I have to extract a slice from a nii files and resize it with dimensions 256x256. Once this is done, I have to save it as a PNG image.

This is my code:

slice from nii file:
def img_from_nii(height, width, n_slice, label,  in_path, temp_path):
    
    filenames = os.listdir(in_path)
    
    for i in range(len(filenames)):
        mri_file = in_path + filenames[i]
        img_data = nib.load(mri_file).get_fdata()
        img_data = np.transpose(img_data, (2, 1, 0))
        slice_2D = Image.fromarray(img_data[:, :, n_slice]).resize((height, width))
        
        resized_slice = plt.matshow(slice_2D, cmap = 'gray', fignum = 0)
        plt.axis('off')
        plt.gca().set_axis_off()
        plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
        plt.margins(0, 0)
        
        plt.savefig(temp_path + label + '_ADNI_' + 'slc' + str(n_slice) + '_' + str(i + 1) + '.png')
        plt.close()
    
    print('dataset done!')

The problem is that PNG files are correctly created, but if you check the image size I do not get 256x256. How is it possible?

check size:
im = Image.open('./outputs/ADNI_png_temp/P_ADNI_slc150_3.png')

width, height = im.size

print('width:', width)
print('height:', height)

outputs:
width: 432
height: 288

How can I solve?

Thanks.
 
Technology news on Phys.org
  • #2
Have you looked at the images in Paint or something? From memory savefig pads the images the same way show() does.

Doesn't the Image class have a save method? Have you tried that?
 
  • #3
If as Image class you mean that of Pillow, yes there is the save method, but it does not support 32-bit images and I lose quality.

By opening the image with any reader, I see the image in the correct size 256x256, but I also have two completely empty side bands.

I believe that the save method of Matplotlib does not provide for the cropping.
 
  • #4
Oops! I forgot to update this post ...:-p

The problem was given by the 'Mathshow ()' function that adds additional spaces around the figure even if the axes are hidden.

I solved this way:
slice from nii file ok:
def img_from_nii(height, width, n_slice, label,  in_path, temp_path):
    
    filenames = os.listdir(in_path)
    
    for i in range(len(filenames)):
        mri_file = in_path + filenames[i]
        img_data = nib.load(mri_file).get_fdata()
        img_data = np.transpose(img_data, (2, 1, 0))
        slice_2D = Image.fromarray(img_data[:, :, n_slice]).resize((height, width), resample = Image.Resampling.LANCZOS)

        plt.imsave(temp_path + label + '_ADNI_' + 'slc' + str(n_slice) + '_' + str(i + 1) + '.png', slice_2D)
        
        plt.close()
    
    print('ADNI ' + label + ' dataset done!')
 

1. What is a .nii file?

A .nii file, also known as a Neuroimaging Informatics Technology Initiative file, is a type of image file used in the medical field for storing and sharing medical imaging data, such as MRI, CT, or PET scans.

2. How do you resize a slice from a .nii file?

To resize a slice from a .nii file, you can use imaging software such as MRIcron or FSL to open the file and manually adjust the dimensions of the slice. Alternatively, you can use a programming language like Python or MATLAB to write a script that resizes the slice for you.

3. Why would someone need to resize a slice from a .nii file?

There are several reasons why someone may need to resize a slice from a .nii file. One common reason is to improve the image quality by increasing the resolution of the slice. Another reason could be to standardize the size of the slices for comparison purposes in a research study.

4. Are there any limitations to resizing a slice from a .nii file?

Yes, there are some limitations to resizing a slice from a .nii file. The main limitation is that it may alter the original data and potentially affect the accuracy of the medical imaging results. Additionally, if the resizing is not done carefully, it could result in distorted images or loss of important details.

5. Is it possible to resize a slice from a .nii file without losing any data?

Yes, it is possible to resize a slice from a .nii file without losing any data. This can be achieved by using advanced image processing techniques, such as interpolation methods, which can preserve the original data while adjusting the size of the slice. However, it is important to note that some loss of data may still occur depending on the degree of resizing.

Similar threads

  • Programming and Computer Science
Replies
3
Views
1K
  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
1
Views
4K
Back
Top