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

人像分割有些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

人像分割的Python示例代码

# 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)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值