【PaddleHub】在家走遍世界

背景

疫情在家,但是阻挡不了我的一颗环游世界的心。

所需库

paddlehub

matplotlib

opencv

numpy

PIL

pandas

项目链接

https://aistudio.baidu.com/aistudio/projectdetail/766202?shared=1

实现思路

  1. 准备好自己的全身照

  2. 爬取想去的城市、景点的照片

  3. 将全身照抠出来

  4. 将抠出来的全身照与背景融合

  5. 改变照片风格,换成艺术风格,对图片进行灰度处理

  6. 给照片加一个相框

  7. 最后一键开启环游世界之旅

查看当前挂载的数据集目录, 该目录下的变更重启环境后会自动还原

!ls /home/aistudio/data

查看工作区文件, 该目录下的变更将会持久保存. 请及时清理不必要的文件, 避免加载过慢.

!ls /home/aistudio/work

如果需要进行持久化安装, 需要使用持久化路径, 如下方代码示例:

!mkdir /home/aistudio/external-libraries
!pip install beautifulsoup4 -t /home/aistudio/external-libraries

同时添加如下代码, 这样每次环境(kernel)启动的时候只要运行下方代码即可:

import sys
sys.path.append('/home/aistudio/external-libraries')

安装paddlehub

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

导入一些必要的库

import matplotlib.pyplot as plt 
import matplotlib.image as mpimg 
from matplotlib import animation
import cv2
import paddlehub as hub
from PIL import Image, ImageSequence, ImageFont, ImageDraw
from IPython.display import display, HTML
import numpy as np 
import imageio
import os
import requests
import re
import pandas as pd

爬取想去的城市,景点的照片,numPicture为爬取的照片数量,十张照片存储在work/pictures中。

def down_pics(sightseeing):
    num=0
    '''
    爬取景点的百度图片,并保存
    ''' 
    path_pic = 'work/'+'pictures/'+sightseeing
    if not os.path.exists(path_pic):
        os.makedirs(path_pic)

    Re=[]
    link='http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word='+sightseeing
    print(link)

    headers = { 
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36' 
     }

    response_pic = requests.get(url=link,headers=headers,timeout=5)
    result = response_pic.text
    pic_url = re.findall('"objURL":"(.*?)",', result, re.S)  # 先利用正则表达式找到图片url 
    print(len(pic_url))
 
    for each in pic_url:
        print('正在下载第' + str(num + 1) + '张图片,图片地址:' + str(each))
        try:
            if each is not None:
                pic = requests.get(each, timeout=7)
            else:
                continue
        except BaseException:
            print('错误,当前图片无法下载')
            continue
        else:
            string = str(num) + '.jpg'
            fp = open(path_pic+'/'+ string, 'wb')
            fp.write(pic.content)
            fp.close()
            num += 1

        # 默认下载10张景色图片 
        numPicture=10
        if num >= numPicture:
            return
def pickup_person():
    # 测试图片路径和输出路径
    test_path = 'work/'
    output_path = 'work/pictures'

    # 待预测图片
    test_img_path = ["xiaomei.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)

将抠出来的人和背景融合

def blend_images(fore_image, background_image, output_path):
    """
    将抠出的人物图像换背景
    fore_image: 前景图片,抠出的人物图片
    base_image: 背景图片
    """
    # 读入图片
    base_image = Image.open(background_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)
    print('人物与背景合成成功')

将图片转成复古的艺术风格,将图片进行灰度处理

#导入图片并进行灰度处理
def shouhui_pic():
    img = Image.open('work/picturesblend_img.jpg')  #读取图片
    img_huidu = img.convert('L')   #灰度处理
    img_huidu.save('work/picsblend_img1.jpg')
    print('灰度化处理图片成功')

然后为图片添加一个相框

def frameadd(number):
    jpg = 'work/picsblend_img1.jpg'
    img = Image.open(jpg)
    new_pic = Image.new('RGB', (img.width + 50, img.height + 50), color=number)
    new_pic.paste(img, (25, 25)) 
    new_pic.save('work/picsblend_img2.png') 
    print('相框添加完成')

开始一键环游世界吧

if __name__ == "__main__":

    sightseeing=str(input('输入你要参观的景点:\n'))
    down_pics(sightseeing)

    pickup_person()

    print('选择背景图片,路径,如:work/pictures/莫斯科/0.jpg')
    background_image = str(input('选择你想要的背景图片:\n'))
    
    output_path = 'work/pictures'
    output_path_img = output_path + 'blend_img.jpg'
    blend_images('humanseg_output/xiaomei.png', background_image, output_path_img)


    shouhui_pic()
    
    print('输入你喜欢的相框的颜色参数,范围(1~255),1至255为由黑色至红色')
    number=int(input('输入你喜欢的颜色参数:\n'))
    frameadd(number)
    print('照片生成成功,见 work/blend_img2.png ')

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值