PaddleHub图片抠图合成(将霉霉P到埃菲尔铁塔前)

2022-07-30,,

此项目是使用PaddleHub简单地对图片进行抠图合成,将霉霉抠出来P到埃菲尔铁塔前面。

和常见的PS抠图相比,使用PaddleHub抠图可以节省时间,并能够智能地对图片中颜色较为接近的边缘进行抠图,准确率较高。 PaddleHub便捷地获取PaddlePaddle生态下的预训练模型,完成模型的管理和一键预测。配合使用Fine-tune API,可以基于大规模预训练模型快速完成迁移学习,让预训练模型能更好地服务于用户特定场景的应用。

PaddleHub官网地址:paddlepaddle.org.cn/hub
更多PaddleHub项目地址:https://github.com/PaddlePaddle/PaddleHub

首先需要安装PaddleHub标准库以及其中DeepLabv3+模型一键抠图。

!pip install paddlehub==1.6.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
!hub install deeplabv3p_xception65_humanseg==1.0.0 
#导入所用标准库
import os
import numpy as np
import paddlehub as hub
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from PIL import Image
In [30] 
# 测试图片路径和输出路径
test_path = 'data/test/'
output_path = 'data/out/'

# 待预测图片
test_img_path = ["taylor swift.jpg"]
test_img_path = [test_path + img for img in test_img_path]
img = mpimg.imread(test_img_path[0]) 

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

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) 
# 预测结果展示
out_img_path = 'humanseg_output/' + os.path.basename(test_img_path[0]).split('.')[0] + '.png'
img = mpimg.imread(out_img_path)
plt.figure(figsize=(10,10))
plt.imshow(img) 
plt.axis('off') 
plt.show() 

抠出来的图片还会有少许没有被抠掉的地方。

# 定义合成函数
def blend_images(fore_image, base_image, output_path):
    """
    将抠出的人物图像换背景
    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(output_path)
    return res_image 
output_path_img = output_path + 'blend_res_img.jpg'
blend_images('humanseg_output/taylor swift.png', 'data/test/eifel.jpg', output_path_img)

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

总结:

此项目使用paddlehub进行了抠图和合成,可以实现PS软件的功能,但少量的代码减小了内存占用,这让我们看到了paddlehub的精巧之处。但还有很多不足之处,比如精确度不是特别高,后面的人影会影响抠图效果,在后面的模型中需要改进。
这是使用paddlehub进行抠图和合成图片的小尝试,这次尝试让我了解了paddlehub工具的使用,后续我还会做一些更多的尝试,比如视频抠图,让图片活起来。

本文地址:https://blog.csdn.net/weixin_43899481/article/details/108240773

《PaddleHub图片抠图合成(将霉霉P到埃菲尔铁塔前).doc》

下载本文的Word格式文档,以方便收藏与打印。