最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

如何通過python實(shí)現(xiàn)人臉識(shí)別驗(yàn)證

 更新時(shí)間:2020年01月17日 09:50:16   作者:Maple_feng  
這篇文章主要介紹了如何通過python實(shí)現(xiàn)人臉識(shí)別驗(yàn)證,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

這篇文章主要介紹了如何通過python實(shí)現(xiàn)人臉識(shí)別驗(yàn)證,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

直接上代碼,此案例是根據(jù)https://github.com/caibojian/face_login修改的,識(shí)別率不怎么好,有時(shí)擋了半個(gè)臉還是成功的

# -*- coding: utf-8 -*-
# __author__="maple"
"""
       ┏┓   ┏┓
      ┏┛┻━━━┛┻┓
      ┃   ☃   ┃
      ┃ ┳┛ ┗┳ ┃
      ┃   ┻   ┃
      ┗━┓   ┏━┛
        ┃   ┗━━━┓
        ┃ 神獸保佑  ┣┓
        ┃ 永無BUG!  ┏┛
        ┗┓┓┏━┳┓┏┛
         ┃┫┫ ┃┫┫
         ┗┻┛ ┗┻┛
"""
import base64
import cv2
import time
from io import BytesIO
from tensorflow import keras
from PIL import Image
from pymongo import MongoClient
import tensorflow as tf
import face_recognition
import numpy as np
#mongodb連接
conn = MongoClient('mongodb://root:123@localhost:27017/')
db = conn.myface #連接mydb數(shù)據(jù)庫,沒有則自動(dòng)創(chuàng)建
user_face = db.user_face #使用test_set集合,沒有則自動(dòng)創(chuàng)建
face_images = db.face_images


lables = []
datas = []
INPUT_NODE = 128
LATER1_NODE = 200
OUTPUT_NODE = 0
TRAIN_DATA_SIZE = 0
TEST_DATA_SIZE = 0


def generateds():
  get_out_put_node()
  train_x, train_y, test_x, test_y = np.array(datas),np.array(lables),np.array(datas),np.array(lables)
  return train_x, train_y, test_x, test_y

def get_out_put_node():
  for item in face_images.find():
    lables.append(item['user_id'])
    datas.append(item['face_encoding'])
  OUTPUT_NODE = len(set(lables))
  TRAIN_DATA_SIZE = len(lables)
  TEST_DATA_SIZE = len(lables)
  return OUTPUT_NODE, TRAIN_DATA_SIZE, TEST_DATA_SIZE

# 驗(yàn)證臉部信息
def predict_image(image):
  model = tf.keras.models.load_model('face_model.h5',compile=False)
  face_encode = face_recognition.face_encodings(image)
  result = []
  for j in range(len(face_encode)):
    predictions1 = model.predict(np.array(face_encode[j]).reshape(1, 128))
    print(predictions1)
    if np.max(predictions1[0]) > 0.90:
      print(np.argmax(predictions1[0]).dtype)
      pred_user = user_face.find_one({'id': int(np.argmax(predictions1[0]))})
      print('第%d張臉是%s' % (j+1, pred_user['user_name']))
      result.append(pred_user['user_name'])
  return result

# 保存臉部信息
def save_face(pic_path,uid):
  image = face_recognition.load_image_file(pic_path)
  face_encode = face_recognition.face_encodings(image)
  print(face_encode[0].shape)
  if(len(face_encode) == 1):
    face_image = {
      'user_id': uid,
      'face_encoding':face_encode[0].tolist()
    }
    face_images.insert_one(face_image)

