基于Python的百度AI人脸识别API接口(可用于OpenCV-Python人脸识别)
资源:
download.csdn.net/download/weixin_53403301/43644312
之前的项目:
【最新】基于OpenCV的Python人脸识别、检测、框选(遍历目录下所有照片依次识别 视频随时标注)
blog.csdn.net/weixin_53403301/article/details/119422635
基于OpenCV-Python的树莓派人脸识别及89C52单片机控制系统设计(指定照片进行识别、遍历目录下所有照片依次识别)
blog.csdn.net/weixin_53403301/article/details/118575731
直接上代码:
"""
Created on Mon May 31 23:40:16 2021
@author: ZHOU
"""
import requests
import os
import base64
import json
ACCESS_TOKEN = ''
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
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_LIST_URL = {
'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):
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:
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:
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()
testface = face(image=FA1, image2=FA2)
result_json = testface.postface()
result = result_json['result']['score']
print('人脸相似度:', result)
if result > 80:
print("人脸匹配成功!")
else:
print("人脸匹配失败!")
return '人脸相似度:' + str(result), result
快速版:
"""
Created on Mon May 31 23:40:16 2021
@author: ZHOU
"""
import requests
import os
import base64
import json
ACCESS_TOKEN = ''
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
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_LIST_URL = {
'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):
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:
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:
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()
testface = face(image=FA1, image2=FA2)
result_json = testface.postface()
result = result_json['result']['score']
print('人脸相似度:', result)
return '人脸相似度:' + str(result), result
py打包
Pyinstaller打包exe(包括打包资源文件 绝不出错版)
依赖包及其对应的版本号
PyQt5 5.10.1
PyQt5-Qt5 5.15.2
PyQt5-sip 12.9.0
pyinstaller 4.5.1
pyinstaller-hooks-contrib 2021.3
Pyinstaller -F setup.py 打包exe
Pyinstaller -F -w setup.py 不带控制台的打包
Pyinstaller -F -i xx.ico setup.py 打包指定exe图标打包
打包exe参数说明:
-F:打包后只生成单个exe格式文件;
-D:默认选项,创建一个目录,包含exe文件以及大量依赖文件;
-c:默认选项,使用控制台(就是类似cmd的黑框);
-w:不使用控制台;
-p:添加搜索路径,让其找到对应的库;
-i:改变生成程序的icon图标。
如果要打包资源文件
则需要对代码中的路径进行转换处理
另外要注意的是 如果要打包资源文件 则py程序里面的路径要从./xxx/yy换成xxx/yy 并且进行路径转换
但如果不打包资源文件的话 最好路径还是用作./xxx/yy 并且不进行路径转换
def get_resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
而后再spec文件中的datas部分加入目录
如:
a = Analysis(['cxk.py'],
pathex=['D:\\Python Test\\cxk'],
binaries=[],
datas=[('root','root')],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
而后直接Pyinstaller -F setup.spec即可
如果打包的文件过大则更改spec文件中的excludes 把不需要的库写进去(但是已经在环境中安装了的)就行
这些不要了的库在上一次编译时的shell里面输出
比如:
然后用pyinstaller --clean -F 某某.spec
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)