Python通过API接口实现人脸识别功能

通过百度API接口,实现人脸识别功能
注册网址:http://ai.baidu.com/?track=cp:ainsem|pf:pc|pp:tongyong-pinpai|pu:pinpai-baiduAI|ci:|kw:10003812

import base64
import json
import requests
import pprint


class BaiduPicIndentify:
    def __init__(self, img):
        self.AK = "你注册的API Key"
        self.SK = "你的Secret Key"
        self.img_src = img
        self.headers = {
            "Content-Type": "application/json; charset=UTF-8"
        }

    def get_accessToken(self):
        host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + self.AK + '&client_secret=' + self.SK
        response = requests.get(host, headers=self.headers)
        json_result = json.loads(response.text)
        return json_result['access_token']

    def img_to_BASE64(slef, path):
        with open(path, 'rb') as f:
            base64_data = base64.b64encode(f.read())
            return base64_data

    def detect_face(self):
        # 人脸检测与属性分析
        img_BASE64 = self.img_to_BASE64(self.img_src)
        request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
        post_data = {
            "image": img_BASE64,
            "image_type": "BASE64",
            "face_field": "gender,age,beauty,gender,race,expression",
            "face_type": "LIVE"
        }
        access_token = self.get_accessToken()
        request_url = request_url + "?access_token=" + '24.01501b97890ac0c45d0435b0d32971f4.2592000.1547123865.282335-14922520'
        print(request_url)
        response = requests.post(url=request_url, data=post_data, headers=self.headers)
        json_result = json.loads(response.text)
        pprint.pprint(json_result)
        if json_result['error_msg'] != 'pic not has face':
            #print(json_result['result'])
            print("图片中包含人脸数:", json_result['result']['face_num'])
            print("图片中包含人物年龄:", json_result['result']['face_list'][0]['age'])
            print("图片中包含人物颜值评分:", json_result['result']['face_list'][0]['beauty'])
            print("图片中包含人物性别:", json_result['result']['face_list'][0]['gender']['type'])
            print("图片中包含人物种族:", json_result['result']['face_list'][0]['race']['type'])
            print("图片中包含人物表情:", json_result['result']['face_list'][0]['expression']['type'])

if __name__ == '__main__':
    img_src = input('请输入需要检测的本地图片路径:')
    baiduDetect = BaiduPicIndentify(img_src)
    baiduDetect.detect_face()
#mayun.jpg
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值