Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert each slice of a numpy file to jpeg format with for loop

I’m beginners in python
I have a numpy file with the shapes of (200, 256, 256). I want to save each slice (:, 256, 256) with jpeg format. how can I do using a for loop ?
Thanks in advance

I tried this but for an image with the shape of (256, 256)

your textfrom PIL import Image
your textimport numpy as np

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

your textA= np.load(‘image.npy’ ,allow_pickle = True)
your textim = Image.fromarray(A)
your textim.save("image.jpeg")

But I want to try this for a file with the shape of (200, 256, 256) with a for loop because I have some files like this.

>Solution :

You can loop over the first dimension, extracting the image slices and saving them

from PIL import Image
import numpy as np

A = np.load('image.npy' ,allow_pickle = True)
for i in range(A.shape[0]):
    im = Image.fromarray(A[i,:,:])
    im = im.convert("L")
    im.save(f"image_{i}.jpeg")

The images will be saves as image_0.jpeg, image_1.jpeg, … etc

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading