使用numpy将alpha通道添加到RGB数组

时间:2016-09-22 15:09:08

标签: python numpy

我在RGB空间中有一个图像数组,并希望将alpha通道添加为全零。具体来说,我有一个numpy阵列的形状(205,54,3),我想将形状更改为(205,54,4),第三维中的附加点全部为0.0'秒。哪个numpy操作会实现这个目标?

4 个答案:

答案 0 :(得分:13)

您可以使用其中一个堆栈函数(stack / hstack / vstack / dstack / concatenate)将多个数组连接在一起。

numpy.dstack( ( your_input_array, numpy.zeros((25, 54)) ) )

答案 1 :(得分:5)

如果您将当前图像作为rgb变量,那么只需使用:

rgba = numpy.concatenate((rgb, numpy.zeros((205, 54, 1))), axis=2)

Concatenate函数将rgb和zeros数组合并在一起。零功能创建零数组。我们将轴设置为2意味着我们在thirde维度中合并。注意:轴从0开始计算。

答案 2 :(得分:0)

np数组样式,在深度尺寸(通道尺寸,第3维)上堆叠:

rgba = np.dstack((rgb, np.zeros(rgb.shape[:-1])))

但是您应该使用OpenCV功能:

rgba = cv2.cvtColor(rgb, cv2.COLOR_RGB2RGBA)

答案 3 :(得分:0)

不确定您是否还在寻找答案。

最近,我正在寻求实现与numpy完全相同的功能,因为我需要将24位深度png强制为32。我同意使用dstack是有意义的,但我无法做到这一点工作。我改用insert,似乎达到了我的目标。

# for your code it would look like the following:
rgba = numpy.insert(
    rgb,
    3, #position in the pixel value [ r, g, b, a <-index [3]  ]
    255, # or 1 if you're going for a float data type as you want the alpha to be fully white otherwise the entire image will be transparent.
    axis=2, #this is the depth where you are inserting this alpha channel into
)

希望这会有所帮助,祝你好运。

相关问题