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



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

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

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

如果您将当前图像设置为rgb变量,则只需使用:

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

连接函数合并rgb和0数组。零点函数创建一个零数组。我们设轴为2,这意味着我们在三维空间中合并。注意:轴从0开始计数

np数组样式,堆栈深度维度(通道维度,第三维度):

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

但是你应该使用OpenCV函数:

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

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

最近我正在寻找实现与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
)

最新更新