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

  • Thread starter Thread starter BRN
  • Start date Start date
  • Tags Tags
    File
Click For Summary
SUMMARY

This discussion addresses the process of extracting a slice from NIfTI (.nii) files and saving it as a PNG image in Python, specifically targeting a resolution of 256x256 pixels. The initial code utilized Matplotlib's matshow() function, which inadvertently added padding to the images, resulting in incorrect dimensions. The solution involved replacing matshow() with plt.imsave() to save the resized image directly, eliminating the padding issue and achieving the desired output size.

PREREQUISITES
  • Python programming knowledge
  • Familiarity with NIfTI file format and the nibabel library
  • Understanding of image processing using the Pillow library
  • Basic knowledge of Matplotlib for image visualization
NEXT STEPS
  • Explore the nibabel library for advanced NIfTI file handling
  • Learn about image resizing techniques in Pillow, focusing on different resampling methods
  • Investigate Matplotlib's imsave() function for efficient image saving
  • Study image padding issues and solutions in Matplotlib visualizations
USEFUL FOR

Data scientists, medical imaging professionals, and Python developers working with neuroimaging data who need to manipulate and save image slices from NIfTI files.

BRN
Messages
107
Reaction score
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:

[CODE lang="python" title="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
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!')[/CODE]

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?

[CODE lang="python" title="check size"]
im = Image.open('./outputs/ADNI_png_temp/P_ADNI_slc150_3.png')

width, height = im.size

print('width:', width)
print('height:', height)[/CODE]

[CODE title="outputs"]
width: 432
height: 288
[/CODE]

How can I solve?

Thanks.
 
Technology news on Phys.org
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?
 
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.
 
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:
[CODE lang="python" title="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
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!')[/CODE]
 
We have many threads on AI, which are mostly AI/LLM, e.g,. ChatGPT, Claude, etc. It is important to draw a distinction between AI/LLM and AI/ML/DL, where ML - Machine Learning and DL = Deep Learning. AI is a broad technology; the AI/ML/DL is being developed to handle large data sets, and even seemingly disparate datasets to rapidly evaluated the data and determine the quantitative relationships in order to understand what those relationships (about the variaboles) mean. At the Harvard &...

Similar threads

  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 1 ·
Replies
1
Views
3K
Replies
12
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
5K