はじめに
こちらの投稿を見て、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-features
を Enabled
に設定してあります。
実装
コードはすべてGitHubに公開しています。(もしよかったstar押していただけると嬉しいです)
ShapeDetectionAPISample - GitHub
処理の流れとしては、
- Webカメラの映像を取得し、表示
- 任意のタイミングで映像の一コマを
canvas
に表示 -
canvas
の画像をFaceDetector
で顔認識 - 認識結果が返されたら、
canvas
の顔の位置に枠を描画 - 2~4を繰り返す
こんな感じです。
サンプルコード
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、早く正式リリースになってほしいなと思います。