An image with alpha channel is just an image with 4 channels: 3 colors (B, G, R in OpenCV), and the alpha channel. So let's say you have your color image src
. Then
import numpy as np
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
img_w_alpha = np.dstack( (src, gray) )
np.dstack
adds the alpha channel as the 4th channel to your color image.
I don't understand though, why you'd want to do that, so if that doesn't answer your question, maybe you need to elaborate on it.
EDIT: Following your comments, maybe you're looking for alpha blending?
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)
As you can see, where Nixon's image is almost black, e.g. in his jacket and hair, the background image is visible, and where Nixon's image is bright, e.g. his collar and face, the background image is barely visible.
The code for blending looks so awkward, because
- we can not multiply a
h-by-w
image with a h-by-w-by-c
image, but we CAN multiply a h-by-w-by-1
image with a h-by-w-by-c
image, so we have to add the dimension to alpha
using reshape
.
- for the blending, we have to convert the image from uint to float, but once we're done, we want to have uint again.
But do some Googling for "alpha blending" if this is what you're after.