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

Question:

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

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.

Asked By: Zahra Karimi

||

Answers:

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 saved as image_0.jpeg, image_1.jpeg, … etc

Answered By: Yazeed Alnumay
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.