LoginSignup
12
8

More than 5 years have passed since last update.

Shape Detection APIでカメラの映像から顔認識してみた

Posted at

はじめに

こちらの投稿を見て、Webカメラの映像をリアルタイムで認識できるか試してみたくなったので、サンプルを作ってみました。
3分でできる「 顔認識 」Shape Detection API(ネット接続も不要) - Qiita
また、以前似たようなことをしていたので、そこからコードを持ってきたりしました。
SkyWay × Cognitive Service - Qiita

動作環境

  • Windows10
  • Google Chrome バージョン: 68.0.3440.106(Official Build) (64 ビット)

Chromeは、FaceDetectorが使えるように「Experimental Web Platform features」 chrome://flags/#enable-experimental-web-platform-featuresEnabled に設定してあります。

実装

コードはすべてGitHubに公開しています。(もしよかったstar押していただけると嬉しいです)
ShapeDetectionAPISample - GitHub
処理の流れとしては、

  1. Webカメラの映像を取得し、表示
  2. 任意のタイミングで映像の一コマを canvas に表示
  3. canvas の画像を FaceDetector で顔認識
  4. 認識結果が返されたら、 canvas の顔の位置に枠を描画
  5. 2~4を繰り返す

こんな感じです。

サンプルコード

サンプルコード
デモ

main.js
navigator.mediaDevices.getUserMedia({ video: { height: 480, width: 640 }, audio: false })
    .then(function (stream) {
        video.srcObject = stream;
        localStream = stream;

        if (window.FaceDetector) {
            var detector = new FaceDetector();
            captureTimer = setInterval(function () {
                ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                var scale = 300 / 640;
                detector.detect(video).then(function (faces) {
                    ctx.lineWidth = 2;
                    ctx.strokeStyle = 'red';
                    for (var face of faces) {
                        ctx.beginPath();
                        ctx.rect(face.boundingBox.x * scale,
                            (face.boundingBox.y - face.boundingBox.height) * scale,
                            face.boundingBox.width * scale,
                            face.boundingBox.height * scale);
                        ctx.stroke();
                        console.log(face);
                    }
                }).catch(function (err) {
                    console.error(err);
                });
            }, 1000 / fps);
        } else {
            console.error('FaceDetector is not enable!');
        }
    }).catch(function (err) {
        console.error(err);
    });

まとめ

以前顔認識を行ったときは、MicrosoftのCognitive Services(Face API)を使っていましたが、この方法だと毎分5~6フレームしか認識できません。
今回のサンプルは毎秒30フレーム程度まで認識可能です。(Core i3 6006UでCPU使用率40%前後)
ブラウザだけで手軽に顔認識ができるShape Detection API、早く正式リリースになってほしいなと思います。

12
8
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
12
8