欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

百度AI人脸识别接口调用示例(基于python)

程序员文章站 2024-02-04 13:18:46
前言:百度AI平台的人脸检测和人脸搜索这两个接口是可以免费调用的,因此非常值得学习。人脸检测:首先需要在百度AI的控制台建立应用,获取API Key和Secret Key基于API的调用:# encoding:utf-8import requestsimport base64from urllib.parse import urlencodeimport urllibdef getAccess_token(AK,SK): host = "https://ai....

前言:

百度AI平台的人脸检测和人脸搜索这两个接口是可以免费调用的,因此比较值得学习。

人脸检测:

首先需要在百度AI的控制台建立应用,获取API KeySecret Key,下面只呈现代码,参数、请求要求等详细信息可以参考百度AI官网技术文档

百度AI人脸识别接口调用示例(基于python)

 基于API的调用:

# encoding:utf-8

import requests
import base64
from urllib.parse import urlencode
import urllib

def getAccess_token(AK,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:
        dict=response.json()
        access_token=dict.get("access_token","none")
        #print(dict.get("access_token","none"))
    return access_token

def Base64(img_path):
    with open(img_path, 'rb') as f:
        image_data = f.read()
        base64_data = base64.b64encode(image_data)  # base64编码
        string=str(base64_data,"utf-8")
        # print(string)
    return string

def request_post(base64_code,access_token):
    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
    params={'image':''+base64_code+'','image_type':'BASE64','face_field':'age,beauty,faceshape,gender,glasses'}
    params=urlencode(params)
    request_url = request_url + "?access_token=" + access_token
    request = urllib.request.Request(url=request_url,data=params.encode("utf-8"))
    request.add_header('Content-Type', 'application/json')
    response = urllib.request.urlopen(request)
    content = response.read()
    return content

if __name__ == "__main__":
    AK="qdfasgdagsdeZ1GfiW0HYv1mK"
    SK="sdgaehyerhewi1WL6v5tjnXm"
    img_path = 'C:/Users/Desktop/dsfas.jpg'
    # print(Base64(img_path))
    base64_code = Base64(img_path)
    access_token=getAccess_token(AK,SK)
    data_set=request_post(base64_code,access_token)
    print(data_set)
   

返回结果:

{
    'error_code': 0, 
    'error_msg': 'SUCCESS',
     'log_id': 11014555848, 
     'timestamp': 1595553710, 
     'cached': 0, 
     'result': 
     {
         'face_num': 1, 
         'face_list': 
         [
             {
                'face_token': 'df6100a11a22226a7057c2ef3d6057a5', 
                'location': 
                  {
                    'left': 34.63, 
                    'top': 118.53, 
                    'width': 89, 
                    'height': 83, 
                    'rotation': -10
                  }, 
                'face_probability': 1,
                'angle': 
                    {
                    'yaw': 2.95, 
                    'pitch': 20.88, 
                    'roll': -13.98
                    }, 
                'liveness': 
                   {
                    'livemapscore': 0.97
                    },
                'beauty': 79.47
                }
                ]
                }
            }

基于SDK的调用:

       基于SDK的调用首先需要安装相应的python库

安装使用Python SDK有如下方式:

如果已安装pip,执行pip install baidu-aip即可。
如果已安装setuptools,执行python setup.py install即可。



人脸识别 Python SDK目录结构

├── README.md
├── aip                   //SDK目录
│   ├── __init__.py       //导出类
│   ├── base.py           //aip基类
│   ├── http.py           //http请求
│   └── face.py //人脸识别
└── setup.py              //setuptools安装
import base64
from aip import AipFace


global string
#""" 你的 APPID AK SK """
APP_ID = '14547822'
API_KEY = 'qTfhshYv1mK'
SECRET_KEY = 'UHuhdfyhwerhhi1WL6v5tjnXm'
client = AipFace(APP_ID, API_KEY, SECRET_KEY)

img_path = 'C:/Users/Desktop/dsfas.jpg'
with open(img_path, 'rb') as f:
    image_data = f.read()
    base64_data = base64.b64encode(image_data)  # base64编码
    string=str(base64_data,"utf-8")
    # print(string)    
image = string
imageType = "BASE64"

options = {}
options["max_face_num"] = 2
options["face_type"] = "LIVE"
options["liveness_control"] = "LOW"
options["face_field"] = "age,beauty,emotion,glasses,race,face_shape,gender"

dict_data=client.detect(image, imageType, options)#返回数据类型为字典
#print(dict_data)

#对返回结果进行处理并输出

dict_data2=dict_data.get("result","none")
dict_data3=dict_data2.get("face_list","none")
for i in dict_data3:
    for key,value in i.items():
        print(key,value)

输出处理后的结果:

location {'left': 34.63, 'top': 118.53, 'width': 89, 'height': 83, 'rotation': -10}
face_probability 1
angle {'yaw': 2.95, 'pitch': 20.88, 'roll': -13.98}
age 25
beauty 79.47
emotion {'type': 'neutral', 'probability': 0.85}
glasses {'type': 'none', 'probability': 1}
race {'type': 'yellow', 'probability': 1}
face_shape {'type': 'oval', 'probability': 0.66}
gender {'type': 'male', 'probability': 1}

人脸搜索:

     人脸搜索首先需要建立人脸库,然后才能进行以下两种搜索

  • 人脸搜索:也称为1:N识别,在指定人脸集合中,找到最相似的人脸;
  • 人脸搜索 M:N识别:也称为M:N识别,待识别图片中含有多个人脸时,在指定人脸集合中,找到这多个人脸分别最相似的人脸

1.建立人脸库:(详细信息可以参考技术文档

        基于API的调用:

# encoding:utf-8

import requests
import base64
from urllib.parse import urlencode
import urllib

#人脸库结构
# |- 人脸库(appid)
#    |- 用户组一(group_id)
#       |- 用户01(uid)
#          |- 人脸(faceid)
#       |- 用户02(uid)
#          |- 人脸(faceid)
#          |- 人脸(faceid)
#          ....
#        ....
#    |- 用户组二(group_id)
#    |- 用户组三(group_id)

# 人脸注册

def getAccess_token(AK,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:
        dict=response.json()
        access_token=dict.get("access_token","none")
        #print(dict.get("access_token","none"))
    return access_token

def Base64(img_path):
    with open(img_path, 'rb') as f:
        image_data = f.read()
        base64_data = base64.b64encode(image_data)  # base64编码
        string=str(base64_data,"utf-8")
        # print(string)
    return string

def request_post(base64_code,access_token):
    request_url="https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add"
    params={'image':''+base64_code+'','image_type':'BASE64','group_id':'group_1','user_id':'user_1','user_info':'图片2'}
    params=urlencode(params)
    request_url = request_url + "?access_token=" + access_token
    request = urllib.request.Request(url=request_url,data=params.encode("utf-8"))
    request.add_header('Content-Type', 'application/json')
    response = urllib.request.urlopen(request)
    content = response.read()
    return content

if __name__ == "__main__":
    AK="qTKX7fdhsGfiW0HYv1mK"
    SK="UHu5ydfgsdgfsdga5tjnXm"
    img_path = 'C:/Users/Desktop/dhglkj.jpg'
    # print(Base64(img_path))
    base64_code = Base64(img_path)
    access_token=getAccess_token(AK,SK)
    data_set=request_post(base64_code,access_token)
    print(data_set)
    #print(type(data_set))#<class 'bytes'>

# 查看人脸库列表

def getAccess_token(AK,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:
        dict=response.json()
        access_token=dict.get("access_token","none")
        #print(dict.get("access_token","none"))
    return access_token

def request_post(access_token):
    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/getlist"
    params={"user_id":"user_1","group_id":"group_1"}
    params=urlencode(params)
    request_url = request_url + "?access_token=" + access_token
    request = urllib.request.Request(url=request_url,data=params.encode("utf-8"))
    request.add_header('Content-Type', 'application/json')
    response = urllib.request.urlopen(request)
    content = response.read()
    return content

if __name__ == "__main__":
    AK="qTKX7mdafsfg0HYv1mK"
    SK="UHu5yYuQahn7L4fhasdfawv5tjnXm"
    access_token=getAccess_token(AK,SK)
    data_set=request_post(access_token)
    print(data_set)
    print(type(data_set))#<class 'bytes'>


#人脸删除

def getAccess_token(AK,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:
        dict=response.json()
        access_token=dict.get("access_token","none")
        #print(dict.get("access_token","none"))
    return access_token

def request_post(access_token):
    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/delete"
    params={"user_id":"user_2","group_id":"group_1","face_token":"df6100a11a22226a7057c2ef3d6057a5"}
    params=urlencode(params)
    request_url = request_url + "?access_token=" + access_token
    request = urllib.request.Request(url=request_url,data=params.encode("utf-8"))
    request.add_header('Content-Type', 'application/json')
    response = urllib.request.urlopen(request)
    content = response.read()
    return content

if __name__ == "__main__":
    AK="qTKX7sdfasdgYv1mK"
    SK="UHu5yYuQahrgagdL6v5tjnXm"
    access_token=getAccess_token(AK,SK)
    data_set=request_post(access_token)
    print(data_set)
    print(type(data_set))#<class 'bytes'>

基于SDK的调用:


import base64
from aip import AipFace

#人脸注册
global string

APP_ID = '1351822'
API_KEY = 'qTKrefhdfgsv1mK'
SECRET_KEY = 'UHejgfhjraf346v5tjnXm'
client = AipFace(APP_ID, API_KEY, SECRET_KEY)

img_path = 'C:/Users/Desktop/dsfas.jpg'
with open(img_path, 'rb') as f:
    image_data = f.read()
    base64_data = base64.b64encode(image_data)  # base64编码
    string=str(base64_data,"utf-8")
    # print(string)    
image = string
imageType = "BASE64"
groupId = "group_1"
userId = "user_1"

#client.addUser(image, imageType, groupId, userId);

options = {}
options["user_info"] = "user's info"
options["quality_control"] = "NORMAL"
options["liveness_control"] = "LOW"
options["action_type"] = "REPLACE"

print(client.addUser(image, imageType, groupId, userId, options))


#人脸删除

APP_ID = '3512822'
API_KEY = 'qTK235aswdtgsafiW0HYv1mK'
SECRET_KEY = 'UHrjtfgy568q3wfsdgGxPYhv5tjnXm'
client = AipFace(APP_ID, API_KEY, SECRET_KEY)
userId = "user_1"
groupId = "group_1"
faceToken = "60f228fddd57eae00cd14b97bc46b174"
#调用删除
print(client.faceDelete(userId, groupId, faceToken))

#人脸信息查询

APP_ID = '18436222'
API_KEY = 'qTKX7mrhjrtygg4567hgfGfiW0HYv1mK'
SECRET_KEY = 'UHurtjhtyk5673424xPYhi1WL6v5tjnXm'
client = AipFace(APP_ID, API_KEY, SECRET_KEY)

userId = "user_1"
groupId = "group_1"
print(client.getUser(userId, groupId))

返回结果:


#添加人脸图片 dsfas.jpg

b'{
    "error_code":0,
    "error_msg":"SUCCESS",
    "log_id":1565001553584,
    "timestamp":1595591257,
    "cached":0,
    "result":{
        "face_token":"df6100a11a22226a7057c2ef3d6057a5",
        "location":{
            "left":34.63,
            "top":118.53,
            "width":89,
            "height":83,
            "rotation":-10}}}'


#添加人脸图片 dsfas.jpg
b'{
    "error_code":0,
    "error_msg":"SUCCESS",
    "log_id":2584845545055,
    "timestamp":1595593206,
    "cached":0,"result":{
        "face_token":"1f92a58188cefd7e4a34ba40d05d1d53",
        "location":{
            "left":95.6,
            "top":129.77,
            "width":112,"height":108,
            "rotation":-1
            }
        }
 }'


#查看图片数据列表 user_1

b'{
    "error_code":0,
    "error_msg":"SUCCESS",
    "log_id":17565896520,
    "timestamp":1595593711,
    "cached":0,
    "result":{
        "face_list":[{
            "face_token":"df6100a11a22226a7057c2ef3d6057a5",
            "ctime":"2020-07-24 19:47:37"},
            {"face_token":"1f92a58188cefd7e4a34ba40d05d1d53",
            "ctime":"2020-07-24 20:20:06"}]}}'

#删除人脸图片


{
  "error_code": 0,  
  "log_id": 73473737,
}

2.人脸搜索:(详细信息可以参考技术文档

    基于SDK的调用:

from aip import AipFace 
import base64

global string
#""" 你的 APPID AK SK """
APP_ID = '1835822'
API_KEY = 'qergfdhGfiW435HYv1mK'
SECRET_KEY = 'UHu5yYujytk34Yhi1WL6v5tjnXm'

client = AipFace(APP_ID, API_KEY, SECRET_KEY)

img_path = 'C:/Users/Desktop/dsfas_test.jpg'

with open(img_path, 'rb') as f:
    image_data = f.read()
    base64_data = base64.b64encode(image_data)  # base64编码
    string=str(base64_data,"utf-8")
    # print(string)
    
image = string

imageType = "BASE64"

groupIdList = "group_1"

""" 调用人脸搜索 """
list1=client.search(image, imageType, groupIdList)
print(list1)

""" 如果有可选参数 """
options = {}
options["max_face_num"] = 3
options["match_threshold"] = 70
options["quality_control"] = "NORMAL"
options["liveness_control"] = "LOW"
options["user_id"] = "233451"
options["max_user_num"] = 3

""" 带参数调用人脸搜索 """
list2=client.search(image, imageType, groupIdList, options)
print(list2)

返回结果:

{
    'error_code': 0,
     'error_msg': 'SUCCESS', 
     'log_id': 2555001258499, 
     'timestamp': 1595593364, 
     'cached': 0, 
     'result': {
         'face_token': '7d3ae01110f614257a143b8821bb63ce', 
         'user_list': [{
             'group_id': 'group_1',
              'user_id': 'user_1', 
              'user_info': '图片2', 
              'score': 94.658317565918}]
              }
}

结束语:

调用百度AI开放接口可以快速便捷的为应用增加AI能力,对于有需求但又没有神经网络搭建、模型训练能力的人员来说是一种不错的选择。

本文地址:https://blog.csdn.net/weixin_42126140/article/details/107582755