LoginSignup
4
3

More than 5 years have passed since last update.

JavaからMicrosoft Cognitive ServicesのEmotion APIを呼び出して顔画像の感情分析を行ってみる

Posted at

「福岡市防災減災アプリコンテスト by Mashup Awards 2016」に参加したので、ネタとして投稿してみる。
イベントのまとめはコチラ。

昨日(2016/10/23)の投稿「JavaからIBM BlueMixのPersonality Insightsを呼び出して日本語テキストから性格分析を行ってみる」の続き。

JavaからMicrosoft Cognitive ServicesのEmotion APIを呼び出して顔画像の感情分析を行ってみる

  • サンプルコードはGitHubに投稿しています。

[事前準備] Microsoft Cognitive Servicesの利用登録

  • ligerboltさんの記事を参照
  • この手順の中で、後述するAPI利用に必要なサブスクリプションキーの払い出しを行います!

1. pom.xmlにCommons HttpComponentsを定義

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.2</version>
</dependency>
  • API自身が簡単に利用できるインタフェースなので、特にJava向けのSDKは無いようです(本当に?)。今回はREST APIを呼び出すためのHTTPクライアントとして、Commons HttpComponentsを利用しました。

2. HTTPクライアント初期化

// 1. HTTPクライアントを生成
try (CloseableHttpClient client = HttpClients.createDefault()) {
    …
} catch (IOException e) {
    e.printStackTrace();
}

3. POST要求を生成

private static final String EMOTION_API_URL = "https://api.projectoxford.ai/emotion/v1.0/recognize";
private static final String SUBSCRIPTION = "dummy";  // FIXME: correct subscription

…中略…

// 分析対象の画像のURLを指定するJSON文字列
String req = "{ \"url\": \"https://portalstoragewuprod.azureedge.net/media/Default/Media/EmotionAPI/Emotion.jpg\" }";
// POSTメソッドを生成
HttpPost post = new HttpPost(EMOTION_API_URL);
post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
post.setHeader("Ocp-Apim-Subscription-Key", SUBSCRIPTION);
post.setEntity(new StringEntity(req));
  • HTTP要求ヘッダに以下の設定が必要です
    • Content-Type = application/json
    • Ocp-Apim-Subscription-Key = <APIのサブスクリプションキー>

4. APIの呼び出し / 例外処理

// APIを呼び出し応答データを取得
try (CloseableHttpResponse response = client.execute(post)) {
    String resp = EntityUtils.toString(response.getEntity());
    System.out.println(resp);
}

最後に

  • クライアントをJavaで実装したとしても、たったこれだけで画像の感情分析ができるなんて楽すぎでしょ!これまで、アカウント登録や、使ってみるにあたって調べるのも大変だろう。。。と思っていた自分がバカみたいですね。
  • 欲を言えば、JSON文字列とオブジェクトのO/Rマッパーがあると、要求データの生成と応答データの中身の取り出しが、もっと楽にかと思うのですが、それ位、Jacksonとか使って自前で作れって感じですかね。

参考

  • Cognitive Services: Emotion API
    • 作らずに試すだけなら、上記のページにあるAPI Referenceの中に、デモ実行用のページもあるので、そちらを使ってみてはいかがでしょうか。
4
3
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
4
3