# 訓(xùn)練臉部信息
def train_face():
  train_x, train_y, test_x, test_y = generateds()
  dataset = tf.data.Dataset.from_tensor_slices((train_x, train_y))
  dataset = dataset.batch(32)
  dataset = dataset.repeat()
  OUTPUT_NODE, TRAIN_DATA_SIZE, TEST_DATA_SIZE = get_out_put_node()
  model = keras.Sequential([
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(OUTPUT_NODE, activation=tf.nn.softmax)
  ])

  model.compile(optimizer=tf.compat.v1.train.AdamOptimizer(),
        loss='sparse_categorical_crossentropy',
        metrics=['accuracy'])
  steps_per_epoch = 30
  if steps_per_epoch > len(train_x):
    steps_per_epoch = len(train_x)
  model.fit(dataset, epochs=10, steps_per_epoch=steps_per_epoch)

  model.save('face_model.h5')



def register_face(user):
  if user_face.find({"user_name": user}).count() > 0:
    print("用戶已存在")
    return
  video_capture=cv2.VideoCapture(0)
  # 在MongoDB中使用sort()方法對(duì)數(shù)據(jù)進(jìn)行排序,sort()方法可以通過參數(shù)指定排序的字段,并使用 1 和 -1 來指定排序的方式,其中 1 為升序,-1為降序。
  finds = user_face.find().sort([("id", -1)]).limit(1)
  uid = 0
  if finds.count() > 0:
    uid = finds[0]['id'] + 1
  print(uid)
  user_info = {
    'id': uid,
    'user_name': user,
    'create_time': time.time(),
    'update_time': time.time()
  }
  user_face.insert_one(user_info)

  while 1:
    # 獲取一幀視頻
    ret, frame = video_capture.read()
    # 窗口顯示
    cv2.imshow('Video',frame)
    # 調(diào)整角度后連續(xù)拍5張圖片
    if cv2.waitKey(1) & 0xFF == ord('q'):
      for i in range(1,6):
        cv2.imwrite('Myface{}.jpg'.format(i), frame)
        with open('Myface{}.jpg'.format(i),"rb")as f:
          img=f.read()
          img_data = BytesIO(img)
          im = Image.open(img_data)
          im = im.convert('RGB')
          imgArray = np.array(im)
          faces = face_recognition.face_locations(imgArray)
          save_face('Myface{}.jpg'.format(i),uid)
      break

  train_face()
  video_capture.release()
  cv2.destroyAllWindows()


def rec_face():
  video_capture = cv2.VideoCapture(0)
  while 1:
    # 獲取一幀視頻
    ret, frame = video_capture.read()
    # 窗口顯示
    cv2.imshow('Video',frame)
    # 驗(yàn)證人臉的5照片
    if cv2.waitKey(1) & 0xFF == ord('q'):
      for i in range(1,6):
        cv2.imwrite('recface{}.jpg'.format(i), frame)
      break

  res = []
  for i in range(1, 6):
    with open('recface{}.jpg'.format(i),"rb")as f:
      img=f.read()
      img_data = BytesIO(img)
      im = Image.open(img_data)
      im = im.convert('RGB')
      imgArray = np.array(im)
      predict = predict_image(imgArray)
      if predict:
        res.extend(predict)

  b = set(res) # {2, 3}
  if len(b) == 1 and len(res) >= 3:
    print(" 驗(yàn)證成功")
  else:
    print(" 驗(yàn)證失敗")

