day09 tornado人脸识别系统技术的实现

通过百度云的AI开放平台的接口来实现的ai的人脸识别

day09 tornado人脸识别系统技术的实现_第1张图片
image.png

安装环境:requirement.txt (pip install -r requirement.txt)

pymysql
sqlalchemy
tornado==4.5
baidu-aip

manage.py

import os
import tornado.web
import tornado.ioloop


from tornado.options import parse_command_line, options, define

from face.views import RegisterHandler, InitDbHandler, LogonHandler

define('port',default=80,type=int)



def make_app():
    return tornado.web.Application(handlers=[
        (r'/register/',RegisterHandler),
        (r'/init_db/', InitDbHandler),
        (r'/login/',LogonHandler)

    ],

    template_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'),
    static_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static'),
    )

if __name__ == '__main__':
    parse_command_line()
    app=make_app()
    app.listen(options.port)
    tornado.ioloop.IOLoop.current().start()

face/models.py

from datetime import datetime

from sqlalchemy import Column,Integer,String,DateTime

from untils.conn import Base

def init_db():
   Base.metadata.create_all()

class User(Base):
   id=Column(Integer,primary_key=True,autoincrement=True)
   username=Column(String(10), unique=True, nullable=False)
   realname = Column(String(10), unique=True, nullable=False)
   create_time = Column(DateTime, default=datetime.now)
   __tablename__ = 'user'

face/views.py


import tornado.web

from face.models import init_db, User
from untils.conn import Base, session
from untils.faceid import face_register, face_login


class RegisterHandler(tornado.web.RequestHandler):
    def get(self):
        error=''
        self.render('register.html', error=error)

    def post(self):
        #注册
        face=self.get_argument('face_img')

        img = face.split(',')[-1]
        username=self.get_argument('username')
        realname=self.get_argument('realname')
        if face and username and realname:
            #条用百度接口注册
            user=User()
            user.username = username
            user.realname = realname
            session.add(user)
            session.commit()

            res = face_register(img,user.id)
            if res:
                self.redirect('/login/')
            else:
                session.delete(user)
                session.commit()
                self.redirect('/register/')
        else:
            error = '请填写完整!'
            self.render('register.html', error=error)

class InitDbHandler(tornado.web.RequestHandler):
    def get(self):
        #将模型映射到数据库中
        #Base.metadata.create_all()
        init_db()
        self.write('创建表成功')
class LogonHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('login.html')

    def post(self):
        face = self.get_argument('face_img')
        img = face.split(',')[-1]
        res = face_login(img)
        if res:
            self.write('成功')
        else:
            self.write('失败')

static/js/ai.js


var video = document.querySelector('video');
var audio, audioType;

var canvas1 = document.getElementById('canvas1');
var context1 = canvas1.getContext('2d');



navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;

var exArray = []; //存储设备源ID
MediaStreamTrack.getSources(function (sourceInfos) {
    for (var i = 0; i != sourceInfos.length; ++i) {
        var sourceInfo = sourceInfos[i];
        //这里会遍历audio,video,所以要加以区分
        if (sourceInfo.kind === 'video') {
            exArray.push(sourceInfo.id);
        }
    }
});

function getMedia() {
    if (navigator.getUserMedia) {
        navigator.getUserMedia({
            'video': {
                'optional': [{
                    'sourceId': exArray[1] //0为前置摄像头,1为后置
                }]
            },
            'audio':true
        }, successFunc, errorFunc);    //success是获取成功的回调函数
    }
    else {
        alert('Native device media streaming (getUserMedia) not supported in this browser.');
    }
}

function successFunc(stream) {
    //alert('Succeed to get media!');
    if (video.mozSrcObject !== undefined) {
        //Firefox中,video.mozSrcObject最初为null,而不是未定义的,我们可以靠这个来检测Firefox的支持
        video.mozSrcObject = stream;
    }
    else {
        video.src = window.URL && window.URL.createObjectURL(stream) || stream;
    }

    //video.play();

    // 音频
    audio = new Audio();
    audioType = getAudioType(audio);
    if (audioType) {
        audio.src = 'polaroid.' + audioType;
        audio.play();
    }
}
function errorFunc(e) {
    alert('Error!'+e);
}

//获取音频格式
function getAudioType(element) {
    if (element.canPlayType) {
        if (element.canPlayType('audio/mp4; codecs="mp4a.40.5"') !== '') {
            return ('aac');
        } else if (element.canPlayType('audio/ogg; codecs="vorbis"') !== '') {
            return ("ogg");
        }
    }
    return false;
}

//拍照
function getPhoto() {
    context1.drawImage(video, 0, 0,220,220); //将video对象内指定的区域捕捉绘制到画布上指定的区域,实现拍照。
    var face = $('#face')
    var canvas1 = document.getElementById('canvas1');
    face.val(canvas1.toDataURL('image/png'))
}

templates/login.html(登陆界面)




    
    登录
    



    
    
    
    
    

templates/register.html(注册界面)




    
    注册
    



    
    
    
    
    

账号:

真实姓名:

untils/conn.py


from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# 连接数据库格式
# mysql+pymysql://root:[email protected]:3306/tornado9
db_url = 'mysql+pymysql://root:[email protected]:3306/tornado9'

# 创建引擎,建立连接
engine = create_engine(db_url)

# 模型与数据库表进行关联的基类,模型必须继承于Base
Base = declarative_base(bind=engine)

# 创建session会话
DbSession = sessionmaker(bind=engine)
session = DbSession()

untils/faceid.py

from aip import AipFace

""" 你的 APPID AK SK """
APP_ID = '15752252'
API_KEY = 'IwwxkcwUr6TBUYCfhCHD97e4'
SECRET_KEY = 'fKyhxKGR6P1XlP6iXfGzlVajagViHdgt'

client = AipFace(APP_ID, API_KEY, SECRET_KEY)

def face_register(image,userId,imageType='BASE64',groupId='user'):

    res = client.addUser(image, imageType,groupId,userId)
    if res['error_code']:
        return False
    return True
def face_login(image, imageType = 'BASE64', groupId = 'user'):
    res = client.search(image,imageType,groupId)
  #  print(res)
    if res['error_code']:
        return False
    return True


你可能感兴趣的:(day09 tornado人脸识别系统技术的实现)