• 欢迎关注微信公众号:九万里大数据
  • 请使用Ctrl+D收藏本站到书签栏
  • 手机也可访问本站 jwldata.com

百度AI开放平台人体分析_人像分割的Python示例代码

其他 九万里大数据 1年前 (2021-06-07) 367次浏览 0个评论 扫描二维码

人像分割有些API需要用到opencv处理返回结果。
https://pypi.org/project/opencv-python

pip install requests
pip install numpy
pip install opencv-python

centos7上在用pip安装opencv-python后在进入python交互终端中导入cv2时有如下报错

from .cv2 import * ImportError: libGL.so.1: cannot open shared object file

解决方法是安装opencv的图形处理依赖包

yum install libglvnd-glx
# encoding:utf-8
 
import requests
import base64
import cv2
import numpy as np
 
'''
人像分割
https://cloud.baidu.com/doc/BODY/s/Fk3cpyxua
'''
 
request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg"
# 二进制方式打开图片文件
f = open('id_photo.jpg', 'rb')
img = base64.b64encode(f.read())
 
params = {"image":img}
access_token = '[调用鉴权接口获取的token]'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
# if response:
#     print (response.json())
 
# 分割后的二值图像,需二次处理方能查看分割效果
res = response.json()
labelmap = base64.b64decode(res['labelmap'])    # res为通过接口获取的返回json
# DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead
# nparr = np.fromstring(labelmap, np.uint8)
nparr = np.frombuffer(labelmap, np.uint8)
labelimg = cv2.imdecode(nparr, 1)
# width, height为图片原始宽、高
width = int(res['person_info'][0]['width'])
height = int(res['person_info'][0]['height'])
labelimg = cv2.resize(labelimg, (width, height), interpolation=cv2.INTER_NEAREST)
im_new = np.where(labelimg==1, 255, labelimg)
cv2.imwrite('id_photo_labelmap.jpg', im_new)

# 分割后的人像前景抠图
foreground = base64.b64decode(res['foreground']) 
with open('id_photo_foreground.jpg','wb') as f:
    f.write(foreground)

欢迎关注我的微信公众号“九万里大数据”,原创技术文章第一时间推送。
欢迎访问原创技术博客网站 jwldata.com,排版更清晰,阅读更爽快。


百度AI开放平台人体分析_人像分割的Python示例代码
 


本站文章,如未注明,均为原创 | 原创文章版权归九万里大数据所有,未经许可不得转载。
本文链接:百度AI开放平台人体分析_人像分割的Python示例代码
喜欢 (1)

您必须 登录 才能发表评论!