学习笔记:web页面的人脸识别注册及登录

前端代码:

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <script src="/static/js/jquery-3.4.1.min.js"></script>
    <script src="/static/js/bootstrap.js"></script>
    <script src="/static/js/canvas-to-blob.js"></script>
    <title>client video</title>
    <style>
        .space {
            height: 20px;
        }
    </style>
</head>
<body>
<h1 align="center">人脸识别</h1>

<div class="space"></div>

<div class="container" style="margin: 0 auto;">
    <div class="row">
        <div class="col-md-3 col-md-offset-3">
            <div class="initFace_box">
                <!-- Button trigger modal -->

                请输入您的名称:<input type="text" id='uname' name='uname'/>
                <button type="button" id="register" class="btn btn-primary" data-toggle="modal"
                        data-target="#faceModal">
                    注册人脸
                </button>
                <button type="button" id="check" class="btn btn-primary" data-toggle="modal" data-target="#faceModal">
                    人脸登录
                </button>

                <!-- Modal -->
                <div class="modal fade" id="faceModal" tabindex="-1" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-body">
                            <video id="video" width="1" height="1" controls> {#用于获取摄像头#}
                            </video>
                            <canvas id="canvas" width="500" height="380"></canvas>
                            {#用于获取摄像头#}
                            <p id="result_tag"></p>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>
</body>
<script src="/static/js/index.js"></script>
</html>

index.js:调用摄像头截图发送

使用定时器来间断获取截图进行识别,直到识别成功或达到一定时间

视频识别电脑风扇哗哗转 顶不住

function getUserMedia(constraints, success, error) {
    if (navigator.mediaDevices.getUserMedia) {
        //最新的标准API
        navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
    } else if (navigator.webkitGetUserMedia) {
        //webkit核心浏览器
        navigator.webkitGetUserMedia(constraints, success, error)
    } else if (navigator.mozGetUserMedia) {
        //firfox浏览器
        navigator.mozGetUserMedia(constraints, success, error);
    } else if (navigator.getUserMedia) {
        //旧版API
        navigator.getUserMedia(constraints, success, error);
    }
}

let video = document.getElementById('video');

video.controls = false;
let canvas = document.getElementById('canvas');
//返回一个用于在画布上绘图的环境
let context = canvas.getContext('2d');

context.arc(250, 250, 200, 0, 0.75 * Math.PI, false);

function success(stream) {
    //兼容webkit核心浏览器
    let CompatibleURL = window.URL || window.webkitURL;
    //将视频流设置为video元素的源
    //video.src = CompatibleURL.createObjectURL(stream);
    video.srcObject = stream;
    video.play();
}

function error(error) {
    console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
    alert("访问用户媒体设备失败")
}

function open_video() { // 打开摄像头并显示
    if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
        //调用用户媒体设备, 访问摄像头
        getUserMedia({video: {width: 640, height: 480}}, success, error);
    } else {
        alert('不支持访问用户媒体');
    }
}


function closeVideo() { // 关闭摄像头
    video.srcObject.getTracks()[0].stop();
    video.srcObject.getTracks()[0].stop();
}

function endRecognize(timer, error) {
    clearInterval(timer); // 检测到人脸,停止检测
    clearInterval(error); // 检测到人脸,取消提示
    closeVideo();
}

function face_recognize(timer, error) { // 验证脸库是否存在该人脸
    let imgData
    context.drawImage(video, 0, 0, 500, 380);
    //获得截图base64编码
    imgData = canvas.toDataURL("image/png", 0.8);
    //ajax发送校验
    $.ajax({
        url: "/check_face",
        type: "POST",
        dataType: 'json',
        data: {"imgData": imgData},
        success: function (data) {
            if (data.result == "fail") {
                $("#result_tag").text("检测不出人脸");
            } else {
                endRecognize(timer, error);
                let file_rand = data.file_rand;
                $.ajax({
                    url: "/recognize",
                    type: "POST",
                    data: {"file_rand": file_rand},
                    success: function (data) {
                        $("#result_tag").text("识别结果:" + data);
                    }
                })
            }
        }
    })
}

// 验证用户人脸进行登录
document.getElementById("check").addEventListener('click', function () {
    let timer;
    let error;
    open_video();
    timer = setInterval(function () { // 每秒检测一次
        face_recognize(timer, error);
    }, 1000);
    error = setInterval(function () { // 检测不到人脸进行提醒
        alert('检测不到人脸,请重试!!');
    }, 4900);
    setTimeout(function () {
        endRecognize(timer, error)// 五秒后还未检测到人脸则停止检测
    }, 5000);
})


// 验证用户进行注册
function register(timer, error) {
    context.drawImage(video, 0, 0, 640, 480);
    //获得截图base64编码
    let imgData = canvas.toDataURL("image/png", 0.8);
    let uname = document.getElementById("uname").value
    //ajax发送校验
    $.ajax({
        url: "/register",
        type: "POST",
        dataType: 'json',
        data: {"imgData": imgData, "uname": uname},
        success: function (data) {
            if (data.result == "fail") {
                $("#result_tag").text("检测不出人脸");
            } else {
                endRecognize(timer, error);
                if (data.result == "repetition") {
                    $("#result_tag").text("请勿重复注册!!");
                } else {
                    $("#result_tag").text("注册成功," + uname + "欢迎你!");
                }
            }
        }
    })
}

document.getElementById("register").addEventListener("click", function () {
    let timer;
    let error;
    open_video();
    timer = setInterval(function () { // 每秒检测一次
        register(timer, error);
    }, 1000);
    error = setInterval(function () { // 检测不到人脸进行提醒
        alert('检测不到人脸,请重试!!')
    }, 4900);
    setTimeout(function () {
        endRecognize(timer, error)
    }, 5000);
});

app.py

from flask import Flask, render_template, jsonify
from flask.globals import request
import base64
import random
import os
import face_recognize

app = Flask(__name__)


@app.route("/")
def hello():
    return render_template("index.html")


@app.route("/check_face", methods=["GET", "POST"])  # 进行识别
def check_face():
    if request.method == "POST":
        img_base64 = request.form["imgData"]
        file_rand = random.randint(1, 9999)
        img_data = base64.b64decode(img_base64.split(",")[1])
        file_paths = os.path.join(app.static_folder, "img", "{}.png".format(file_rand))
        with open(file_paths, "wb+") as f:
            f.write(img_data)
        result = face_recognize.check_face(file_paths)
        if result == "fail":
            os.remove(file_paths)
        return jsonify({"result": result, "file_rand": str(file_rand)})


@app.route("/register", methods=["GET", "POST"])  # 进行注册
def register():
    if request.method == "POST":
        img_base64 = request.form["imgData"]
        uname = request.form["uname"]
        rand = random.randint(1, 9999)
        file_name = f'{uname}_{rand}'
        img_data = base64.b64decode(img_base64.split(",")[1])
        file_paths = os.path.join(app.static_folder, "init_face", "{}.png".format(file_name))
        with open(file_paths, "wb+") as f:
            f.write(img_data)
        result = face_recognize.check_face(file_paths)
        if result == "fail":
            os.remove(file_paths)  # 识别不到人脸
        elif face_recognize.face_recognize_image(file_paths):
            os.remove(file_paths)
            result = "repetition"  # 重复注册
        return jsonify({"result": result})


@app.route('/recognize', methods=["GET", "POST"])
def recognize():
    if request.method == "POST":
        file_rand = request.get_data().decode("utf-8").split("=")[1]
        name = face_recognize.face_recognize_image(os.path.join(app.static_folder, "img", "{}.png".format(file_rand)))
        if name:
            return name
        else:
            return "未知人员"


if __name__ == '__main__':
    app.run(debug=True)
face_recognize.py 进行人脸识别和验证
import cv2
import face_recognition
import os

# 获取脸库的所有人脸特征


def get_features():
    basefacefilespath = "static\\init_face"
    baseface_titles = []  # 名称
    baseface_face_encodings = []  # 人脸数据
    # 读取人脸资源
    for fn in os.listdir(basefacefilespath):
        baseface_face_encodings.append(
            face_recognition.face_encodings(face_recognition.load_image_file(basefacefilespath + "\\" + fn))[0])
        fn = fn[:(len(fn) - 4)]
        baseface_titles.append(fn)

    return baseface_face_encodings, baseface_titles


# 人脸识别
def face_recognize_image(filename):
    frame = face_recognition.load_image_file(filename)
    face_encoding = face_recognition.face_encodings(frame)[0]
    baseface_face_encodings, baseface_titles = get_features()

    for i, v in enumerate(baseface_face_encodings):
        match = face_recognition.compare_faces([v], face_encoding, tolerance=0.5)
        print(match)
        name = None
        if match[0]:
            name = baseface_titles[i]
            break
    return name


def face_recognize_video(video):  # 使用视频进行识别
    input_movie = cv2.VideoCapture(video)
    baseface_face_encodings, baseface_titles = get_features()
    while True:
        # 抓取每一帧
        ret, frame = input_movie.read()

        # Quit when the input video file ends
        if not ret:
            break

        # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
        rgb_frame = frame[:, :, ::-1]

        # Find all the faces and face encodings in the current frame of video
        face_locations = face_recognition.face_locations(rgb_frame)
        face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)

        for face_encoding in face_encodings:
            for i, v in enumerate(baseface_face_encodings):
                match = face_recognition.compare_faces([v], face_encoding, tolerance=0.5)
                print(match)
                name = "未知人员"
                if match[0]:
                    name = baseface_titles[i]
                    break
            if (name):
                print(name)
                return name

    cv2.destroyAllWindows()


# 检测照片是否存在人脸
def check_face(filename):
    frame = face_recognition.load_image_file(filename)
    face_location = face_recognition.face_locations(frame)
    if len(face_location) == 0:
        return "fail"
    else:
        return "success"


if __name__ == "__main__":
    pass

部分代码参考:基于face_recognition & flask 构建的人脸识别web服务_阿坨的博客-CSDN博客_flask实现人脸识别前言此demo采用face_recognition和flask搭建一个人脸识别的网页版demo,网页端可上传注册人脸图并调用摄像头捕获人脸进行识别。face_recognition是世界上最简洁的人脸识别库,你可以使用Python和命令行工具提取、识别、操作人脸。face_recognition的人脸识别是基于业内领先的C++开源库 dlib中的深度学习模型,用Labeled Faces in the Wild人脸数据集进行测试,有高达99.38%的准确率。但对小孩和亚洲人脸的识别准确率尚待提升。安装https://blog.csdn.net/atuo200/article/details/117992251

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值