首页 > 其他分享 >FaceDetector 人脸检测追踪demo

FaceDetector 人脸检测追踪demo

时间:2024-05-08 23:44:06浏览次数:28  
标签:canvas detect FaceDetector demo ctx width video 人脸 document

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      video,
      canvas {
        width: 640px;
      }
    </style>
  </head>
  <body>
    <button id="start" onclick="start()" class="btn btn-lg btn-primary">Start capture</button>
    <button id="detect" onclick="detect()" class="btn btn-lg btn-primary">Detect the face</button>
    <br />
    <video id="video" autoplay="true" muted="true"></video>
    <canvas id="canvas"></canvas>

    <script>
      const detectBtn = document.getElementById('detect')
      detectBtn.disabled = true;

      function start() {
        navigator.mediaDevices
          .enumerateDevices()
          .then((devices) => {
            console.log('devices => ', devices);
            var videoSource = null;
            devices.forEach((device) => {
              if (device.kind == 'videoinput') {
                videoSource = device.deviceId;
              }
            });
            const constraints = {
              video: { deviceId: { exact: videoSource }, width: { max: 320 } },
            };
            console.log('constraints => ', constraints);
            return navigator.mediaDevices.getUserMedia(constraints);
          })
          .then((stream) => {
            document.getElementById('video').srcObject = stream;
            document.getElementById('start').disabled = true;
            document.getElementById('detect').disabled = false;
          })
          .catch((e) => {
            console.error('getUserMedia() failed: ', e);
          });
      }
      function detect() {
        if (!Reflect.has(globalThis, 'FaceDetector')) {
          document.body.innerHTML = `<h1>不支持人脸检测</h1>`;
          return;
        }

        /** @type {HTMLCanvasElement} */
        var canvas = document.getElementById('canvas');
        /** @type {HTMLVideoElement} */
        var video = document.getElementById('video');

        if (video.videoWidth < video.offsetWidth) {
          canvas.width = video.offsetWidth * devicePixelRatio;
          canvas.height = video.offsetHeight * devicePixelRatio;
        } else {
          canvas.width = video.videoWidth * devicePixelRatio;
          canvas.height = video.videoHeight * devicePixelRatio;
        }

        var ctx = canvas.getContext('2d');

        var faceDetector = new FaceDetector();

        video.requestVideoFrameCallback(_detect);

        function _detect() {
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

          faceDetector 
            .detect(canvas)
            .then((faces) => {
              ctx.lineWidth = 3;
              ctx.strokeStyle = 'red';

              for (var i = 0; i < faces.length; i++) {
                const { x, y, width, height } = faces[i].boundingBox;
                ctx.beginPath();
                ctx.rect(
                  Math.floor(x),
                  Math.floor(y),
                  Math.floor(width),
                  Math.floor(height)
                );
                ctx.stroke();
              }
              ctx.closePath();
            })
            .catch((err) => {
              console.log('error: => ' + err);
            })
            .finally(() => {
              video.requestVideoFrameCallback(_detect);
            });
        }
      }
    </script>
  </body>
</html>

标签:canvas,detect,FaceDetector,demo,ctx,width,video,人脸,document
From: https://www.cnblogs.com/chlai/p/18181185

相关文章

  • 【OpenVINO™】基于 C# 和 OpenVINO™ 部署 Blazeface 模型实现人脸检测
     前言OpenVINO™C#API是一个OpenVINO™的.Netwrapper,应用最新的OpenVINO™库开发,通过OpenVINO™CAPI实现.Net对OpenVINO™Runtime调用,使用习惯与OpenVINO™C++API一致。OpenVINO™C#API由于是基于OpenVINO™开发,所支持的平台与OpenVINO™完全一......
  • 基于表面法线法的二维人脸图构建三维人脸模型matlab仿真
    1.算法运行效果图预览   2.算法运行软件版本matlab2022a  3.算法理论概述二维人脸图像获取表面法线 首先,我们需要从二维灰度或者彩色人脸图像中估计表面法线。通常这一过程包括以下几个步骤: 人脸检测与对齐:确保人脸图像被准确检测并进行标准化对齐,以便后续......
  • 动手学深度学习——CNN应用demo
    CNN应用demoCNN实现简单的手写数字识别importtorchimporttorch.nn.functionalasFfromtorchvisionimportdatasets,transformsfromtqdmimporttqdmtorch.zeros(8)defrelu(x):returntorch.clamp(x,min=0)deflinear(x,weight,bias):out=torch.matmul......
  • ollama + ollama web + fastapi app (langchain) demo
    ollama+ollamaweb+fastapiapp(langchain)demohttps://github.com/fanqingsong/ollama-dockerWelcometotheOllamaDockerComposeSetup!ThisprojectsimplifiesthedeploymentofOllamausingDockerCompose,makingiteasytorunOllamawithallitsd......
  • 一个demo快速理解序列号和反序列化
    一个demo快速理解序列号和反序列化分享一个例子用来快速理解序列化和反序列化其实序列化和反序列化就是为了交换数据,(简单粗暴的理解就是把运行中的对象存进文件里面)importjava.io.*;publicclassMain{publicstaticvoidmain(String[]args)throwsException{......
  • OceanBase单机版重新部署提示[ERROR] Deploy “demo“ is running. You could not dep
    执行介质里uninstall.sh脚本删除部署信息后重新安装Demo提示:[root@tidb01bin]#obddemo[ERROR]Deploy"demo"isrunning.Youcouldnotdeployanrunningcluster.Seehttps://www.oceanbase.com/product/ob-deployer/error-codes.TraceID:b18c41ba-07af-11ef-bd8f-......
  • 对接银行支付,自己的demo可以调通,放到项目里,却总提示验签失败。原来竟是因为...
    原因是字符集(charset)不一致对接一个银行支付通道的支付API,自己java写的demo可以调通,放到项目工程里,部署到环境上,总是收到验签失败的响应。这个问题,困扰我们的开发大兄弟长达一个星期。对接通道接口联调不通,常见的场景有许多,如:签名原串需要对key进行排序。不同的排序算法会导......
  • Go语言实现多协程文件上传,断点续传--demo
    packagemainimport("fmt""io""os""regexp""strconv""sync""github.com/qianlnk/pgbar")/***需求:1.多协程下载文件2.断点续连**/funcmain(){//获取要下载文件DownloadFileName:=&quo......
  • [Python急救站]人脸识别技术练习
    这段时间做了一个用于初学者学习人脸识别系统的程序,在上代码时,先给说说事前准备:首先我们需要一个OpenCV的一个haarcascade_frontalface_default.xml文件,只要去GitHub上面即可下载:https://github.com/opencv/opencv点击Code,选择DownloadZIP,下载后解压在目录下opencv-4.x\data\ha......
  • WPF所有原生空间使用demo
    //前台窗体<Windowx:Class="WpfTestDemo.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.......