日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人工智能 > pytorch >内容正文

pytorch

【API调用】人脸检测+人脸属性(旷视 / 百度)

發(fā)布時間:2024/1/8 pytorch 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【API调用】人脸检测+人脸属性(旷视 / 百度) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

  • 1 簡介
  • 2 曠視 face++
    • 2.1 注冊
      • [獲得 API Key](https://console.faceplusplus.com.cn/app/apikey/list)
    • 2.2 調(diào)用API(以人臉檢測為例)
      • 調(diào)用代碼
      • 將結(jié)果轉(zhuǎn)化為json
    • 2.3 API返回結(jié)果
      • keys
      • 結(jié)果demo
    • 2.3 異常
      • 連接超時
  • 3. 百度
    • 3.0 調(diào)用參考
    • 3.1 [創(chuàng)建應用](https://console.bce.baidu.com/ai/?_=1629876388503&fromai=1#/ai/face/app/list)
      • 獲得apikey / secrect-key
    • 3.2 調(diào)用代碼
      • 代碼需補充自己的信息
    • 3.3 結(jié)果

1 簡介

本文,基于曠視與百度API,調(diào)用獲得人臉檢測以及人臉屬性信息(年齡性別情緒種族等),
大批量調(diào)用時,本人實驗發(fā)現(xiàn)(約調(diào)用·3萬次)
曠視API的調(diào)用代碼簡單,耗時短(約100ms一次)
以上結(jié)論,因本人水平有限,僅限于本人實驗。

2 曠視 face++

  • 官網(wǎng)web-demo在線演示

2.1 注冊

獲得 API Key

  • 登錄曠視人工智能開放平臺,注冊后,在平臺內(nèi)申請API Key

2.2 調(diào)用API(以人臉檢測為例)

  • 人臉檢測-文檔
  • 人臉檢測-參考代碼
  • 調(diào)用速度:約100毫秒/次

調(diào)用代碼

需要填上以上信息才能用

  • key = “填上你的KEY”
    secret = “填上你的SECRET”
    filepath = r"本地圖片的路徑"
# -*- coding: utf-8 -*- import urllib.request import urllib.error import timehttp_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 serverresp = urllib.request.urlopen(req, timeout=5)# get responseqrcont = 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'))

將結(jié)果轉(zhuǎn)化為json

修改處

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

2.3 API返回結(jié)果

keys

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

結(jié)果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. 百度

  • https://ai.baidu.com/tech/face/detect
  • 調(diào)用性能:約20秒1次

3.0 調(diào)用參考

https://blog.csdn.net/cskywit/article/details/81540500

3.1 創(chuàng)建應用

獲得apikey / secrect-key

  • 文檔(人臉檢測)

其中client_id 為官網(wǎng)獲取的AcessKey, client_secret 為官網(wǎng)獲取的Secrectkey

# encoding:utf-8 import requests # client_id 為官網(wǎng)獲取的AK, client_secret 為官網(wǎng)獲取的SK host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【官網(wǎng)獲取的AK】&client_secret=【官網(wǎng)獲取的SK】' response = requests.get(host) if response:print(response.json())

3.2 調(diào)用代碼

首先需要獲得 access-token,

  • 見代碼def get_access_token(self):
  • 后續(xù)不需要執(zhí)行,注釋 access_token=baidu_faceDetect_api.get_access_token()

代碼需補充自己的信息

import requests import base64 import json import timeclass 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 為官網(wǎng)獲取的AK, client_secret 為官網(wǎng)獲取的SKhost = 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權(quán)限 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# 原文鏈接:https://blog.csdn.net/cskywit/article/details/81540500def 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_tokenresponse = 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("圖像品質(zhì):", json_result['result']['face_list'][0]['quality'])# 人臉旋轉(zhuǎn)角度參數(shù)# yaw 三維旋轉(zhuǎn)之左右旋轉(zhuǎn)角[-90(左), 90(右)]# pitch 三維旋轉(zhuǎn)之俯仰角度[-90(上), 90(下)]# roll 平面內(nèi)旋轉(zhuǎn)角[-180(逆時針), 180(順時針)]print("人臉旋轉(zhuǎn)角度參數(shù):", 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'])#左眼狀態(tài) [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 結(jié)果

  • 約20秒一次(也可能是我代碼有問題)

總結(jié)

以上是生活随笔為你收集整理的【API调用】人脸检测+人脸属性(旷视 / 百度)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。