django--调用百度AI接口实现人脸注册登录

面部识别----考勤打卡、注册登录、面部支付等等...感觉很高大上,又很方便,下面用python中的框架--django完成一个注册登录的功能,调用百度AI的接口,面部识别在网上也有好多教程,可以自己建模,训练模型,但是这都需要大量的数据去提高模型的准确度,我们直接用了百度AI的接口,十分的快捷、高效、准确,下来码一下代码啦!!

首先需要在百度AI官网注册一个应用,免费,并提供强大的人脸库。

  1.注册表单 

                                  <div class="tab-content">
                                        <div class="tab-content-inner active" data-content="signup">
                                            <!-- <form action="{% url ‘regist‘ %}" method="POST"> -->
                                                <div class="row form-group">
                                                    <div class="col-md-12">
                                                        <input type="text" class="form-control" id="username" placeholder="用户名">
                                                    </div>
                                                </div>
                                                <div class="row form-group">
                                                    <div class="col-md-12">
                                                        <input type="text" class="form-control" id="mobile" placeholder="手机号">
                                                    </div>
                                                </div>
                                                <div class="row form-group">
                                                    <div class="col-md-12">
                                                        <input type="password" class="form-control" id="password" placeholder="密码">
                                                    </div>
                                                </div>
                                                <div class="row form-group">
                                                        <div class="col-md-12">
                                                            <!-- <input type="text" class="form-control" id="mobile_code" placeholder="验证码">
                                                            <input type="button" value=" 获取验证码" id="zphone"> -->
                                                        </div>
                                                </div>
                                                <div class="row form-group">
                                                    <div class="col-md-12">
                                                        <label for="password2"><font color=‘green‘>新用户点击注册会有面部特征收集哦!</font></label>
                                                    </div>
                                                </div>

                                                <div class="row form-group">
                                                    <div class="col-md-12">
                                                        <input type="submit" class="btn btn-primary" value="注册" id="regist">
                                                    </div>
                                                </div>
                                            <!-- </form>     -->
                                        </div>

   2.注册时调用摄像头,ajax封装给后端的数据

    <!-- jQuery -->
    <script src="../static/assets/js/jquery.min.js"></script>
    <!-- jQuery Easing -->
    <script src="../static/assets/js/jquery.easing.1.3.js"></script>
    <!-- Bootstrap -->
    <script src="../static/assets/js/bootstrap.min.js"></script>
    <!-- Waypoints -->
    <script src="../static/assets/js/jquery.waypoints.min.js"></script>
    <!-- Carousel -->
    <script src="../static/assets/js/owl.carousel.min.js"></script>
    <!-- countTo -->
    <script src="../static/assets/js/jquery.countTo.js"></script>
    <!-- Magnific Popup -->
    <script src="../static/assets/js/jquery.magnific-popup.min.js"></script>
    <script src="../static/assets/js/magnific-popup-options.js"></script>
    <!-- Main -->
    <script src="../static/assets/js/main.js"></script>


