文章目录

  • 1 简介
  • 2 旷视 face++
  • 2.1 注册
  • [获得 API Key](https://console.faceplusplus.com.cn/app/apikey/list)
  • 2.2 调用API(以人脸检测为例)
  • 调用代码
  • 将结果转化为json
  • 2.3 API返回结果
  • keys
  • 结果demo
  • 2.3 异常
  • 连接超时
  • 3. 百度
  • 3.0 调用参考
  • 3.1 [创建应用](https://console.bce.baidu.com/ai/?_=1629876388503&fromai=1#/ai/face/app/list)
  • 获得apikey / secrect-key
  • 3.2 调用代码
  • 代码需补充自己的信息
  • 3.3 结果


1 简介

本文,基于旷视与百度API,调用获得人脸检测以及人脸属性信息(年龄性别情绪种族等),

大批量调用时,本人实验发现(约调用·3万次

旷视API的调用代码简单,耗时短(约100ms一次)

以上结论,因本人水平有限,仅限于本人实验。

python 爬取天眼查企业信息 天眼查api接口调用_百度

2 旷视 face++

2.1 注册

获得 API Key

  • 登录旷视人工智能开放平台,注册后,在平台内申请API Key
  • python 爬取天眼查企业信息 天眼查api接口调用_python 爬取天眼查企业信息_03


2.2 调用API(以人脸检测为例)

调用代码

需要填上以上信息才能用

  • key = “填上你的KEY”
    secret = “填上你的SECRET”
    filepath = r"本地图片的路径"
# -*- coding: utf-8 -*-
import urllib.request
import urllib.error
import time

http_url = 'https://api-cn.faceplusplus.com/facepp/v3/detect'
key = "填上你的KEY"
secret = "填上你的SECRET"
filepath= r"本地图片的路径"

boundary = '----------%s' % hex(int(time.time() * 1000))
data = []
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="%s"\r\n' % 'api_key')
data.append(key)
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="%s"\r\n' % 'api_secret')
data.append(secret)
data.append('--%s' % boundary)
fr = open(filepath, 'rb')
data.append('Content-Disposition: form-data; name="%s"; filename=" "' % 'image_file')
data.append('Content-Type: %s\r\n' % 'application/octet-stream')
data.append(fr.read())
fr.close()
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="%s"\r\n' % 'return_landmark')
data.append('1')
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="%s"\r\n' % 'return_attributes')
data.append(
    "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus")
data.append('--%s--\r\n' % boundary)

for i, d in enumerate(data):
    if isinstance(d, str):
        data[i] = d.encode('utf-8')

http_body = b'\r\n'.join(data)

# build http request
req = urllib.request.Request(url=http_url, data=http_body)

# header
req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)

try:
    # post data to server
    resp = urllib.request.urlopen(req, timeout=5)
    # get response
    qrcont = resp.read()
    # if you want to load as json, you should decode first,
    # for example: json.loads(qrount.decode('utf-8'))
    print(qrcont.decode('utf-8'))
except urllib.error.HTTPError as e:
    print(e.read().decode('utf-8'))

将结果转化为json

修改处

# results=qrcont.decode('utf-8')
    results = json.loads(qrcont)

2.3 API返回结果

keys

dict_keys(['request_id', 'time_used', 'faces', 'image_id', 'face_num'])

结果demo

{
    "image_id": "Dd2xUw9S/7yjr0oDHHSL/Q==", 
    "request_id": "1470472868,dacf2ff1-ea45-4842-9c07-6e8418cea78b", 
    "time_used": 752, 
    "faces": [
        {
            "landmark": {
                "mouth_upper_lip_left_contour2": {
                    "y": 185, 
                    "x": 146
                }, 
                "contour_chin": {
                    "y": 231, 
                    "x": 137
                }, 
               .........省略关键点信息
                "right_eye_pupil": {
                    "y": 146, 
                    "x": 205
                }, 
                "mouth_upper_lip_bottom": {
                    "y": 195, 
                    "x": 159
                }
            }, 
            "attributes": {
                "gender": {
                    "value": "Female"
                }, 
                "age": {
                    "value": 21
                }, 
                "glass": {
                    "value": "None"
                }, 
                "headpose": {
                    "yaw_angle": -26.625063, 
                    "pitch_angle": 12.921974, 
                    "roll_angle": 22.814377
                }, 
                "smile": {
                    "threshold": 30.1, 
                    "value": 2.566890001296997
                }
            }, 
            "face_rectangle": {
                "width": 140, 
                "top": 89, 
                "left": 104, 
                "height": 141
            }, 
            "face_token": "ed319e807e039ae669a4d1af0922a0c8"
        }
    ],
	"face_num":1
}

2.3 异常

连接超时

CONCURRENCY_LIMIT_EXCEEDED

  • 以上错误是,官方对免费的用户请求频率有限制,估计访问频次 2-5次/秒

3. 百度

python 爬取天眼查企业信息 天眼查api接口调用_百度_04


3.1 创建应用

获得apikey / secrect-key

其中client_id 为官网获取的AcessKey, client_secret 为官网获取的Secrectkey

# encoding:utf-8
import requests 

# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【官网获取的AK】&client_secret=【官网获取的SK】'
response = requests.get(host)
if response:
    print(response.json())

3.2 调用代码

首先需要获得 access-token

  • 见代码def get_access_token(self):
  • 后续不需要执行,注释 access_token=baidu_faceDetect_api.get_access_token()

代码需补充自己的信息

import requests
import base64
import json
import time

class BaiduFaceDetec():
    def __init__(self):
        self.api_key='你的'
        self.secret_key = '你的'
        self.access_token='你的'
        self.headers = {'content-type': 'application/json'}
        # self.headers = {
        #     "Content-Type": "application/json; charset=UTF-8"
        # }

    def get_access_token(self):
        # client_id 为官网获取的AK, client_secret 为官网获取的SK
        host = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={self.api_key}&client_secret={self.secret_key}'
        response = requests.get(host)
        if response:
            # print(response.json())
            self.access_token=response.json()['access_token']
            print("finish get access_token")
            return self.access_token
        """
        {'refresh_token': xxx
         'expires_in': 2592000, 
         'session_key': xxx
         'access_token': xxxxx
         'scope': 'public brain_all_scope vis-faceverify_faceverify_h5-face-liveness vis-faceverify_FACE_V3 vis-faceverify_idl_face_merge vis-faceverify_FACE_EFFECT vis-faceverify_face_beauty vis-faceverify_face_feature_sdk wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test', 'session_secret': 'eef5ffe19217d25dff3c435ddda8468a'}
        """

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

    def get_face_attri(self,path,method="BASE64"):
        '''
        人脸检测与属性分析
        '''

        request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
        t0 = time.time()

        img_BASE64 = self.img_to_BASE64(path)
        t1 = time.time()
        # print("Time cost on one image {} s".format(t1 - t0))
        # print("img_BASE64",img_BASE64)
        post_data = {
            "image": img_BASE64,
            "image_type":method ,
            # "face_field": "gender,age,beauty,emotion,expression,faceshape,",
            "face_field": "quality,gender,age,beauty,gender,emotion,expression,eye_status,landmark,faceshape,",
            "face_type": "LIVE"
        }
        request_url = request_url + "?access_token=" + self.access_token
        response = requests.post(url=request_url, data=post_data, headers=self.headers)
        print(response.text)
        json_result = json.loads(response.text)
        print("detect_result:",json_result)

    
        if json_result['error_msg'] != 'pic not has face':
            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]['quality'])
 
                # 人脸旋转角度参数
                # yaw  三维旋转之左右旋转角[-90(左), 90(右)]
                # pitch 三维旋转之俯仰角度[-90(上), 90(下)]
                # roll 平面内旋转角[-180(逆时针), 180(顺时针)]
      
            print("人脸旋转角度参数:", json_result['result']['face_list'][0]['angle'])
            print("是否微笑:", json_result['result']['face_list'][0]['expression']) # 笑不笑
            # angry:愤怒 disgust:厌恶 fear:恐惧 happy:高兴 sad:伤心 surprise:惊讶 neutral:无表情 pouty: 撅嘴 grimace:鬼脸
            print("情绪如何", json_result['result']['face_list'][0]['emotion'])
            #左眼状态 [0,1]取值,越接近0闭合的可能性越大
            print("是否睁眼", json_result['result']['face_list'][0]['eye_status'])


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    t0=time.time()
    img_path=r'你的本地图片地址'
    baidu_faceDetect_api=BaiduFaceDetec()
    access_token=baidu_faceDetect_api.get_access_token()
    # print(access_token)
    baidu_faceDetect_api.get_face_attri(img_path)
    t1=time.time()
    print("Time cost on one image {} s".format(t1-t0))

3.3 结果

  • 约20秒一次(也可能是我代码有问题)

python 爬取天眼查企业信息 天眼查api接口调用_python_05