Azureの小ネタ (改)

~Azureネタを中心に、色々とその他の技術的なことなどを~

Javaから Cognitive Service Face APIを使う

Project Oxford 改め、Cognitive Service の Face APIを Javaから使ってみましょう。

www.microsoft.com

使うまでの登録とかキーの取得とかは割愛します。

ソース

クライアントSDKは、以下のGithubで公開されています。その中からFace APIを参照しますと、Android/iOS/Windows の3つのプラットフォームしかサポートされてません。Mavenに登録されているSDKもAndroid 専用のようです。

https://github.com/Microsoft/ProjectOxford-ClientSDK

多分、Pure Javaでそのままコンパイルできると思ってやってみました。

ProjectOxford-ClientSDK/Face/Android/ClientLibrary at master · Microsoft/ProjectOxford-ClientSDK · GitHub

Androidのフォルダからsrc/main 配下をCopyして任意のIDEに持ってきます。

元は、gradleなんですけど、ちょっと慣れてないので、Maven向けにPom.xmlを用意します。以下抜粋ですけど、

  • Java8 でコンパイル(7でもいいのかも)
  • Apache Http Components
  • Google Gson

の環境となっております。

 <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
                    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.3.1</version>
        </dependency>
    </dependencies>

これでさくっとコンパイルできるかとおもいます。

実行

次に実行してみます。顔画像をInputStreamにして、detect を呼び出すと認識してくれます。 ちょっとAPIがJavaっぽくなくて、Public Fieldの使い方とかちょっとアレだなぁと思います。 Android向けなのでそんなもの?と思ったけど、そんなことないですよねぇ。NETのプロパティをそのままフィールド変数にしてるだけかとは思いますが。

 public static void main(String[] args) {

        // Clientを生成 (要認証キ-)
        FaceServiceRestClient client = new FaceServiceRestClient(key);

        // 画像を読む
        try (FileInputStream imageStream = new FileInputStream(image)) {

            // 取得したい属性の配列
            FaceAttributeType[] faceAttributeTypes = { FaceAttributeType.Age, FaceAttributeType.Smile,
                    FaceAttributeType.Gender };

            Face[] detect = client.detect(imageStream, false, true, faceAttributeTypes);

            for (Face face : detect) {
                System.out.println("age    : " + face.faceAttributes.age);
                System.out.println("gender : " + face.faceAttributes.smile);
                System.out.println("simple : " + face.faceAttributes.gender);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

実行結果はこんな感じ。

age    : 35.7
gender : 0.008
simple : male

以上、さらっと使った結果でした。