LoginSignup
8
9

More than 5 years have passed since last update.

HTML Media Capture API で画像を取得して Rekognition API で認識する

Last updated at Posted at 2014-11-28

目標

デバイス付属のカメラから画像を取得して、
画像処理 API Rekognition に入れて認識させる。

制限

認識 API へのデータ送信は、現状 URL を指定する方法しか
動くことを確認していないので、1, 3 の間に 2 が必要。

  1. カメラから画像取得
  2. 手作業、ないしサーバ側のコードによる外部からアクセスできる場所への画像の保存
  3. 認識結果の取得

方法

カメラから画像取得

ブラウザによらずにオブジェクトを取得するために、名前を揃える。

navigator.getUserMedia = navigator.getUserMedia       ||
                         navigator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia    ||
                         navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL;

getUserMedia メソッドで画像を取得。
myVideo という id をつけた video 要素に対して、
カメラから取得した画像情報を流し込む。 (src の設定)
そして、再生を開始 (play)

function getMedia() {
  navigator.getUserMedia(
    {video: true},
    function(localMediaStream) {
      myVideo  = document.getElementById('myVideo');
      stream = localMediaStream;
      src = window.URL.createObjectURL(localMediaStream);
      myVideo.src = src;
      myVideo.play();
    },
    function(err) {
      alert('カメラから映像を取得することができませんでした。');  
      console.log(err);
    }
  );
}

キャプチャ部分。
snap という id のボタンをクリックすると始まる。

document.getElementById("snap").addEventListener("click", function() {
  // canvas オブジェクトの取得
  var canvas = document.getElementById("canvas");
  context = canvas.getContext("2d");

  // video に流されるデータを canvas に書き込み
  context.drawImage(myVideo, 0, 0, 640, 480);

  // canvas のデータを data URL に変換して href に設定
  $("#captured").attr("href", canvas.toDataURL("image/png"));
});

認識結果の取得

  1. https://rekognition.com/user/create ここからアカウントを作って API Key, API Secret を取得 API Key を kkk, API Secret を sss と仮定。
  2. 画像を置く。 例えば http://example.com/example.png
  3. https://rekognition.com/developer/face に従って Web URI にアクセスする。 例えば
http://rekognition.com/func/api/?api_key=kkk&api_secret=sss&jobs=face_emotion_part&urls=http://example.com/example.png
  • api_key に API Key
  • api_secret に API Secret
  • urls に画像への URL
  • jobs に走らせたいジョブを結合したもの (この場合 emotion, part なので face_emotion_part) 結合できるジョブ (=機能) のリストは https://rekognition.com/developer/face ここの3行目 (jobs) を参照。

参考文献

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