具有 alpha 通道的图像只是具有 4 个通道的图像:3 种颜色(OpenCV 中的 B、G、R)和 alpha 通道。所以假设你有你的彩色图像src。那么
import numpy as np
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
img_w_alpha = np.dstack( (src, gray) )
np.dstack 将 Alpha 通道作为第四个通道添加到您的彩色图像中。
但我不明白,为什么你想这样做,所以如果这不能回答你的问题,也许你需要详细说明。
编辑:跟随您的 cmets,也许您正在寻找 alpha 混合?
import cv2
# Load the tiff
tif = cv2.imread('tmp/Nixon.tif')
h,w,c = tif.shape
alpha = cv2.cvtColor(tif, cv2.COLOR_BGR2GRAY)
tif_a = cv2.cvtColor(tif, cv2.COLOR_BGR2BGRA)
tif_a[:,:,3] = alpha # now you have an image whose alpha channel equals the greyscale values,
# but I'm not sure what good that is
# load a background image
img = cv2.imread('tmp/PA110602.JPG')
img = cv2.resize(img, (w,h)) # for blending, both images need to be of same size
# blend the two images, using the greyscale version of tif as alpha values
blend = cv2.add(
alpha.reshape((*alpha.shape,1))/255.0*tif.astype(float),
(1.0-alpha.reshape((*alpha.shape,1))/255.0)*img.astype(float),
dtype=cv2.CV_8UC1)
如您所见,尼克松的图像几乎是黑色的,例如在他的夹克和头发中,背景图像是可见的,并且尼克松的图像是明亮的,例如。他的衣领和脸,几乎看不到背景图像。
混合的代码看起来很别扭,因为
- 我们不能将
h-by-w 图像与h-by-w-by-c 图像相乘,但我们可以将h-by-w-by-1 图像与h-by-w-by-c 图像相乘,因此我们必须使用reshape 将维度添加到alpha .
- 对于混合,我们必须将图像从 uint 转换为 float,但一旦完成,我们希望再次使用 uint。
但是,如果这是您所追求的,请在谷歌上搜索“alpha blending”。