Face Detection API

_clai發表於2024-05-08

一個針對影像中的人臉進行識別的底層加速平臺元件


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      .img,
      .canvas {
        width: 320px;
      }
    </style>
  </head>
  <body>
    <img src="./people.jpg" alt="" class="img" hidden />
    <hr />
    <canvas class="canvas"></canvas>

    <script>
      init();

      function init() {
        if (!Reflect.has(globalThis, 'FaceDetector')) {
          document.body.innerHTML = `<h1>不支援人臉檢測</h1>`;
          return;
        }

        const img = document.querySelector('.img');
        /** @type {HTMLCanvasElement} */
        const canvas = document.querySelector('.canvas');

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

        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;

        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        ctx.save();

        const faceDetector = new FaceDetector({
          fastMode: true /* 是否開啟速度優先(於精確度)模式,將透過更小的比例尺(更靠近目標圖形)或尋找更大的目標圖形的辦法進行識別 */,
          maxDetectedFaces: 5 /* 當前場景中已識別的人臉數的最大值 */,
        });
        faceDetector
          .detect(canvas)
          .then((faces) => {
            console.log(faces);
            ctx.lineWidth = 3;
            ctx.strokeStyle = 'yellow';

            faces.forEach((face) => {
              const { x, y, width, height } = face.boundingBox;

              ctx.beginPath();
              ctx.rect(x, y, width, height);
              ctx.stroke();
            });
            ctx.closePath();
          })
          .catch((error) => {
            console.log(error);
          });
      }
    </script>
  </body>
</html>

相關文章