91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Django如何調用百度AI接口實現人臉注冊登錄

發布時間:2020-08-01 10:22:59 來源:億速云 閱讀:303 作者:小豬 欄目:開發技術

這篇文章主要講解了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, 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)})

看完上述內容,是不是對Django如何調用百度AI接口實現人臉注冊登錄有進一步的了解,如果還想學習更多內容,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

张家界市| 辽阳县| 镇巴县| 红安县| 吴堡县| 肃南| 曲沃县| 陆良县| 富蕴县| 灵丘县| 阿城市| 新源县| 通城县| 桃园县| 太仓市| 固原市| 肥西县| 呼和浩特市| 巫溪县| 达孜县| 四会市| 汾西县| 无棣县| 英德市| 张掖市| 宝坻区| 如皋市| 东平县| 获嘉县| 奉化市| 东港市| 寿阳县| 共和县| 神农架林区| 禄丰县| 武定县| 连南| 霍城县| 江华| 托克托县| 报价|