美文网首页
python调用人脸识别平台接口并解析json

python调用人脸识别平台接口并解析json

作者: 冒险小A | 来源:发表于2018-08-08 15:30 被阅读0次

将本地图片转化为base64给face++接口,得到返回的json并解析

  1. 安装requests库
    为什么选择这个库 ? Requests它会比urllib更加方便,可以节约我们大量的工作。requests是python实现的最简单易用的HTTP库,建议爬虫使用requests库。默认安装好python之后,是没有安装requests模块的,需要单独通过pip安装(请先安装pip)
    pip insatll request
  1. 编写py代码
# coding=utf-8
# face++ 人脸识别detect部分
import requests
import base64
import json

def file_base64(file_name):
    with open(file_name, 'rb') as fin:
        file_data = fin.read()
        base64_data = base64.b64encode(file_data)
    return base64_data

def post_pic():
    url = 'https://api-cn.faceplusplus.com/facepp/v3/detect'
    image_1 = file_base64('/home/dashuaibi/图片/1.jpg') 

    postData = {
        'api_key': 'mTxxxxxxxxxxxxxxxxwuG',
        'api_secret': 'uo3xxxxxxxxxxxxxxxxxxxxxxxxeb5',
        'image_base64': image_1,
        'return_attributes' : 'emotion'
    }

    back = requests.post(url, data = postData)
    jres = json.loads(back.text)
    print jres['faces'][0]['attributes']['emotion']

if __name__=="__main__":
    post_pic()
  1. 运行后发现打印的是
    {u'neutral': 60.45, u'sadness': 0.963, u'disgust': 0.104, u'anger': 3.324, u'surprise': 0.795, u'fear': 0.104, u'happiness': 34.26}
    在loads后变成python变量时,元素都变成了单引号,并且字符串前加多了个u
    json.loads()会在key前加上Unicode识别字符
    但是只是提示作用而已 并不影响数据
  1. 编写业务逻辑
# coding=utf-8
# face++ 人脸识别detect部分
import requests
import base64
import json

def file_base64(file_name):
    with open(file_name, 'rb') as fin:
        file_data = fin.read()
        base64_data = base64.b64encode(file_data)
    return base64_data

def post_pic():
    url = 'https://api-cn.faceplusplus.com/facepp/v3/detect'
    image_1 = file_base64('/home/dashuaibi/图片/1.jpg') 

    postData = {
        'api_key': 'mTtxxxxxxxxxxxxxwuG',
        'api_secret': 'uo3xxxxxxxxxxxxxxJeb5',
        'image_base64': image_1,
        'return_attributes' : 'emotion'
    }

    back = requests.post(url, data = postData)
    jres = json.loads(back.text)
    #emotion各可能性
    info = jres['faces'][0]['attributes']['emotion']
    anger = info['anger']
    disgust = info['disgust']
    fear = info['fear']
    happiness = info['happiness']
    neutral = info['neutral']
    sadness = info['sadness']
    surprise = info['surprise']
    emotion = [anger,disgust,fear,happiness,neutral,sadness,surprise]
    emotion_name = ['愤怒','厌恶','恐惧','高兴','平静','伤心','惊讶']
    print '您现在的表情是'+emotion_name[emotion.index(max(emotion))]

if __name__=="__main__":
    post_pic()
  1. 输出结果 :
  1. 总结:
  • python的库超级强大!!!!!!
  • pip超级好用!!!!!
  • 因为是linux的gedit手打,相当于记事本了,就懒得每一行写注释了嘿嘿

相关文章

网友评论

      本文标题:python调用人脸识别平台接口并解析json

      本文链接:https://www.haomeiwen.com/subject/qmhxbftx.html