配置API的視頻教程在這里,建議看視頻,視頻里的很詳細,
視頻教程
百度Ai平臺鏈接
這是最后的代碼
代碼和教程的代碼一樣
import requests
import base64
import cv2
import numpy as np
import base64
from 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’
這主要是因為你要處理的圖片太大了,把它的容量改小一點,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/299431.html
標籤:其他
