RGB图像和Alpha通道的合并.
W1 - 添加到 RGBA 通道
import cv2
rgba = cv2.cvtColor(rgb_data, cv2.COLOR_RGB2RGBA)
# Then assign the mask to the last channel of the image
rgba[:, :, 3] = alpha_data
# First create the image with alpha channel
cv::cvtColor(rgb_data, rgba , cv::COLOR_RGB2RGBA);
# Split the image for access to alpha channel
std::vector<cv::Mat>channels(4);
cv::split(rgba, channels);
# Assign the mask to the last channel of the image
channels[3] = alpha_data;
# Finally concat channels for rgba image
cv::merge(channels, 4, rgba);
W2 - cv2.merge
import cv2
b, g, r_ = cv2.split(img)
#creating a dummy alpha channel image.
alpha = np.ones(b.shape, dtype=b.dtype) * 50
#alpha = alpha.astype(np.uint8)
img_bgra = cv2.merge((b, g, r, alpha))
cv2.imwrite("test.png", img_bgra)
W3 - np.dstack
import numpy as np
img_bgra = np.dstack((img_bgr, alpha))
Alpha Blending
$$ I = \alpha F + (1 - \alpha) B $$
- $\alpha = 0$ - 背景
- $\alpha = 1$ - 前景
- $0 < \alpha < 1$ - 前景背景像素融合
import cv2
# Read the images
foreground = cv2.imread("puppets.png")
background = cv2.imread("ocean.png")
alpha = cv2.imread("puppets_alpha.png")
# Convert uint8 to float
foreground = foreground.astype(float)
background = background.astype(float)
# Normalize the alpha mask to keep intensity between 0 and 1
alpha = alpha.astype(float)/255
# Multiply the foreground with the alpha matte
foreground = cv2.multiply(alpha, foreground)
# Multiply the background with ( 1 - alpha )
background = cv2.multiply(1.0 - alpha, background)
# Add the masked foreground and background.
outImage = cv2.add(foreground, background)
# Display image
cv2.imshow("outImg", outImage/255)
cv2.waitKey(0)