opencv通过mask掩码图合成两张图
此处两张图分别为纯色背景图和抠出来的人像图(背景是纯白色的)
def composite(fg, bg, a, w, h):
"""
:param fg: 白色背景人像图,Image对象
:param bg: 纯色图,Image对象
:param a: mask灰度图,可以是二值,Image对象
:param w: 原图的宽
:param h: 原图的高
:return: Image对象
"""
bbox = fg.getbbox()
bg = bg.crop((0, 0, w, h))
fg_list = fg.load()
bg_list = bg.load()
a_list = a.load()
for y in range(h):
for x in range(w):
alpha = a_list[x, y] / 255
# alpha = (a_list[x,y][0] / 255 + a_list[x,y][1] / 255 + a_list[x,y][2] / 255) / 3
t = fg_list[x, y][0]
t2 = bg_list[x, y][0]
if alpha >= 1:
r = int(fg_list[x, y][0])
g = int(fg_list[x, y][1])
b = int(fg_list[x, y][2])
bg_list[x, y] = (r, g, b, 255)
elif alpha > 0:
r = int(alpha * fg_list[x, y][0] + (1 - alpha) * bg_list[x, y][0])
g = int(alpha * fg_list[x, y][1] + (1 - alpha) * bg_list[x, y][1])
b = int(alpha * fg_list[x, y][2] + (1 - alpha) * bg_list[x, y][2])
bg_list[x, y] = (r, g, b, 255)
return bg