基于Python的百度AI人脸识别API接口(可用于OpenCV-Python人脸识别)

Posted 光电Mike Zhou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于Python的百度AI人脸识别API接口(可用于OpenCV-Python人脸识别)相关的知识,希望对你有一定的参考价值。

基于Python的百度AI人脸识别API接口(可用于OpenCV-Python人脸识别)

资源:
https://download.csdn.net/download/weixin_53403301/43644312

之前的项目:
【最新】基于OpenCV的Python人脸识别、检测、框选(遍历目录下所有照片依次识别 视频随时标注)
https://blog.csdn.net/weixin_53403301/article/details/119422635

基于OpenCV-Python的树莓派人脸识别及89C52单片机控制系统设计(指定照片进行识别、遍历目录下所有照片依次识别)
https://blog.csdn.net/weixin_53403301/article/details/118575731

直接上代码:

# -*- coding: utf-8 -*-
"""
Created on Mon May 31 23:40:16 2021

@author: ZHOU
"""

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests # 调用 requests的HTTP协议库
import os # 调用os多操作系统接口库
import base64 # 调用base64编码库
import json # 调用javascript Object Notation数据交换格式
 
ACCESS_TOKEN = ''
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #去掉文件名,返回目录 
 
# ID,KEY的配置信息
INFO_CONFIG =  
    'ID': '15050553',
    'API_KEY': 'rlRrtRL5oRdXGh71jgg1OmyN',
    'SECRET_KEY': 'dK5TpuTAZn2nw5eVpspZLmF5Qs1Uu8A1'


"""
若API出错 则改为:

INFO_CONFIG =  
    'ID': '15050553',
    'API_KEY': 'rlRrtRL5oRdXGh71jgg1OmyN',
    'SECRET_KEY': 'dK5TpuTAZn2nw5eVpspZLmF5Qs1Uu8A1'


或:

INFO_CONFIG =  
    'ID': '15788358',
    'API_KEY': 'ohtGa5yYoQEZ8Try8lnL99UK',
    'SECRET_KEY': 'qaDjyuXkf5MZ28g5C8pwFngDZenhswC3'


"""

# URL配置
URL_LIST_URL = 
    # ACCESS_TOKEN_URL用于获取ACCESS_TOKEN, POST请求,
    #  grant_type必须参数,固定为client_credentials,client_id必须参数,应用的API Key,client_secre 必须参数,应用的Secret Key.
    'ACCESS_TOKEN_URL': 'https://aip.baidubce.com/oauth/2.0/token?' + 'grant_type=client_credentials&client_id=API_KEYS&client_secret=SECRET_KEYS&'.format(
        API_KEYS=INFO_CONFIG['API_KEY'], SECRET_KEYS=INFO_CONFIG['SECRET_KEY']),
    # 登入人脸识别机器学习库
    'FACE_PLATE': 'https://aip.baidubce.com/rest/2.0/face/v3/match',
 

 
 
class AccessTokenSuper(object):
    pass
 
 
class AccessToken(AccessTokenSuper): # 定义登陆API大类
    def getToken(self):
        accessToken = requests.post(url=URL_LIST_URL['ACCESS_TOKEN_URL']) #登入网址
        accessTokenJson = accessToken.json()
        if dict(accessTokenJson).get('error') == 'invalid_client':
            return '获取accesstoken错误,请检查API_KEY,SECRET_KEY是否正确!'
        return accessTokenJson
 
 
ACCESS_TOKEN = AccessToken().getToken()['access_token']
 
LICENSE_PLATE_URL = URL_LIST_URL['FACE_PLATE'] + '?access_token='.format(ACCESS_TOKEN)
 
 
class faceSuper(object):
    pass
 
 
class face(faceSuper): # 定义图像输入大类
 
    def __init__(self, image=None, image2=None): # 定义初始化函数
        self.HEADER = 
            'Content-Type': 'application/json; charset=UTF-8',
        
        if image is not None: 	# 没有图像1
            imagepath = os.path.exists(image)
            if imagepath == True:
                images = image
                with open(images, 'rb') as images:
                    img1 = base64.b64encode(images.read())
            else:
                print("图像1不存在")
                return
        if image2 is not None: 	# 没有图像2
            imagepath2 = os.path.exists(image2)
            if imagepath2 == True:
                images2 = image2
                with open(images2, 'rb') as images2:
                    img2 = base64.b64encode(images2.read())
            else:
                print("图像2不存在")
                return
        self.img = img1
        self.imgs = img2
        self.IMAGE_CONFIG1 = "image": str(img1, 'utf-8'), "image_type": "BASE64"
        self.IMAGE_CONFIG2 = "image": str(img2, 'utf-8'), "image_type": "BASE64"
        self.IMAGE_CONFIG = json.dumps([self.IMAGE_CONFIG1, self.IMAGE_CONFIG2])
 
    def postface(self):  # 定义从服务器进行数据获取函数
        if (self.img==None and self.imgs==None):
            return '图像不存在'
        face = requests.post(url=LICENSE_PLATE_URL, headers=self.HEADER, data=self.IMAGE_CONFIG)
        # 登陆服务器获取数据
        return face.json() 	# 输出结果
 
 
def facef(FA1, FA2): # 人脸识别逻辑函数
    testAccessToken = AccessToken() # 获取API配置
    testface = face(image=FA1, image2=FA2) # 赋值给图像输入大类
    result_json = testface.postface()  # 从服务器获取数据
    result = result_json['result']['score'] #输出结果
    print('人脸相似度:', result)
    if result > 80: # 识别结果大于80则成功
        print("人脸匹配成功!")        
