LoginSignup
0
1

More than 5 years have passed since last update.

Microsoft Emotion APIをJavaからイメージデータを直接送信して呼び出す。

Posted at

Emotion API って?

Microsoft Azure CognitiveServicesの一つで、写真などの人の顔から感情を読み取ってくれます。
詳しくはこちら
2017/6/24現在、ある程度無料で使うことができます。

何故、Javaか?

特に理由はありません。
公式にJavaでのサンプル実装があるのですが、画像を上げたURLを送るものしかなかったので画像を直接送る方式の実装を試してみた。

環境

Java:1.8.0_131
Emotion Api : 1.0

手順

サブスクリプションの登録

サブスクリプションを登録する。
公式サイトの「試用版」というタグから作成を押すと登録可能、32桁のキーが払い出されるので保存しておく。

pom.xmlへ依存の追加

以下を追加する。

pom.xml
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.3</version>
</dependency>

EmotionApiClientの作成

ほぼサンプルソース通りだが、以下の通り実装した。メソッドの引数はイメージファイルのバイト配列。結果はJSONのまま呼び出し側に返す。

EmotionApiClient.java
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class EmotionApiClient {

    private final String KEY = "上で発行した32桁のキー";

    String postApi(byte[] image) {
        HttpClient httpClient = HttpClientBuilder.create().build();


        try
        {
            URIBuilder uriBuilder = new URIBuilder("https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize");

            URI uri = uriBuilder.build();
            HttpPost request = new HttpPost(uri);

            request.setHeader("Content-Type", "application/octet-stream");
            request.setHeader("Ocp-Apim-Subscription-Key", KEY);

            ByteArrayEntity reqEntity = new ByteArrayEntity(image);
            request.setEntity(reqEntity);

            HttpResponse response = httpClient.execute(request);

            //ステータスの確認はした方がいい。
            HttpEntity entity = response.getEntity();

            if (entity != null)
            {
                return EntityUtils.toString(entity);
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }

        return "";
    }
 }

終わりに

想像以上に簡単に実装できました。明るいところや暗いところでどの程度認識できるのかを今後試していきたいと思います。

0
1
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
0
1