<script> !(function () { // 老的浏览器可能根本没有实现 mediaDevices,所以我们可以先设置一个空的对象 if (navigator.mediaDevices === undefined) { navigator.mediaDevices = {}; } if (navigator.mediaDevices.getUserMedia === undefined) { navigator.mediaDevices.getUserMedia = function (constraints) { // 首先,如果有getUserMedia的话,就获得它 var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; // 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口 if (!getUserMedia) { return Promise.reject(new Error(‘getUserMedia is not implemented in this browser‘)); } // 否则,为老的navigator.getUserMedia方法包裹一个Promise return new Promise(function (resolve,reject) { getUserMedia.call(navigator,constraints,resolve,reject); }); } } const constraints = { video: true,audio: false }; videoPlaying = false; v = document.getElementById(‘v‘); promise = navigator.mediaDevices.getUserMedia(constraints); promise.then(stream => { // 旧的浏览器可能没有srcObject if ("srcObject" in v) { v.srcObject = stream; } else { // 防止再新的浏览器里使用它,应为它已经不再支持了 v.src = window.URL.createObjectURL(stream); } v.onloadedmetadata = function (e) { v.play(); videoPlaying = true; }; }).catch(err => { console.error(err.name + ": " + err.message); }) document.getElementById(‘regist‘).addEventListener(‘click‘,function () { if (videoPlaying) { mycanvas = document.getElementById(‘canvas‘); mycanvas.width = v.videoWidth; mycanvas.height = v.videoHeight; mycanvas.getContext(‘2d‘).drawImage(v,0); // 图片数据转换成数组 data = mycanvas.toDataURL(‘image/webp‘); document.getElementById(‘photo‘).setAttribute(‘src‘,data); // ajax提交数据到后台 $.ajax({ type:"POST",url:‘http://127.0.0.1:8000/regist/‘,data:{username:$("#username").val(),mobile:$(‘#mobile‘).val(),password:$(‘#password‘).val(),mobile_code:$(‘#mobile_code‘).val(),imagecontent:data},dataType:"json",success:function(data){ alert(data.result) $(‘#resText‘).text(data[‘result‘]); if(data.code == 200){ window.location.href=‘http://127.0.0.1:8000/home/‘ }else{ alert(data.result); } } }) } },false);

  3.将已经注册的应用中的各种id和key贴上来

# 导入百度AI
from django.apps import AppConfig
from aip import AipFace
import json
# django内置事务
from django.db import transaction
# 导入状态码
from jyapp.ErrorCode import *  # 官网给出的状态码,通过pandas读出保存到

# 百度AI基本信息
class AppConfig(AppConfig):
    name = 
    APP_ID = ‘‘
    API_KEY = ‘‘
    SECRECT_KEY = ‘‘
    client = AipFace(APP_ID,API_KEY,SECRECT_KEY)
    client.setConnectionTimeoutInMillis(1000*5)
    client.setSocketTimeoutInMillis(1000*5)

  4.注册接口,按照接口文档传入必须的参数,手机验证码功能已在本文中注释掉,需要时自行百度。

# 注册
class Regist(View):
    def get(self,request):
        return render(request,moban_index.html)
    def post(self,request):
        # 获取前端数据
        imagecontent = request.POST.get(imagecontent)
        username = request.POST.get(username)
        mobile = request.POST.get(mobile)
        password = request.POST.get(password)
        # mobile_code = request.POST.get(‘mobile_code‘)
        # print(imagecontent,username,mobile,password,mobile_code)
        # mobile_code_right = request.session.get(‘message_code‘)
        if not all([imagecontent,password]):
            return JsonResponse({result:注册信息不能为空})
        # if mobile_code != mobile_code_right:
        #     return JsonResponse({‘result‘:‘请输入正确的验证码‘})
        else:
            # 验证该用户是否存在
            user = models.User.objects.filter(mobile=mobile)
            if user:
                return JsonResponse({result:该用户已存在,请直接登录})
            else:
                try:
                    # 引入事务
                    with transaction.atomic():   
                        # 分割字符串
                        base_data = imagecontent.split(,)[1]
                        # base64解码
                        base64_decode = base64.b64decode(base_data)
                        # 图片写入本地
                        with open(static/image/+mobile+.jpeg,wb) as f:
                            f.write(base64_decode)
                        # 添加到mysql数据库
                        models.User.objects.create(
                            imagecontent = static/image/+mobile+.jpeg,# 可以根据需求是否保存注册照片到数据库,也可以通过百度AI人脸库查看
                            username = username,mobile = mobile,password = password,)
                        imageType = BASE64
                        groupId = usergroup    # 自定义
                        userId = mobile
                        # 加入可选参数
                        options = {}
                        options[user_info] = username
                        options[quality_control] = NORMAL
                        options[liveness_control] = LOW
                        result = AppConfig.client.addUser(base_data,imageType,groupId,userId,options)
                        print(result)
                        error_code = result[error_code]
                        if isinstance(error_code,int) and error_code == 0:
                            request.session[mobile] = mobile
                            return JsonResponse({code:200,result:注册成功})
                            # return JsonResponse({‘result‘:‘注册成功‘})
                        else:
                            error = ErrorCode().getErrorInfo(error_code)
                            return JsonResponse({result:{}.format(error)})
                except:
                    return JsonResponse({result:注册失败})

  5.登录.html

                      <div class="tab-content-inner" data-content="login">
                                            <!-- <form action="{% url ‘login‘ %}" method="POST"> -->
                                                <div class="row form-group">
                                                    <div class="col-md-12">
                                                        <input type="text" class="form-control" id="mobile1" placeholder="请输入手机号">
                                                    </div>
                                                </div>
                                                <div class="row form-group">
                                                    <div class="col-md-12">
                                                        <input type="password" class="form-control" id="password1" placeholder="请输入密码">
                                                    </div>
                                                </div>

                                                <div class="row form-group">
                                                    <div class="col-md-12">
                                                        <input type="submit" class="btn btn-primary" value="密码登陆" id="login">
                                                        <input type="submit" class="btn btn-primary" value="人脸登陆" id="login_face">
                                                    </div>
                                                </div>
                                            <!-- </form>     -->
                                        </div>

 

   6.ajax封装登录信息

    document.getElementById(‘login_face‘).addEventListener(‘click‘,0);
                    data = mycanvas.toDataURL(‘image/webp‘);
                    document.getElementById(‘photo‘).setAttribute(‘src‘,data);

                    $.ajax({
                        type:"POST",url:‘http://127.0.0.1:8000/login_face/‘,data:{mobile:$(‘#mobile1‘).val(),success:function(data){
                            $(‘#resText‘).text(data[‘result‘]);
                            document.getElementById(‘photo‘).setAttribute(‘src‘,‘static/‘+data[‘point72src‘]);
                            console.log(data[‘point72src‘])
                            if(data.code == 200){
                                alert(data.result)
                                window.location.href=‘http://127.0.0.1:8000/idcard/‘
                            }else{
                                alert(data.result);
                            }
                        }
                    })
                }
            },false);

  7.人脸快速登录

