# /usr/local/bin/python3.7
# -*- coding: UTF-8 -*-
# 百度人脸识别
import json
import requests
# 调用一个借口API获取官网值: 对比图片的相识度
def get_token():
host = 'https://aip.baidubce.com/oauth/2.0/token'
host = host + '?grant_type=client_credentials'
host = host + '&client_id=你的KEY'
host = host + '&client_secret=你的SERCET'
content = requests.get(host).content.decode()
content = eval(content[:-1])
return content['access_token']
# 读取图片值的二进制数据
# 二进制方式打开图文件
def image_data(file1path, file2path):
import base64
with open(file1path, "rb") as f:
img1 = base64.b64encode(f.read())
with open(file2path, "rb") as f:
img2 = base64.b64encode(f.read())
params = json.dumps(
[{
"image": str(img1, "utf-8"),
"image_type": "BASE64",# BASE64 URL FACE_TOKEN
"face_type": "LIVE",# LIVE IDCARD WATERMARK CERT
"quality_control": "LOW"# NONE LOW NORMAL HIGH
}, {
"image": str(img2, "utf-8"),
"image_type": "BASE64",
"face_type": "IDCARD",
"quality_control": "LOW"
}]
)
return params
# 进行对比获得结果
def image_result(file1path, file2path):
print("正在调用人脸识别......")
token = get_token()
print('正在解析人脸图像......')
params = image_data(file1path, file2path)
request_url = 'https://aip.baidubce.com/rest/2.0/face/v3/match'
request_url = request_url + '?access_token=' + token
# 返回数据结果 score
headers = {"Content-Type": "application/json"}
content = requests.post(request_url, data=params, headers=headers).content
if json.loads(content)['result'] is None:
return "图片错误:%s " % json.loads(content)['error_msg']
else:
content = eval(content)
score = content['result']['score']
if score > 80:
return "照片相似度:" + str(score) + ',同一个人'
else:
return "照片相似度:" + str(score) + ',不是同一个人'
if __name__ == "__main__":
print(image_result("1125/mayunershi.png", "1125/xiaomayun.png"))