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 text
from PIL import Image
your text
import numpy as np
your text
A= np.load(‘image.npy’ ,allow_pickle = True)
your text
im = Image.fromarray(A)
your text
im.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.
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
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 text
from PIL import Image
your text
import numpy as np
your text
A= np.load(‘image.npy’ ,allow_pickle = True)
your text
im = Image.fromarray(A)
your text
im.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.
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