用python来作人脸识别代码量少 思路清晰,python
在使用以前咱们须要在咱们的配置的编译器中经过pip install baidu-aip 便可api
from aip import AipFace
就能够开始使用api了 咱们第一次接触这个东西不妨app
help(AipFace)
你就能够看到他所支持的功能。机器学习
在使用以前咱们须要在百度的后台建立应用。将咱们人脸都存放入库中。学习
其次咱们要了解一个概念,咱们要将本机中的图片与后台的人脸对比的话咱们须要将图片转成base64的字符串的格式url
import base64
f = open('./photo/mr.jpg', 'rb')
image = base64.b64encode(f.read())
image64 = str(image,'utf-8')
image_type = "BASE64"
固然咱们也能够将base64码转换成图片。spa
人脸检测的原理是经过机器学习转化提早图片人脸中的七十二个关键点。并进行其余的分析。rest
python3的代码为code
''' # 人脸检测与属性分析 ''' request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect" f = open('./photo/mr.jpg', 'rb') image = base64.b64encode(f.read()) image64 = str(image,'utf-8') image_type = "BASE64" # params = "{\"image\":\"%s\",\"image_type\":\"BASE64\",\"face_field\":\"faceshape,facetype\"}"%image64 params = {'image': image64,'image_type':"BASE64",'face_field': 'faceshape,facetype'} # 此处的faceshape和facetype须要本身加上去 更具本身须要的返回值 params = urllib.parse.urlencode(params).encode("utf-8") access_token = '[24.3941b86dfcbc8eaea432d11df4f6660d.2592000.1542368987.282335-14255146]' request_url = request_url + "?access_token=" + access_token request = urllib.request.urlopen(url=request_url, data=params) # 发送请求 content = request.read() # 将返回结果读取出来 print(content) # 显示返回结果 import urllib.request,sys,base64 import urllib.parse # 返回实例 a = {'error_code': 0, 'error_msg': 'SUCCESS', 'log_id': 1011018945051, 'timestamp': 1540301526, 'cached': 0, 'result': {'face_num': 1, 'face_list': [{'face_token': '80ed04e5e8771730b3fe240f8ead4e97', 'location': {'left': 564.6082764, 'top': 117.9681244, 'width': 263, 'height': 265, 'rotation': 1}, 'face_probability': 1, 'angle': {'yaw': -0.301689893, 'pitch': -15.59528351, 'roll': 0.9747127891 } } ] } }
具体各类属性请看百度文档 https://ai.baidu.com/docs#/Face-Detect-V3/topblog
介绍完人脸检测咱们就能够进行人脸对比了
import base64 from aip import AipFace '''新建aipface的配置''' ''' 你的 app id ak sk ''' AppId = '14255146' ApiKey = 'UoyrHmKFG3nGPL5HmDiGo80G' SecretKey = 'HUo1z36aDc1UxOwuS8d7Vxldh4GsQg8l' client = AipFace(AppId, ApiKey, SecretKey) f = open('./photo/huge.jpg', 'rb') image = base64.b64encode(f.read()) image64 = str(image,'utf-8') image_type = "BASE64" print(client.detect(image64, image_type)) # 此处的返回值为人脸的基本检测的数值效果 # print(strs) # 人脸检测 # image = str(strs) # 取决于image_type参数,传入BASE64字符串或URL字符串或FACE_TOKEN字符串 imageType = "BASE64" groupIdList = "17ai_1" """ 调用人脸搜索 """ print(client.search(str(image64), image_type, groupIdList)) # 将返回对比结果 ''' """ 若是有可选参数 """ options = {} options["quality_control"] = "NORMAL" options["liveness_control"] = "LOW" options["user_id"] = "233451" options["max_user_num"] = 3 """ 带参数调用人脸搜索 """ # print(client.search(image, imageType, , options)) # 人脸搜索返回例子 ''' face = { "face_token": "fid", "user_list": [ { "group_id": "test1", "user_id": "u333333", "user_info": "Test User", "score": 99.3 } ] }