调用百度人脸识别接口实现人脸识别
目标:
1.学习使用百度AI开放平台进行人脸识别
2.将学到的内容:JSON数据,HTTP API调用,base64图片编码与解码
import jsonimport requestsapi1 = "/oauth/2.0/token?grant_type=client_credentials&client_id=lVfov6E1oaWZR9f4qIhd9Hjy&client_secret=Gubrc6RnMTdA3Eb8WumHIGrz4vHgCTdy"api2 = "/rest/2.0/face/v3/match?access_token="# 1. 读取图片数据def get_img(img1, img2):import base64with open(img1, "rb") as f:pic1 = f.read()with open(img2, "rb") as f:pic2 = f.read()params = json.dumps([{"image": str(base64.b64encode(pic1), "utf-8"), "image_type": "BASE64", "face_type": "LIVE", "quality_control": "LOW"},{"image": str(base64.b64encode(pic2), "utf-8"), "image_type": "BASE64", "face_type": "IDCARD","quality_control": "LOW"},])return params# 2. 获取token值 拼接APIdef get_token():response = requests.get(api1)access_token = eval(response.text)['access_token']api_url = api2 + access_tokenreturn api_url# 3. 请求API拿到最终结果def than_img(img1, img2):api_url = get_token()params = get_img(img1, img2)content = requests.post(api_url, params).textscore = eval(content)['result']['score']if score > 80:print("图片相似度:" + str(score) + ",同一个人")else:print("图片相似度:" + str(score) + ",不是同一个人")img1="D:\document\mayun1.jpeg"img2="D:\document\mayun2.jpg"img3="D:\document\image2.jpg"than_img(img1, img3)