Hello 大家好妹笆,2018春節(jié)這么快就過去了,祝大家新年快樂啦娜氏, 新年新氣象拳缠,新的一年就要搞一點不一樣的東西!C趁帧窟坐!每個人都有一些屬于自己的秘密,所以想著可以借助目前比較火的人臉識別來做一個安全系統(tǒng)。當然哲鸳,基于此人臉識別系統(tǒng)還可以實現(xiàn)人臉簽到臣疑、人臉閘機等等多種功能,就看你的想象力了徙菠,比如給你的電腦上鎖讯沈,每隔一段時間拍一張照,如果不是你本人就自動鎖定系統(tǒng)等等……
基本的原理就是首先創(chuàng)建一個人臉庫婿奔,將各個用戶上傳到不同的用戶組缺狠,來設定所擁有的不同權(quán)限,創(chuàng)建人臉庫的時候首先要為每個用戶上傳人臉照片萍摊,在上傳過程中還要檢測上傳照片的質(zhì)量挤茄,看是否合格。
人臉識別服務
現(xiàn)在是一個基于互聯(lián)網(wǎng)的時代冰木,因此我的想法是一切能夠在云端做的事情穷劈,絕不在本地運行,僅僅將樹莓派作為一個終端片酝,來連接各種服務,然后將這些服務呈現(xiàn)給你挖腰,這樣一是能夠保證本地的運行速率雕沿,畢竟樹莓派性能有限,識別一個照片需要兩三秒的時間就有些不優(yōu)雅了猴仑,二是容錯率較好审轮,一旦發(fā)生錯誤能更加方便的對其進行修正和重新部署。
因此本人采用了百度的人臉識別服務辽俗,目前百度的人臉識別主要提供三種功能:
接口名稱 | 接口能力簡要描述 |
---|---|
人臉檢測 | 檢測人臉并定位疾渣,返回五官關(guān)鍵點,及人臉各屬性值 |
人臉比對 | 返回兩兩比對的人臉相似值 |
人臉查找 | 在一個人臉集合中找到找到相似的人臉 |
人臉注冊 | 包括人臉識別崖飘、人臉認證榴捡、人臉庫管理相關(guān)接口 |
安裝人臉識別 Python SDK
人臉識別 Python SDK目錄結(jié)構(gòu)
├── README.md
├── aip //SDK目錄
│ ├── _init_.py //導出類
│ ├── base.py //aip基類
│ ├── http.py //http請求
│ └── face.py //人臉識別
└── setup.py //setuptools安裝
支持Python版本:2.7.+ ,3.+
安裝使用Python SDK有如下方式:
已安裝pip :執(zhí)行pip install baidu-aip即可朱浴。
已安裝setuptools〉趸:執(zhí)行python setup.py install即可。
新建AipFace
AipFace是人臉識別的Python SDK客戶端翰蠢,為使用人臉識別的開發(fā)人員提供了一系列的交互方法项乒。
參考如下代碼新建一個AipFace:
from aip import AipFace
""" 你的 APPID AK SK """
APP_ID = '你的 App ID'
API_KEY = '你的 Api Key'
SECRET_KEY = '你的 Secret Key'
client = AipFace(APP_ID, API_KEY, SECRET_KEY)
在上面代碼中,常量APP_ID在百度云控制臺中創(chuàng)建梁沧,常量API_KEY與SECRET_KEY是在創(chuàng)建完畢應用后檀何,系統(tǒng)分配給用戶的,均為字符串,用于標識用戶频鉴,為訪問做簽名驗證栓辜,可在AI服務控制臺中的應用列表中查看。
接口說明
人臉檢測
- 檢測請求圖片中的人臉砚殿,返回人臉位置啃憎、72個關(guān)鍵點坐標、及人臉相關(guān)屬性信息似炎。
- 檢測響應速度辛萍,與圖片中人臉數(shù)量相關(guān),人臉數(shù)量較多時響應時間會有些許延長羡藐。
- 典型應用場景:如人臉屬性分析贩毕,基于人臉關(guān)鍵點的加工分析,人臉營銷活動等仆嗦。
核心代碼
""" 讀取圖片 """
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
image = get_file_content('example.jpg')
""" 可選參數(shù) """
##################################################################################
##################################################################################
##################################################################################
##################################################################################
#其中有以下可選參數(shù)
#max_face_num :最多處理人臉數(shù)目
#face_fields :可定制一些返回的信息辉阶,包括(age,beauty,expression,faceshape,gender,glasses,landmark,race,qualities)
##################################################################################
##################################################################################
##################################################################################
##################################################################################
options = {}
options["max_face_num"] = 2
options["face_fields"] = "age"
""" 帶參數(shù)調(diào)用人臉檢測 """
client.detect(image, options)
人臉檢測 返回示例
{
"result_num": 1,
"result": [
{
"location": {
"left": 117,
"top": 131,
"width": 172,
"height": 170
},
"face_probability": 1,
"rotation_angle": 2,
"yaw": -0.34859421849251,
"pitch": 2.3033397197723,
"roll": 1.9135693311691,
"landmark": [
{
"x": 161.74819946289,
"y": 163.30244445801
},
...
],
"landmark72": [
{
"x": 115.86531066895,
"y": 170.0546875
},
...
],
"age": 29.298097610474,
"beauty": 55.128883361816,
"expression": 1,
"expression_probablity": 0.5543018579483,
"gender": "male",
"gender_probability": 0.99979132413864,
"glasses": 0,
"glasses_probability": 0.99999964237213,
"race": "yellow",
"race_probability": 0.99999976158142,
"qualities": {
"occlusion": {
"left_eye": 0,
"right_eye": 0,
"nose": 0,
"mouth": 0,
"left_cheek": 0.0064102564938366,
"right_cheek": 0.0057411273010075,
"chin": 0
},
"blur": 1.1886881756684e-10,
"illumination": 141,
"completeness": 1,
"type": {
"human": 0.99935841560364,
"cartoon": 0.00064159056637436
}
}
}
],
"log_id": 2493878179101621
}
質(zhì)量判斷
可通過人臉檢測接口瘩扼,基于以下字段和對應閾值谆甜,進行質(zhì)量檢測的判斷,以保證人臉質(zhì)量符合后續(xù)業(yè)務操作要求集绰。
人臉注冊
用于從人臉庫中新增用戶规辱,可以設定多個用戶所在組,及組內(nèi)用戶的人臉圖片栽燕。
人臉庫罕袋、用戶組、用戶碍岔、用戶下的人臉層級關(guān)系如下所示:
|- 人臉庫
|- 用戶組一
|- 用戶01
|- 人臉
|- 用戶02
|- 人臉
|- 人臉
....
....
|- 用戶組二
|- 用戶組三
....
關(guān)于人臉庫的設置限制
- 每個開發(fā)者賬號可以創(chuàng)建100個人臉庫,人臉庫互不相通浴讯;
- 每個人臉庫下,可以創(chuàng)建多個用戶組蔼啦,用戶組(group)數(shù)量沒有限制榆纽;
- 每個用戶組(group)下,可添加最多無限張人臉捏肢,無限個uid掠河;
- 每個用戶(uid)所能注冊的最大人臉數(shù)量沒有限制;
為了保證識別效果猛计,請控制注冊人臉的質(zhì)量,進行質(zhì)量判斷
核心代碼
uid = "user1"
userInfo = "user's info"
groupId = "group1,group2"
""" 讀取圖片 """
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
image = get_file_content('example.jpg')
""" 可選參數(shù) """
##################################################################################
##################################################################################
##################################################################################
##################################################################################
#其中有以下可選參數(shù)
#action_type :參數(shù)包含append唠摹、replace
#如果為“replace”,則每次注冊時進行替換replace(新增或更新)操作奉瘤,默認為append操作
##################################################################################
##################################################################################
##################################################################################
##################################################################################
options = {}
options["action_type"] = "replace"
""" 帶參數(shù)調(diào)用人臉注冊 """
client.addUser(uid, userInfo, groupId, image, options)
人臉識別
用于計算指定組內(nèi)用戶勾拉,與上傳圖像中人臉的相似度煮甥。識別前提為您已經(jīng)創(chuàng)建了一個人臉庫。
- 說明:人臉識別返回值不直接判斷是否是同一人藕赞,只返回用戶信息及相似度分值成肘。
- 說明:推薦可判斷為同一人的相似度分值為80,也可以根據(jù)自己需求選擇更合適的閾值斧蜕。
核心代碼
groupId = "group1,group2"
""" 讀取圖片 """
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
image = get_file_content('example.jpg')
##################################################################################
##################################################################################
##################################################################################
##################################################################################
#其中有以下可選參數(shù)
#ext_fields :特殊返回信息,目前支持faceliveness(活體檢測)
#user_top_num :返回用戶top數(shù)双霍,默認為1,最多返回5個
##################################################################################
##################################################################################
##################################################################################
##################################################################################
options = {}
options["ext_fields"] = "faceliveness"
options["user_top_num"] = 3
""" 帶參數(shù)調(diào)用人臉識別 """
client.identifyUser(groupId, image, options)
最終代碼
# -*- coding: UTF-8 -*-
'''
人臉模塊
'''
import uuid
from aip import AipFace
from prettytable import PrettyTable
from collections import Counter
""" APPID AK SK """
APP_ID = '10850801'
API_KEY = '4u4mTUmdVzeNoxBBN9YNEbEf'
SECRET_KEY = '4l4uDDOoor7DME7XBoH8Bx6Q1QY8GWhn '
client = AipFace(APP_ID, API_KEY, SECRET_KEY)
class FACE(object):
def get_file_content(self,file):
with open(file, 'rb') as fp:
return fp.read()
###################################
###################################
#############人臉注冊##############
###################################
###################################
def face_reg(self,name,filePath,groupId = "friends"):
global regist
uid = str(uuid.uuid3(uuid.NAMESPACE_DNS,name)).replace('-', '')
userInfo = name
""" 讀取圖片 """
image = self.get_file_content(filePath)
""" 參數(shù) """
options = {}
options["max_face_num"] = 2
options["face_fields"] = "face_probability,qualities,beauty"
""" 帶參數(shù)調(diào)用人臉檢測 """
quality = client.detect(image, options)
""" 人臉檢測結(jié)果 """
face_probability = quality['result'][0]['face_probability']
Blur = quality['result'][0]['qualities']['blur']
illumination = quality['result'][0]['qualities']['illumination']
completeness = quality['result'][0]['qualities']['completeness']
beauty = quality['result'][0]['beauty']
''' 打印照片評價指標 '''
table = PrettyTable(["上傳照片參數(shù)", "數(shù)據(jù)"])
table.add_row(["人臉可能性(0-1)", round(face_probability,2)])
table.add_row(["模糊度(0-1)", round(Blur,2)])
table.add_row(["照片亮度", round(illumination,2)])
table.add_row(["人臉完整度(0-1)", round(completeness,2)])
table.add_row(["顏值(0-100)", round(beauty,2)])
table.sort_key("數(shù)據(jù)")
table.reversesort = True
print(table)
if face_probability > 0.7 and Blur < 0.7 and illumination > 40 and completeness > 0.4 :
""" 調(diào)用人臉注冊 """
regist = client.addUser(uid, userInfo, groupId, image);
if str(regist).find("error_msg") != -1:
return regist["error_msg"]
else :
print ('圖片沒有通過檢測')
###################################
###################################
#############人臉對比##############
###################################
###################################
def face_comp(self,filePath,groupId = "friends"):
""" 讀取圖片 """
image = self.get_file_content(filePath)
""" 可選參數(shù) """
options = {}
options["ext_fields"] = "faceliveness"
options["user_top_num"] = 5
""" 帶參數(shù)調(diào)用人臉識別 """
face_comp = client.identifyUser(groupId, image, options)
""" 輸出對比結(jié)果 """
comp = face_comp['result']
return comp
###################################
###################################
#############多人識別##############
###################################
###################################
def faces_comp(self,filePath,groupId = "friends"):
""" 讀取圖片 """
image = self.get_file_content(filePath)
""" 可選參數(shù) """
options = {}
options["ext_fields"] = "faceliveness"
options["detect_top_num"] = 3
options["user_top_num"] = 2
""" 帶參數(shù)調(diào)用M:N 識別 """
faces_comp = client.multiIdentify(groupId, image, options)
return faces_comp
if __name__ == '__main__':
face = FACE()
#face.face_reg('李博','1.jpg')
print("與人臉庫中%s的匹配度為%.1f%%"%(face.face_comp('3.jpg')[0]["user_info"],face.face_comp('3.jpg')[0]["scores"][0]),sep='')
# print (face.face_comp('2.jpg'))