AI人像抠图及合成

https://aistudio.baidu.com/aistudio/projectdetail/368518

0.可以用于头像照生成证件照

1.从人物图片中扣选出人物

2.将扣选出的图片和背景图结合

3.生成新的人物在背景图上的图片

AI人像抠图及合成_第1张图片

AI人像抠图及合成_第2张图片

# !pip install paddlehub==1.6.0 -i https://pypi.tuna.tsinghua.edu.cn/simple

# 待预测图片
#test_img_path = ["./meditation.jpg"]
test_img_path = ["./figure.png"]
#test_img_path = ["./merge.jpg"]


import matplotlib.pyplot as plt 
import matplotlib.image as mpimg 

img = mpimg.imread(test_img_path[0]) 

# 展示待预测图片
plt.figure(figsize=(10,10))
plt.imshow(img) 
plt.axis('off') 
plt.show()

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/meditation.png"
test_img_path = "./humanseg_output/figure.png"
img = mpimg.imread(test_img_path)
plt.figure(figsize=(10,10))
plt.imshow(img) 
plt.axis('off') 
plt.show()

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("merge.jpg")


#blend_images('./humanseg_output/meditation.png', 'sea_wave.jpg')
blend_images('./humanseg_output/figure.png', 'background.png')

# 展示合成图片
plt.figure(figsize=(10,10))
img = mpimg.imread("./merge.jpg")
plt.imshow(img) 
plt.axis('off') 
plt.show()

 

你可能感兴趣的:(AI)