163. Google Cloud Vision

Google Cloud Vision API允许用户利用机器学习算法来处理图像,包括:图像分类,面部检测,文本提取等。

Spring Cloud GCP 提供:

  • 一个便利启动程序,它自动配置开始使用Google Cloud Vision API所需的身份验证设置和 Client 端对象。

  • Cloud Vision 模板可简化与 Cloud Vision API 的交互。

  • 使您可以轻松地将图像作为 Spring 资源发送到 API。

    • 提供常用操作的便捷方法,例如从图像中提取文本。

使用 Spring Cloud GCP BOM 进行 Maven 坐标:

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-gcp-starter-vision</artifactId>
</dependency>

Gradle coordinates:

dependencies {
  compile group: 'org.springframework.cloud', name: 'spring-cloud-gcp-starter-vision'
}

163.1 Cloud Vision 模板

CloudVisionTemplate提供了一种将 Cloud Vision API 与 Spring Resources 结合使用的简单方法。

spring-cloud-gcp-starter-vision依赖项添加到项目后,您可以@Autowire CloudVisionTemplate的实例以在代码中使用。

CloudVisionTemplate提供了以下与 Cloud Vision 连接的方法:

public AnnotateImageResponse analyzeImage(Resource imageResource, Feature.Type… featureTypes)

Parameters:

  • Resource imageResource表示您要分析的图像对象的 Spring 资源。 Google Cloud Vision 文档提供了他们支持的图像类型列表

  • Feature.Type… featureTypes表示要从图像中提取的 Cloud Vision 功能的 var-arg 数组。Feature 是指人们希望对图像执行的一种图像分析,例如标签检测,OCR 识别,面部检测等。可以指定多个 Feature 以在一个请求内进行分析。 Cloud Vision 功能文档中提供了 Cloud Vision 功能的完整列表。

Returns:

  • AnnotateImageResponse包含请求中指定的所有 Feature 分析的结果。对于您在请求中提供的每种功能类型,AnnotateImageResponse提供了一种 getter 方法来获取该功能分析的结果。例如,如果您使用LABEL_DETECTION功能分析了图像,则可以使用annotateImageResponse.getLabelAnnotationsList()从响应中检索结果。

AnnotateImageResponse由 Google Cloud Vision 库提供;有关更多详细信息,请咨询RPC referenceJavadoc。此外,您可以咨询Cloud Vision 文档来熟悉 API 的概念和功能。

163.2 检测图像标签示例

Image labeling是指产生描述图像内容的标签。以下是使用 Cloud Vision Spring 模板如何完成此操作的代码示例。

@Autowired
private ResourceLoader resourceLoader;

@Autowired
private CloudVisionTemplate cloudVisionTemplate;

public void processImage() {
  Resource imageResource = this.resourceLoader.getResource("my_image.jpg");
  AnnotateImageResponse response = this.cloudVisionTemplate.analyzeImage(
      imageResource, Type.LABEL_DETECTION);
  System.out.println("Image Classification results: " + response.getLabelAnnotationsList());
}

163.3 Sample

提供了Spring Boot 应用程序 samples,以显示如何使用 Cloud Vision 启动器和模板。