LoginSignup
7
5

More than 3 years have passed since last update.

Webカメラにおける顔認識を最小限のコードで実現させる

Posted at

はじめに

顔認識のプラットフォームは、すでにAWS、Azure、GCPなどでサービスとして展開されていますが、フロント(Javascript)でもやりたいと思い調査したので、共有します。今回はあくまでもコアとなるコードをわかりやすくするためにできる限り無駄なコードを書かずに実現していますので、他の機能も使ってみたい場合は以下のサイトを確認してみてください。

face-api.js

手順

まず、公式のリポジトリをクローンします。

git clone https://github.com/justadudewhohacks/face-api.js.git

以下のファイルをコピーします。

  • dist/face-api.min.js → js/
  • weights/tiny_face_detector_model-shard1 → models/
  • weights/ttiny_face_detector_model-weights_manifest.json → models/
<!DOCTYPE html>
<html>

<head>
  <title>Face Detect Sample</title>
</head>

<body onload="init()">
  <video id="video" autoplay onloadedmetadata="onPlay()"></video>
  <p id="message"></p>

  <script src="js/face-api.min.js"></script>
  <script>
    const video = document.getElementById("video");
    const init = async () => {

      // Webカメラ初期化
      const stream = await navigator.mediaDevices.getUserMedia({
        audio: false,
        video: {
          width: 400,
          height: 400
        }
      });

      try {
        video.srcObject = stream;
      } catch (err) {
        video.src = window.URL.createObjectURL(stream);
      }
      // (1)モデル読み込み ※フォルダを指定
      await faceapi.nets.tinyFaceDetector.load("models/");
    }

    const onPlay = () => {
      const message = document.getElementById('message')
      const inputSize = 512; // 認識対象のサイズ
      const scoreThreshold = 0.5; // 数値が高いほど精度が高くなる(〜0.9)
      // (2)オプション設定
      const options = new faceapi.TinyFaceDetectorOptions({
        inputSize,
        scoreThreshold
      })
      const detectInterval = setInterval(async () => {
        // (3)顔認識処理
        const result = await faceapi.detectSingleFace(
          video,
          options
        );

        if (result) {
          message.textContent = "認識されてます"
        } else {
          message.textContent = "認識されていません"
        }
      }, 500);
    }
  </script>
</body>

</html>
7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5