#    if result < 20:
#        print("未检测到人脸!")
    else:
        print("人脸匹配失败!")
    return '人脸相似度:' + str(result), result # 输出字符串结果

快速版:

# -*- coding: utf-8 -*-
"""
Created on Mon May 31 23:40:16 2021

@author: ZHOU
"""

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests # 调用 requests的HTTP协议库
import os # 调用os多操作系统接口库
import base64 # 调用base64编码库
import json # 调用JavaScript Object Notation数据交换格式
 
ACCESS_TOKEN = ''
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #去掉文件名,返回目录 
 
# ID,KEY的配置信息
INFO_CONFIG =  
    'ID': '15050553',
    'API_KEY': 'rlRrtRL5oRdXGh71jgg1OmyN',
    'SECRET_KEY': 'dK5TpuTAZn2nw5eVpspZLmF5Qs1Uu8A1'


"""
若API出错 则改为:

INFO_CONFIG =  
    'ID': '15050553',
    'API_KEY': 'rlRrtRL5oRdXGh71jgg1OmyN',
    'SECRET_KEY': 'dK5TpuTAZn2nw5eVpspZLmF5Qs1Uu8A1'


或:

INFO_CONFIG =  
    'ID': '15788358',
    'API_KEY': 'ohtGa5yYoQEZ8Try8lnL99UK',
    'SECRET_KEY': 'qaDjyuXkf5MZ28g5C8pwFngDZenhswC3'


"""

# URL配置
URL_LIST_URL = 
    # ACCESS_TOKEN_URL用于获取ACCESS_TOKEN, POST请求,
    #  grant_type必须参数,固定为client_credentials,client_id必须参数,应用的API Key,client_secre 必须参数,应用的Secret Key.
    'ACCESS_TOKEN_URL': 'https://aip.baidubce.com/oauth/2.0/token?' + 'grant_type=client_credentials&client_id=API_KEYS&client_secret=SECRET_KEYS&'.format(
        API_KEYS=INFO_CONFIG['API_KEY'], SECRET_KEYS=INFO_CONFIG['SECRET_KEY']),
    # 登入人脸识别机器学习库
    'FACE_PLATE': 'https://aip.baidubce.com/rest/2.0/face/v3/match',
 

 
 
class AccessTokenSuper(object):
    pass
 
 
class AccessToken(AccessTokenSuper): # 定义登陆API大类
    def getToken(self):
        accessToken = requests.post(url=URL_LIST_URL['ACCESS_TOKEN_URL']) #登入网址
        accessTokenJson = accessToken.json()
        if dict(accessTokenJson).get('error') == 'invalid_client':
            return '获取accesstoken错误,请检查API_KEY,SECRET_KEY是否正确!'
        return accessTokenJson
 
 
ACCESS_TOKEN = AccessToken().getToken()['access_token']
 
LICENSE_PLATE_URL = URL_LIST_URL['FACE_PLATE'] + '?access_token='.format(ACCESS_TOKEN)
 
 
class faceSuper(object):
    pass
 
 
class face(faceSuper): # 定义图像输入大类
 
    def __init__(self, image=None, image2=None): # 定义初始化函数
        self.HEADER = 
            'Content-Type': 'application/json; charset=UTF-8',
        
        if image is not None: 	# 没有图像1
            imagepath = os.path.exists(image)
            if imagepath == True:
                images = image
                with open(images, 'rb') as images:
                    img1 = base64.b64encode(images.read())
            else:
                print("图像1不存在")
                return
        if image2 is not None: 	# 没有图像2
            imagepath2 = os.path.exists(image2)
            if imagepath2 == True:
                images2 = image2
                with open(images2, 'rb') as images2:
                    img2 = base64.b64encode(images2.read())
            else:
                print("图像2不存在")
                return
        self.img = img1
        self.imgs = img2
        self.IMAGE_CONFIG1 = "image": str(img1, 'utf-8'), "image_type": "BASE64"
        self.IMAGE_CONFIG2 = "image": str(img2, 'utf-8'), "image_type": "BASE64"
        self.IMAGE_CONFIG = json.dumps([self.IMAGE_CONFIG1, self.IMAGE_CONFIG2])
 
    def postface(self):  # 定义从服务器进行数据获取函数
        if (self.img==None and self.imgs==None):
            return '图像不存在'
        face = requests.post(url=LICENSE_PLATE_URL, headers=self.HEADER, data=self.IMAGE_CONFIG)
        # 登陆服务器获取数据
        return face.json() 	# 输出结果
 
 
def facef(FA1, FA2): # 人脸识别逻辑函数
    testAccessToken = AccessToken() # 获取API配置
    testface = face(image=FA1, image2=FA2) # 赋值给图像输入大类
    result_json = testface.postface()  # 从服务器获取数据
    result = result_json['result']['score'] #输出结果
    print('人脸相似度:', result)
#    if result > 80: # 识别结果大于80则成功
#        print("人脸匹配成功!")        
#    if result < 20:
#        print("未检测到人脸!")
#    else:
#        print("人脸匹配失败!")
    return '人脸相似度:' + str(result), result # 输出字符串结果

以上是关于基于Python的百度AI人脸识别API接口(可用于OpenCV-Python人脸识别)的主要内容,如果未能解决你的问题,请参考以下文章

借助百度云API进行人脸识别

基于百度AI开放平台的人脸识别及语音合成

图像识别—基于百度API的图像识别

基于百度AI人脸识别技术的Demo

附源码基于OpenCV的Python人脸识别

附源码基于OpenCV的Python人脸识别