class Login_face(View):
    def get(self,request):
        imagecontent = request.POST.get(imagecontent)
        mobile = request.POST.get(mobile)
        if not all([imagecontent,mobile]):
            return JsonResponse({code:100,result:登录信息不能为空})
        else:
            user = models.User.objects.filter(mobile=mobile)
            if not user:
                return JsonResponse({code:113,result:用户不存在})
            else:
                base_data = imagecontent.split(,)[1]
                imageType = BASE64
                groupIdList = usergroup
                # 加入可选参数
                options = {}
                options[max_user_num] = 1
                options[quality_control] = NORMAL
                options[liveness_control] = LOW
                # options[‘user_id‘] = mobile
                result = AppConfig.client.search(base_data,groupIdList,options)
                print(result)
                error_code = result[error_code]
                try:
                    user_id = result[result][user_list][0][user_id]
                    score = result[result][user_list][0][score]
                    if isinstance(error_code,int) and error_code == 0 and user_id == mobile and score >= 90:  
                        request.session[mobile] = mobile
                        return JsonResponse({code:200,result:快速登录成功})
                    else:
                        error = ErrorCode().getErrorInfo(error_code)
                        return JsonResponse({result:{}.format(error)})
                except:
                    error = ErrorCode().getErrorInfo(error_code)
                    return JsonResponse({result:{}.format(error)})

 

 

 

