python扫描人脸认证(百度接口)

2017-10-19  本文已影响1295人  siriusing

使用python-opencv拍照,并调用百度人脸识别接口来认证当前使用的用户。

准备:一个是需要成为百度开发者,一个是要安装opencv

思路:这里主要是先用cv来调用笔记本的摄像头拍个照,然后和预定的照片进行对比,得到相似度,如果相似度小于80,就调用win-api锁定电脑

# -*- coding:utf-8 -*-


import urllib, urllib2
import sys,ssl
import json, os
import time, base64
import cv2,ctypes


appid='你的appid'
appkey='appkey'
SecretKey='百度开发者那里找一下'


#获取百度接口调用需要的accesstoken
def getAccessToken():
    # 这里accessToken需要缓存在文件中以保证不频繁请求
    path='./accesstoeken'
    with open(path, 'r+') as f:
        
        content=f.read()
    
        if len(content)>10:
                        
            modifyTime=os.path.getmtime(path)
            nowTime=time.time()
            js=json.loads(content)

            if nowTime-modifyTime>js['expires_in']:
                print 'time out limit'
                #requist access token

            else:
                return js['access_token']

        #重新请求accesstoken
        host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+appkey+'&client_secret='+SecretKey
        request = urllib2.Request(host)
        request.add_header('Content-Type', 'application/json; charset=UTF-8')
        response = urllib2.urlopen(request)
        content = response.read()
        #持久化
        f.write(content)
        js=json.loads(content)
        return js['access_token']
    
# 检查人脸
def checkFace(path):

    request_url = "https://aip.baidubce.com/rest/2.0/face/v1/detect"

    # 二进制方式打开图片文件
    f = open(path, 'rb')
    img = base64.b64encode(f.read())

    params = {"face_fields":"age,beauty,expression,faceshape,gender,glasses,landmark,race,qualities","image":img,"max_face_num":5}
    params = urllib.urlencode(params)

    access_token = getAccessToken()
    request_url = request_url + "?access_token=" + access_token
    request = urllib2.Request(url=request_url, data=params)
    request.add_header('Content-Type', 'application/x-www-form-urlencoded')
    response = urllib2.urlopen(request)
    content = response.read()
    if content:
        return content

# standard_img 标准参照图
# refer_img 查询图
# filter_score 阀值
def faceMatch(standard_img,refer_img,filter_score):
    request_url = "https://aip.baidubce.com/rest/2.0/face/v2/match"

    f = open(standard_img, 'rb')
    # 参数images:图像base64编码
    img1 = base64.b64encode(f.read())
    # 二进制方式打开图文件
    f = open(refer_img, 'rb')
    # 参数images:图像base64编码
    img2 = base64.b64encode(f.read())

    # "ext_fields":"qualities","image_liveness":"faceliveness"
    params = {"images":img1 + ',' + img2}
    params = urllib.urlencode(params)


    access_token = getAccessToken()
    request_url = request_url + "?access_token=" + access_token
    request = urllib2.Request(url=request_url, data=params)
    request.add_header('Content-Type', 'application/x-www-form-urlencoded')
    response = urllib2.urlopen(request)
    content = response.read()

    if content:
        print content
        js=json.loads(content)

        score=js['result'][0]['score']
        # print score

        return score>filter_score

def capturePhoto(path):

    cap = cv2.VideoCapture(0)

    # while(1):
        # get a frame
    ret, frame = cap.read()
    # show a frame
    cv2.imshow("capture", frame)
    # if cv2.waitKey(1) & 0xFF == ord('q'):
    
    cv2.imwrite(path, frame)
    
    cap.release()
    cv2.destroyAllWindows()
    return path


authimg='myphoto.jpg'
checkimg='photo.jpg'
# 拍照
capturePhoto(checkimg)

# 如果两个脸相似度达到80分
if faceMatch(authimg,checkimg,80):
    print 'auth success'

else:
    # "调用WindowAPI锁定计算机"
    dll = ctypes.WinDLL('user32.dll');
    dll.LockWorkStation();
上一篇 下一篇

猜你喜欢

热点阅读