在Python中将3个单独的numpy数组合并为RGB图像

Ish*_*mar 41 python numpy image image-processing

所以我有一组数据,我能够转换成R,G,B波段的单独numpy数组.现在我需要将它们组合起来形成RGB图像.

我试过'Image'来完成这项工作,但它需要'模式'来归因.

我试图做一个技巧.我会使用Image.fromarray()将数组带到图像,但默认情况下,当Image.merge需要合并"L"模式图像时,它会达到'F'模式.如果我在第一个位置将fromarray()中的数组属性声明为'L',则所有RGB图像都会失真.

但是,如果我保存图像,然后打开它们然后合并,它工作正常.图像以"L"模式读取图像.

现在我有两个问题.

首先,我不认为这是一种优雅的工作方式.所以,如果有人知道更好的方法,请告诉我们

其次,Image.SAVE无法正常工作.以下是我面临的错误:

In [7]: Image.SAVE(imagefile, 'JPEG')
----------------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

/media/New Volume/Documents/My own works/ISAC/SAMPLES/<ipython console> in <module>()

TypeError: 'dict' object is not callable
Run Code Online (Sandbox Code Playgroud)

请建议解决方案.

请注意,图像大小为4000x4000.

Bi *_*ico 51

我真的不明白你的问题,但这里有一个我最近做过的类似的例子,看起来它可能有所帮助:

# r, g, and b are 512x512 float arrays with values >= 0 and < 1.
from PIL import Image
import numpy as np
rgbArray = np.zeros((512,512,3), 'uint8')
rgbArray[..., 0] = r*256
rgbArray[..., 1] = g*256
rgbArray[..., 2] = b*256
img = Image.fromarray(rgbArray)
img.save('myimg.jpeg')
Run Code Online (Sandbox Code Playgroud)

我希望有所帮助

  • @IshanTomar - 如果有帮助,你可能希望接受这个答案. (12认同)
  • @IshanTomar你真的应该接受最有帮助的答案,这是阻止StackOverflow滴答作响的重要部分 (3认同)
  • @LeiYang,这意味着对之前的所有维度进行切片。请参阅:https://python-reference.readthedocs.io/en/latest/docs/brackets/ellipsis.html (2认同)

den*_*nis 46

rgb = np.dstack((r,g,b))  # stacks 3 h x w arrays -> h x w x 3
Run Code Online (Sandbox Code Playgroud)

要将浮动0 .. 1转换为uint8 s,

rgb_uint8 = (np.dstack((r,g,b)) * 255.999) .astype(np.uint8)  # right, Janna, not 256
Run Code Online (Sandbox Code Playgroud)


小智 6

rgb = np.dstack((r,g,b))  # stacks 3 h x w arrays -> h x w x 3
Run Code Online (Sandbox Code Playgroud)

如果您传递 3 个通道,此代码不会创建 3d 数组。保留 2 个通道。


Jan*_*ila 5

在将numpy数组uint8传递到之前将其转换为Image.fromarray

例如。如果浮点数在[0..1]范围内:

r = Image.fromarray(numpy.uint8(r_array*255.999))
Run Code Online (Sandbox Code Playgroud)