结束!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Python中的函数(二) 在上一篇文章中提到了Python中函数的定义和使用,在这篇文章里我们来讨论下关于函数的一些更深的话题。在学习C语言函数的时候,遇到的问题主要有形参实参的区别、参数的传递和改变、变量的作用域。同样在Python中,关于对函数的理解和使用也存在这些问题。下面来逐一讲解。一.函
Python中的字符串 可能大多数人在学习C语言的时候,最先接触的数据类型就是字符串,因为大多教程都是以&quot;Hello world&quot;这个程序作为入门程序,这个程序中要打印的&quot;Hello world&quot;就是字符串。如果你做过自然语言处理方面的研究,并且用Python
Python 面向对象编程(一) 虽然Python是解释性语言,但是它是面向对象的,能够进行对象编程。下面就来了解一下如何在Python中进行对象编程。一.如何定义一个类 在进行python面向对象编程之前,先来了解几个术语:类,类对象,实例对象,属性,函数和方法。 类是对现实世界中一些事物的封装,
Python面向对象编程(二) 在前面一篇文章中谈到了类的基本定义和使用方法,这只体现了面向对象编程的三大特点之一:封装。下面就来了解一下另外两大特征:继承和多态。 在Python中,如果需要的话,可以让一个类去继承一个类,被继承的类称为父类或者超类、也可以称作基类,继承的类称为子类。并且Pytho
Python中的函数(一) 接触过C语言的朋友对函数这个词肯定非常熟悉,无论在哪门编程语言当中,函数(当然在某些语言里称作方法,意义是相同的)都扮演着至关重要的角色。今天就来了解一下Python中的函数用法。一.函数的定义 在某些编程语言当中,函数声明和函数定义是区分开的(在这些编程语言当中函数声明
在windows下如何快速搭建web.py开发框架 用Python进行web开发的话有很多框架供选择,比如最出名的Django,tornado等,除了这些框架之外,有一个轻量级的框架使用起来也是非常方便和顺手,就是web.py。它由一名黑客所创建,但是不幸的是这位创建者于2013年自杀了。据说现在由
将Sublime Text 2搭建成一个好用的IDE 说起编辑器,可能大部分人要推荐的是Vim和Emacs,本人用过Vim,功能确实强大,但是不是很习惯,之前一直有朋友推荐SUblime Text 2这款编辑器,然后这段时间就试了一下,就深深地喜欢上这款编辑器了...
Python中的模块 有过C语言编程经验的朋友都知道在C语言中如果要引用sqrt这个函数,必须用语句&quot;#include&lt;math.h&gt;&quot;引入math.h这个头文件,否则是无法正常进行调用的。那么在Python中,如果要引用一些内置的函数,该怎么处理呢?在Python中
Python的基础语法 在对Python有了基础的认识之后,下面来了解一下Python的基础语法,看看它和C语言、java之间的基础语法差异。一.变量、表达式和语句 Python中的语句也称作命令,比如print &quot;hello python&quot;这就是一条语句。 表达式,顾名思义,是
Eclipse+PyDevʽjango+Mysql搭建Python web开发环境 Python的web框架有很多,目前主流的有Django、Tornado、Web.py等,最流行的要属Django了,也是被大家最看好的框架之一。下面就来讲讲如何搭建Django的开发环境。一.准备工作 需要下载的
在windows下安装配置Ulipad 今天推荐一款轻便的文本编辑器Ulipad,用来写一些小的Python脚本非常方便。 Ulipad下载地址: https://github.com/limodou/ulipad http://files.cnblogs.com/dolphin0520/u...
Python中的函数(三) 在前面两篇文章中已经探讨了函数的一些相关用法,下面一起来了解一下函数参数类型的问题。在C语言中,调用函数时必须依照函数定义时的参数个数以及类型来传递参数,否则将会发生错误,这个是严格进行规定的。然而在Python中函数参数定义和传递的方式相比而言就灵活多了。一.函数参数的
在Notepad++中搭配Python开发环境 Python在最近几年一度成为最流行的语言之一,不仅仅是因为它简洁明了,更在于它的功能之强大。它不仅能够完成一般脚本语言所能做的事情,还能很方便快捷地进行大规模的项目开发。在学习Python之前我们来看一下Python的历史由来,&quot;Pytho
Python中的条件选择和循环语句 同C语言、Java一样,Python中也存在条件选择和循环语句,其风格和C语言、java的很类似,但是在写法和用法上还是有一些区别。今天就让我们一起来了解一下。一.条件选择语句 Python中条件选择语句的关键字为:if 、elif 、else这三个。其基本形式如
关于raw_input( )和sys.stdin.readline( )的区别 之前一直认为用raw_input( )和sys.stdin.readline( )来获取输入的效果完全相同,但是最近在写程序时有类似这样一段代码:import sysline = sys.stdin.readline()
初识Python 跟学习所有的编程语言一样,首先得了解这门语言的编程风格和最基础的语法。下面就让我们一起来了解一下Python的编程风格。1.逻辑行与物理行 在Python中有逻辑行和物理行这个概念,物理行是指在编辑器中实际看到的一行,逻辑行是指一条Python语句。在Python中提倡一个物理行只
当我们的代码是有访问网络相关的操作时,比如http请求或者访问远程数据库,经常可能会发生一些错误,有些错误可能重新去发送请求就会成功,本文分析常见可能需要重试的场景,并最后给出python代码实现。
1.经典迭代器 2.将Sentence中的__iter__改成生成器函数 改成生成器后用法不变,但更加简洁。 3.惰性实现 当列表比较大,占内存较大时,我们可以采用惰性实现,每次只读取一个元素到内存。 或者使用更简洁的生成器表达式 4.yield from itertools模块含有大量生成器函数可
本文介绍简单介绍socket的常用函数,并以python-kafka中的源码socketpair为例,来讲解python socket的运用
python实践中经常出现编码相关的异常,大多网上找资料而没有理解原理,导致一次次重复错误。本文对常用Unicode、UTF-8、GB2312编码的原理进行介绍,接着介绍了python字符类型unicode和str以及常见编解码错误UnicodeEncodeError和UnicodeDEcodeEr