废话不多说,参考文档里是使用
params = "{\"image\":\"027d8308a2ec665acb1bdf63e513bcb9\",\"image_type\":\"FACE_TOKEN\",\"face_field\":\"faceshape,facetype\"}"
但实际中我们要自己选择图片的路径,因此:
//获取文件的路径
filePath = r"C:\Users\abc\Desktop\text.jpg"
//定义一个读取函数,将api接口转成对应格式
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
pic = base64.b64encode(fp.read())
return pic
//image标签和image_type标签页是必传的参数,我这里在加入一个识别情绪的参数
params = {"image":''+get_file_content(filePath)+'', "image_type": "BASE64", "face_field": "expression"}
//这个挺关键
params = urllib.urlencode(params)
access_token = get_token()//这里是获取access_token的函数,我是动态获得
//接下来基本与百度文档一致,即可识别
request_url = request_url + "?access_token=" + access_token
request = urllib2.Request(url=request_url, data=params)
request.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(request)
content = response.read()
if content:
print content
附加上一下源码,这个是我在python3.7下识别的源码
#encoding:utf-8
import urllib, urllib3, base64,json,sys,ssl
import re
import cv2
from urllib import parse,request
#涉及图片路径的自己改
photopaths = r"C:\Users\abc\Desktop\image/"
APP_ID = '自己填'
API_KEY = '自己的'
SECRET_KEY = '自己的'
filePath = r"C:\Users\abc\Desktop\image\1.jpg"
def opencamere():
camera = cv2.VideoCapture(0)
cv2.namedWindow('MyCamera')
c = 1
while True:
success, frame = camera.read()
cv2.imshow('MyCamera', frame)
if (c):
c = c + 1
if (c % 5 == 0): # 每隔timeF帧进行存储操作
cv2.imwrite(photopaths+str(1)+'.jpg',frame)
print(recognize())
if cv2.waitKey(1) & 0xff == ord('q'):
break
cv2.destroyWindow('MyCamera')
camera.release()
def get_token():
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+API_KEY+'&client_secret='+SECRET_KEY
re = request.Request(host)
re.add_header('Content-Type', 'application/json; charset=UTF-8')
response = request.urlopen(re)
content = response.read()
content = bytes.decode(content)
content = eval(content[:-1])
return content['access_token']
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
pic = base64.b64encode(fp.read())
return pic
#params = "{\"image\":\"027d8308a2ec665acb1bdf63e513bcb9\",\"image_type\":\"FACE_TOKEN\",\"face_field\":\"faceshape,facetype\"}"
def recognize():
params = {"image": '' + str(get_file_content(filePath), 'utf-8') + '', "image_type": "BASE64",
"face_field": "emotion"}
params = parse.urlencode(params).encode('utf-8')
access_token = get_token()
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
request_url = request_url + "?access_token=" + access_token
message = request.Request(url=request_url, data=params)
message.add_header('Content-Type', 'application/json')
response = request.urlopen(message)
content = response.read()
#pat_emotion = re.compile('angry'|'happy'|'fear'|'sad',re.S)
pat_emotion = re.compile('(angry|happy|fear|sad)')
content = pat_emotion.findall(str(content))
if content:
print(content)
return content
opencamere()