Django调用百度AI接口实现人脸注册登录代码实例


Posted in Python onApril 23, 2020

面部识别----考勤打卡、注册登录、面部支付等等...感觉很高大上,又很方便,下面用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, 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,username,mobile,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', function () {
        if (videoPlaying) {
          mycanvas = document.getElementById('canvas');
          mycanvas.width = v.videoWidth;
          mycanvas.height = v.videoHeight;
          mycanvas.getContext('2d').drawImage(v, 0, 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(),imagecontent:data},
            dataType:"json",
            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):
    return render(request,'moban_index.html')
  def post(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,imageType,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)})

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Linux下用Python脚本监控目录变化代码分享
May 21 Python
Python+django实现简单的文件上传
Aug 17 Python
python微信公众号开发简单流程
Mar 23 Python
对numpy中数组元素的统一赋值实例
Apr 04 Python
python 数字类型和字符串类型的相互转换实例
Jul 17 Python
python内置数据类型之列表操作
Nov 12 Python
基于Python安装pyecharts所遇的问题及解决方法
Aug 12 Python
python 扩展print打印文件路径和当前时间信息的实例代码
Oct 11 Python
python 实现多线程下载m3u8格式视频并使用fmmpeg合并
Nov 15 Python
Python超越函数积分运算以及绘图实现代码
Nov 20 Python
如何用用Python将地址标记在地图上
Feb 07 Python
python实现的人脸识别打卡系统
May 08 Python
Anaconda和ipython环境适配的实现
Apr 22 #Python
Django框架获取form表单数据方式总结
Apr 22 #Python
Anaconda的安装及其环境变量的配置详解
Apr 22 #Python
Tensorflow中的图(tf.Graph)和会话(tf.Session)的实现
Apr 22 #Python
Django实现图片上传功能步骤解析
Apr 22 #Python
Django框架配置mysql数据库实现过程
Apr 22 #Python
jupyter notebook 实现matplotlib图动态刷新
Apr 22 #Python
You might like
php注销代码(session注销)
2012/05/31 PHP
php获取文件内容最后一行示例
2014/01/09 PHP
PHP中你应该知道的require()文件包含的正确用法
2015/06/12 PHP
CodeIgniter基于Email类发邮件的方法
2016/03/29 PHP
PDO::inTransaction讲解
2019/01/28 PHP
laravel-admin自动生成模块,及相关基础配置方法
2019/10/08 PHP
jQuery实现控制文字内容溢出用省略号(…)表示的方法
2016/02/26 Javascript
基于jQuery插件实现点击小图显示大图效果
2016/05/11 Javascript
BootStrap网页中代码显示用法详解
2016/10/21 Javascript
超全面的javascript中变量命名规则
2017/02/09 Javascript
Bootstrap Table使用整理(一)
2017/06/09 Javascript
jQuery实现切换隐藏与显示同时切换图标功能
2017/10/29 jQuery
超详细动手搭建一个VuePress 站点及开启PWA与自动部署的方法
2019/01/27 Javascript
JS关闭子窗口并且刷新上一个窗口的实现示例
2020/03/10 Javascript
js实现简单点赞操作
2020/03/17 Javascript
[33:17]OG vs VGJ.T 2018国际邀请赛小组赛BO2 第二场 8.18
2018/08/19 DOTA
Python ORM框架SQLAlchemy学习笔记之安装和简单查询实例
2014/06/10 Python
python实现随机梯度下降法
2020/03/24 Python
解决Python运行文件出现out of memory框的问题
2018/12/03 Python
解决Python中定时任务线程无法自动退出的问题
2019/02/18 Python
django ModelForm修改显示缩略图 imagefield类型的实例
2019/07/28 Python
Python数据可视化 pyecharts实现各种统计图表过程详解
2019/08/15 Python
解决Django连接db遇到的问题
2019/08/29 Python
通过 Django Pagination 实现简单分页功能
2019/11/11 Python
Pytorch 使用CNN图像分类的实现
2020/06/16 Python
html5 canvas里绘制椭圆并保持线条粗细均匀的技巧
2013/03/25 HTML / CSS
Java程序员面试90题
2013/10/19 面试题
肯尼迪就职演说稿
2013/12/31 职场文书
学生会主席演讲稿
2014/04/25 职场文书
2015年派出所工作总结
2015/04/24 职场文书
2016春季幼儿园开学寄语
2015/12/03 职场文书
运动会班级口号霸气押韵
2015/12/24 职场文书
先进基层党组织事迹材料2016
2016/02/29 职场文书
linux下导入、导出mysql数据库命令的实现方法
2021/05/26 MySQL
MySQL命令无法输入中文问题的解决方式
2021/08/30 MySQL
Linux在两个服务器直接传文件的操作方法
2022/08/05 Servers