PaddleHub一键抠图并替换背景
抠图模型千千万,而我就用DeepLabv3+。DeepLabv3+ 是Google DeepLab语义分割系列网络的最新作,其前作有 DeepLabv1,DeepLabv2, DeepLabv3。在最新作中,作者通过encoder-decoder进行多尺度信息的融合,同时保留了原来的空洞卷积和ASSP层, 其骨干网络使用了Xception模型,提高了语义分割的健壮性和运行速率,在 PASCAL VOC 2012 dataset取得新的state-of-art performance。在完成一键抠图之后,通过图像合成,实现扣图任务。
1、准备工作
(1)线上环境:百度AI Studio提供了线上一站式开发实训平台,直接可在该平台完成。
(2)本地实现:在本编译器中,需要提前安装PaddleHub库,pip安装即可,最好加上国内源。
pip install paddlehub==1.6.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
2、实现步骤及代码
1、定义待抠图照片
本示例中文件夹下girl.jpg为待预测图片
# 待预测图片
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
test_img_path = ["./girl.jpg"]
img = mpimg.imread(test_img_path[0])
# 展示待预测图片
plt.figure(figsize=(10,10))
plt.imshow(img)
plt.axis('off')
plt.show()
原图片展示:
2、加载预训练模型
通过加载PaddleHub DeepLabv3+模型(deeplabv3p_xception65_humanseg)实现一键抠图
import paddlehub as hub
module = hub.Module(name="deeplabv3p_xception65_humanseg")
input_dict = {"image": test_img_path}
# execute predict and print the result
results = module.segmentation(data=input_dict)
for result in results:
print(result)
# 预测结果展示
test_img_path = "./humanseg_output/girl.png"
img = mpimg.imread(test_img_path)
plt.figure(figsize=(10,10))
plt.imshow(img)
plt.axis('off')
plt.show()
抠出的人物图像:
3、背景合成
将抠出的人物图片合成在想要的背景图片当中。
from PIL import Image
import numpy as np
def blend_images(fore_image, base_image):
"""
将抠出的人物图像换背景
fore_image: 前景图片,抠出的人物图片
base_image: 背景图片
"""
# 读入图片
base_image = Image.open(base_image).convert('RGB')
fore_image = Image.open(fore_image).resize(base_image.size)
# 图片加权合成
scope_map = np.array(fore_image)[:, :, -1] / 255
scope_map = scope_map[:, :, np.newaxis]
scope_map = np.repeat(scope_map, repeats=3, axis=2)
res_image = np.multiply(scope_map, np.array(fore_image)[:, :, :3]) + np.multiply((1 - scope_map),
np.array(base_image))
# 保存图片
res_image = Image.fromarray(np.uint8(res_image))
res_image.save("blend_res_img.jpg")
blend_images('./humanseg_output/girl.png', '1.jpg')
# 展示合成图片
plt.figure(figsize=(10,10))
img = mpimg.imread("./blend_res_img.jpg")
plt.imshow(img)
plt.axis('off')
plt.show()
合成的结果展示:
3、总结
注意:若用上述方法进行人物背景合成时,背景图最好选择和原图片大小相近,不然在合成的时候可能会导致人物变形。若在提前对人像美颜在合成我们想要的背景图,这样就既可以实现美颜又能进行抠图合成新的图片。