if __name__ == '__main__':
  register_face("maple")
  rec_face()

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 使用Python進(jìn)行有效的數(shù)據(jù)脫敏的常用方法

    使用Python進(jìn)行有效的數(shù)據(jù)脫敏的常用方法

    數(shù)據(jù)脫敏(Data Masking)是在數(shù)據(jù)處理和分析過程中,對(duì)敏感信息進(jìn)行處理,以保護(hù)個(gè)人隱私和企業(yè)機(jī)密的一種技術(shù)手段,數(shù)據(jù)脫敏的目的是不會(huì)泄露敏感信息,同時(shí)保持?jǐn)?shù)據(jù)的可用性和分析價(jià)值,本文給大家介紹了使用Python進(jìn)行有效的數(shù)據(jù)脫敏的常用方法,需要的朋友可以參考下
    2025-03-03
  • Python Word文件自動(dòng)化實(shí)戰(zhàn)之簡歷篩選

    Python Word文件自動(dòng)化實(shí)戰(zhàn)之簡歷篩選

    本文將利用Python自動(dòng)化做一個(gè)具有實(shí)操性的小練習(xí),即通過讀取簡歷來篩選出符合招聘條件的簡歷。文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2022-05-05
  • tensorflow之讀取jpg圖像長和寬實(shí)例

    tensorflow之讀取jpg圖像長和寬實(shí)例

    這篇文章主要介紹了tensorflow之讀取jpg圖像長和寬實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • python搭建虛擬環(huán)境的步驟詳解

    python搭建虛擬環(huán)境的步驟詳解

    相信每位python都知道,進(jìn)行不同的python項(xiàng)目開發(fā),有的時(shí)候會(huì)遇到這樣的情況:python 版本不一樣,使用的軟件包版本不一樣。這種問題最佳的解決辦法是為不同的項(xiàng)目搭建獨(dú)立的 python 環(huán)境。下面來一起看看吧。
    2016-09-09
  • Python基于回溯法子集樹模板解決數(shù)字組合問題實(shí)例

    Python基于回溯法子集樹模板解決數(shù)字組合問題實(shí)例

    這篇文章主要介紹了Python基于回溯法子集樹模板解決數(shù)字組合問題,簡單描述了數(shù)字組合問題并結(jié)合實(shí)例形式分析了Python回溯法子集樹模板解決數(shù)字組合問題的具體步驟與相關(guān)操作技巧,需要的朋友可以參考下
    2017-09-09
  • pandas之分組統(tǒng)計(jì)列聯(lián)表pd.crosstab()問題

    pandas之分組統(tǒng)計(jì)列聯(lián)表pd.crosstab()問題

    這篇文章主要介紹了pandas之分組統(tǒng)計(jì)列聯(lián)表pd.crosstab()問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • Python中return函數(shù)返回值實(shí)例用法

    Python中return函數(shù)返回值實(shí)例用法

    在本篇文章里小編給大家整理的是一篇關(guān)于Python中return函數(shù)返回值實(shí)例用法,有興趣的朋友們可以學(xué)習(xí)下。
    2020-11-11
  • Django url反向解析的實(shí)現(xiàn)

    Django url反向解析的實(shí)現(xiàn)

    本文主要介紹了Django url反向解析的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-12-12
  • Python 繼承,重寫,super()調(diào)用父類方法操作示例

    Python 繼承,重寫,super()調(diào)用父類方法操作示例

    這篇文章主要介紹了Python 繼承,重寫,super()調(diào)用父類方法,結(jié)合完整實(shí)例形式詳細(xì)分析了Python面向?qū)ο蟪绦蛟O(shè)計(jì)中子類繼承與重寫父類方法的相關(guān)操作技巧,需要的朋友可以參考下
    2019-09-09
  • python神經(jīng)網(wǎng)絡(luò)ResNet50模型的復(fù)現(xiàn)詳解

    python神經(jīng)網(wǎng)絡(luò)ResNet50模型的復(fù)現(xiàn)詳解

    這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)ResNet50模型的復(fù)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05

最新評(píng)論

蒙山县| 广南县| 周至县| 清流县| 阿坝县| 浮山县| 赤峰市| 元朗区| 西乡县| 东安县| 宜春市| 那坡县| 方城县| 闽清县| 余江县| 武川县| 庄河市| 方城县| 钟祥市| 顺昌县| 永定县| 西平县| 宁海县| 舞钢市| 白朗县| 合阳县| 樟树市| 黔东| 舒兰市| 鄂托克前旗| 遂川县| 桂平市| 类乌齐县| 桐柏县| 金湖县| 南丰县| 六盘水市| 桓台县| 贺州市| 德江县| 镇原县|