Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

python - How to save a 3 channel numpy array as image

I have a numpy array with shape (3, 256, 256) which is a 3 channel (RGB) image of resoulution 256x256. I am trying to save this to disk with Image from PIL by doing the following:

from PIL import Image
import numpy as np

#... get array s.t. arr.shape = (3,256, 256)
img = Image.fromarray(arr, 'RGB')
img.save('out.png')

However this is saving an image of dimensions 256x3 to disk

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The @Dietrich answer is valid, however in some cases it will flip the image. Since the transpose operator reverses the index, if the image is stored in RGB x rows x cols the transpose operator will yield cols x rows x RGB (which is the rotated image and not the desired result).

>>> arr = np.random.uniform(size=(3,256,257))*255

Note the 257 for visualization purposes.

>>> arr.T.shape
(257, 256, 3)

>>> arr.transpose(1, 2, 0).shape
(256, 257, 3)

The last one is what you might want in some cases, since it reorders the image (rows x cols x RGB in the example) instead of fully transpose it.

>>> arr = np.random.uniform(size=(3,256,256))*255
>>> arr = np.ascontiguousarray(arr.transpose(1,2,0))
>>> img = Image.fromarray(arr, 'RGB')
>>> img.save('out.png')

Probably the cast to contiguous array is not even needed, but is better to be sure that the image is contiguous before saving it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...