Spring Framework で Vision を使用する

Spring Cloud Google Cloud には、Spring アプリケーションから Vision API とのインターフェースを持つことができるように、便利なライブラリが用意されています。このライブラリに含まれている自動構成とヘルパークラスと Spring 起動テンプレート クラスを使用すると、Vision API をすぐに使い始めることができます。

Spring Framework に慣れている場合は Spring Cloud Vision を使用できます。これにより、アプリケーションで Vision API を簡単に使用し、作成するコードの量を減らせます。

このページでは、Java アプリケーションに Spring Cloud Vision を追加する方法について説明します。このモジュールの詳細については、Spring Cloud Vision のリファレンスをご覧ください。

依存関係の設定

このライブラリを使用するには、プロジェクトに spring-cloud-gcp-starter-vision アーティファクトを追加します。

Maven 座標(Spring Cloud Google Cloud BOM を使用):

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-gcp-dependencies</artifactId>
      <version>1.2.8.RELEASE</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-dependencies</artifactId>
      <version>${spring.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-gcp-starter-vision</artifactId>
</dependency>

さらに、サービス アカウントを作成し、サービス アカウント キーを使用して Google Cloud で認証する必要もあります。

詳細については、Java 開発環境の設定の手順をご覧ください。Java 用 Google Cloud クライアント ライブラリをインストールする必要はありません。Spring Boot スターターによってクライアント ライブラリが自動的にインストールされます。

画像分析

クラスパスで Spring Cloud Google Cloud Vision の依存関係を構成した後は、Spring 依存関係の挿入CloudVisionTemplate のインスタンスを取得し、画像処理をすぐに始められます。

@Autowired private CloudVisionTemplate cloudVisionTemplate;

CloudVisionTemplate は Vision API クライアント ライブラリのラッパーです。これにより、Vision API を使用して画像を簡単に処理できます。CloudVisionTemplate 機能の詳細については、Cloud Vision テンプレートのリファレンス ページをご覧ください。

以降のセクションでは、CloudVisionTemplate の一般的なユースケースのサンプルコードについて説明します。コードスニペットはすべて Spring および Cloud Vision のサンプル アプリケーションから引用しています。

画像の分類ラベルを取得する

以下のコードは画像の分類ラベルを抽出し、画像コンテンツの一般的な説明を提供します。

AnnotateImageResponse response =
    this.cloudVisionTemplate.analyzeImage(
        this.resourceLoader.getResource(imageUrl), Type.LABEL_DETECTION);

Map<String, Float> imageLabels =
    response.getLabelAnnotationsList().stream()
        .collect(
            Collectors.toMap(
                EntityAnnotation::getDescription,
                EntityAnnotation::getScore,
                (u, v) -> {
                  throw new IllegalStateException(String.format("Duplicate key %s", u));
                },
                LinkedHashMap::new));

画像内のテキストを抽出する

以下のコードサンプルは、画像からテキストを抽出する一般的なオペレーションを実行します。

String textFromImage =
    this.cloudVisionTemplate.extractTextFromImage(this.resourceLoader.getResource(imageUrl));
return "Text from image: " + textFromImage;

次のステップ