我认为您正在寻找渐变 alpha 混合,而不是 Fred 的回答很好地展示的更简单的 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)
这给了这个黑色:
而且这个是白色的:
关键词:图像处理、Python、OpenCV、alpha、alpha blending、alpha compositing、overlay。