• 118338

    文章

  • 803

    评论

  • 12

    友链

  • 最近新加了换肤功能,大家多来逛逛吧~~~~
  • 喜欢这个网站的朋友可以加一下QQ群,我们一起交流技术。

face-api.js 使用摄像头,识别人脸

撸了今年阿里、腾讯和美团的面试,我有一个重要发现.......>>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>基于视频的人脸识别</title>
    <script src="face-api.js"></script>
    <link rel="stylesheet" href="css/materialize.css">
    <link rel="stylesheet" href="styles.css">
    <script type="text/javascript" src="assets/jquery-2.1.1.min.js"></script>
    <script src="assets/materialize.min.js"></script>
</head>
<body>

<div>
    <video id="video"/>
</div>
</body>

<script type="text/javascript">

    const displaySize = {width: 200, height: 200};
    let canvas = null;
    let video = document.getElementById('video');

    //getUserMedia 返回摄像头的流数据
    if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (options) {   // 首先,如果有getUserMedia的话,就获得它
            let userMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

            // 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
            if (!userMedia) {
                return Promise.reject(new Error('userMedia is not implemented in this browser'));
            }

            // 否则,为老的navigator.getUserMedia方法包裹一个Promise
            return new Promise(function (resolve, reject) {
                userMedia.call(navigator, options, resolve, reject);
            });
        }
    }

    //参数
    const options = {
        video: true,
        audio: false
    };
    let promise = navigator.mediaDevices.getUserMedia(options);
    //打开设备,获取数据流
    promise.then(stream => {
        // 旧的浏览器可能没有srcObject
        if ("srcObject" in video) {
            video.srcObject = stream;
        } else {
            // 防止再新的浏览器里使用它,应为它已经不再支持了
            video.src = window.URL.createObjectURL(stream);
        }
        //如果数据已经加载了,就播放
        video.onloadedmetadata = (e) => {
            video.play();
        };
    }).catch(err => {
        console.error(err.name + ": " + err.message);
    });

    //监听摄像头播放事件
    video.addEventListener('play', () => {
        canvas = faceapi.createCanvasFromMedia(video);
        document.body.append(canvas);
        faceapi.matchDimensions(canvas, displaySize);
        displayingDetectionResult();
        setInterval(displayingDetectionResult, 1000);
    });


    //展示识别的结果
    async function displayingDetectionResult() {
        if (!faceapiIsReady()) {
            return;
        }

        // const displaySize = { width: video.width, height: video.height }

        // const options = new faceapi.SsdMobilenetv1Options({ minConfidence: 0.5, maxResults: 3 });
        const options = new faceapi.TinyFaceDetectorOptions({scoreThreshold: 0.2, inputSize: 608});
        const detections = await faceapi.detectAllFaces(video, options).withFaceLandmarks();
        if (!detections || detections.length <= 0) {
            return;
        }

        const resizedDetections = faceapi.resizeResults(detections, displaySize);
        canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
        faceapi.draw.drawDetections(canvas, resizedDetections);
        // faceapi.draw.drawFaceLandmarks(canvas, resizedDetections);

    }

    function getCurrentFaceDetectionNet() {
        // return faceapi.nets.ssdMobilenetv1;
        return faceapi.nets.tinyFaceDetector;
    }

    function faceapiIsReady() {
        return !!getCurrentFaceDetectionNet().params
    }

    //人脸识别初始化配置
    async function init() {
        await getCurrentFaceDetectionNet().load('/');        //神经网络加载
        await faceapi.loadFaceLandmarkModel('/');            //人脸识别必须
        await faceapi.loadFaceRecognitionModel('/');        //人脸识别必须
    }

    $(() => {
        init();
    })

</script>

</html>

695856371Web网页设计师②群 | 喜欢本站的朋友可以收藏本站,或者加入我们大家一起来交流技术!

0条评论

Loading...


自定义皮肤 主体内容背景
打开支付宝扫码付款购买视频教程
遇到问题联系客服QQ:419400980
注册梁钟霖个人博客