人像分割有些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,排版更清晰,阅读更爽快。