原理上参考了这篇博客https://blog.csdn.net/m0_46555380/article/details/114301348
原博为C#写的,这里使用了Python,opencv-python的版本为3.4.2.16
# 参考:https://blog.csdn.net/m0_46555380/article/details/114301348
# 当一个像素为白色背景时, 能够显示出一个特定的颜色 x , 当黑色背景时, 显示出 y
# 设: 颜色 x 的亮度为 xc, 颜色 y 的亮度为 yc, 这个像素的亮度为 zc, 不透明度为 za, 则满足:
# xc = za * zc + (1 - za)
# yc = za * zc
# 最终:
# zc = yc / za za = yc - xc + 1
# 考虑 ARGB通道值为0 ~ 255
# zc = yc / (za / 255) = yc * 255 / za
# za = yc - xc + 255
# 需要满足条件 xc >= yc
import cv2
def xc_max_than_yc(xc, yc, color_ratio=0.5):
"""令 xc > yc"""
threshold = 255 * color_ratio
xc = (xc / 255) * (255 - threshold) + threshold
yc = (yc / 255) * threshold
return xc, yc
def create_Mtank(white, black):
"""生成幻影坦克,条件是白底图的每个像素值大于黑底图的每个像素值"""
za = black - white + 255
zc = black.copy()
idx = black != 0
zc[idx] = black[idx] * 255 / za[idx]
img = cv2.merge((zc, zc, zc, za))
return img
white_path = "./img/1.jpg" # 白底图
black_path = "./img/2.jpg" # 黑底图
img_false = cv2.imread(white_path, 0)
img_true = cv2.imread(black_path, 0)
x, y = img_true.shape
img_false = cv2.resize(img_false, (y, x))
xc, yc = xc_max_than_yc(img_false, img_true)
cv2.imwrite("result.png", create_Mtank(xc, yc))