我认为您更多地寻找分级的 alpha 混合,而不是弗雷德的答案很好地演示的更简单的 alpha 阈值。
为了测试目的,我制作了一个中间带有 alpha 渐变的示例图像。这里它是一个普通图像,并合成在棋盘上以显示透明度,就像 Photoshop 所做的那样:
要进行 Alpha 混合,请使用以下公式:
result = alpha * Foreground + (1-alpha)*Background
其中值都是在 0..1 范围内缩放的浮点数
混合黑色和白色背景的代码如下:
#!/usr/bin/env python3
import cv2
import numpy as np
# Load image, including gradient alpha layer
im = cv2.imread('GradientAlpha.png', cv2.IMREAD_UNCHANGED)
# Separate BGR channels from A, make everything float in range 0..1
BGR = im[...,0:3].astype(np.float)/255
A = im[...,3].astype(np.float)/255
# First, composite image over black background using:
# result = alpha * Foreground + (1-alpha)*Background
bg = np.zeros_like(BGR).astype(np.float) # black background
fg = A[...,np.newaxis]*BGR # new alpha-scaled foreground
bg = (1-A[...,np.newaxis])*bg # new alpha-scaled background
res = cv2.add(fg, bg) # sum of the parts
res = (res*255).astype(np.uint8) # scaled back up
cv2.imwrite('OverBlack.png', res)
# Now, composite image over white background
bg = np.zeros_like(BGR).astype(np.float)+1 # white background
fg = A[...,np.newaxis]*BGR # new alpha-scaled foreground
bg = (1-A[...,np.newaxis])*bg # new alpha-scaled background
res = cv2.add(fg, bg) # sum of the parts
res = (res*255).astype(np.uint8) # scaled back up
cv2.imwrite('OverWhite.png', res)
这就给出了黑色:
这是白色的:
Keywords:图像处理、Python、OpenCV、alpha、alpha 混合、alpha 合成、叠加。