配置API的视频教程在这里。建议看视频,视频里的很详细。
视频教程
百度Ai平台链接
这是最后的代码
代码和教程的代码一样
import requests
import base64import cv2
import numpy as np
import base64from PIL import Image
'''
人像分割
'''
file_path = 'F:/630/images/test/4.jpg'
img = Image.open(file_path)width = img.width #图片的宽
height = img.height #图片的高request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg"
# 二进制方式打开图片文件
f = open(file_path, 'rb')
img = base64.b64encode(f.read())params = {"image":img}
access_token = '24.08f1b607452661766d1f84729094d470.2592000.1633934401.282335-24834460'
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())labelmap = base64.b64decode(response.json()['labelmap']) # res为通过接口获取的返回json
nparr = np.frombuffer(labelmap, np.uint8)
labelimg = cv2.imdecode(nparr, 1)
# width, height为图片原始宽、高
labelimg = cv2.resize(labelimg, (width, height), interpolation=cv2.INTER_NEAREST)
im_new = np.where(labelimg==1, 255, labelimg)
cv2.imwrite('F:/630/images/15/4.png', im_new)
实现效果这样
图片是百度找的图
可能会出现的报错是
KeyError: ‘labelmap’
这主要是因为你要处理的图片太大了。把它的容量改小一点。