【问题标题】:how to use Google Cloud API - Application Default Credentials for text detection如何使用 Google Cloud API - 应用程序默认凭据进行文本检测
【发布时间】:2018-05-23 15:34:48
【问题描述】:

我使用以下 java 代码来检测图像的文本,但这里的问题是我无法正确验证

 public static void detectText() throws Exception, IOException {

    GoogleCredential credential = GoogleCredential.getApplicationDefault();

    List<AnnotateImageRequest> requests = new ArrayList<>();

    ByteString imgBytes = ByteString.readFrom(new FileInputStream("/home/buddika/Desktop/car_number_pate_16.jpeg"));

    Image img = Image.newBuilder().setContent(imgBytes).build();
    Feature feat = Feature.newBuilder().setType(Type.TEXT_DETECTION).build();
    AnnotateImageRequest request =
            AnnotateImageRequest.newBuilder()
                    .addFeatures(feat).setImage(img).build();
    requests.add(request);

    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
        List<AnnotateImageResponse> responses = response.getResponsesList();

        for (AnnotateImageResponse res : responses) {
            if (res.hasError()) {
                System.out.println("Error: %s\n"+ res.getError().getMessage());
                return;
            }

            // For full list of available annotations, see http://g.co/cloud/vision/docs
            for (EntityAnnotation annotation : res.getTextAnnotationsList()) {
                System.out.println("Text: %s\n" + annotation.getDescription());
                System.out.println("Position : %s\n" + annotation.getBoundingPoly());
            }
        }
    }
}

一旦执行此代码行,我就会收到以下错误消息

Exception in thread "main" java.io.IOException: The Application Default Credentials are not available. They are available if running on Google App Engine, Google Compute Engine, or Google Cloud Shell. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
    at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getDefaultCredential(DefaultCredentialProvider.java:98)
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:213)
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:191)
    at com.security.management.system.api.google_cloud_api.TextDetect.detectText(TextDetect.java:157)
    at com.security.management.system.api.google_cloud_api.TextDetect.main(TextDetect.java:48)

使用了以下库

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.cloud.vision.spi.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.*;
import com.google.cloud.vision.v1.Feature.Type;
import com.google.protobuf.ByteString;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

注意我也使用了 .json 文件,该文件也根据link 给出的指令下载了

注意:- 我在 .bashrc 文件中设置了 GOOGLE_APPLICATION_CREDENTIALS 变量

你能帮我解决这个问题吗

【问题讨论】:

  • 您阅读了整封邮件吗? The Application Default Credentials are not available. They are available if running on Google App Engine, Google Compute Engine, or Google Cloud Shell. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.你在 GAE 上运行吗?如果没有,您是否将环境变量设置为指向凭据?
  • 确实,您说您“使用了 .json 文件” - 请详细说明您如何使用它。
  • 我已将 .json 文件放在资源目录中并尝试使用此代码行来获取默认设置 GoogleCredential credential = GoogleCredential.getApplicationDefault(); @JonSkeet
  • @JimGarrison GoogleCredential credential = GoogleCredential.getApplicationDefault();这是我尝试过的方式
  • @BuddhikaAlwis:只是将 JSON 文件放在资源目录中不会有任何作用。它需要在执行时是文件系统上的一个文件,然后您需要设置 GOOGLE_APPLICATION_CREDENTIALS 环境变量来指定位置。此外,您在创建客户端时没有使用凭据...如果默认应用程序凭据有效,则根本不需要手动加载它们,但如果您 手动加载它们,你应该在ImageAnnotatorSettings中指定它们。

标签: java google-authentication google-cloud-vision


【解决方案1】:

我在 Spring Boot 中使用了谷歌云视觉 api。并且能够从图像中提取文本。

用于在属性下方添加的凭据。

application.properties 文件:

spring.cloud.gcp.project-id=mycloud-123456
spring.cloud.gcp.credentials.location=file:src/main/resources/service-account.json.

在 pom.xml 中添加了依赖

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

您的上述功能正在项目中工作。定义 GoogleCredential 的注释行。

@RequestMapping("/gettext")
 public String detectText() throws Exception, IOException {

        //GoogleCredential credential = GoogleCredential.getApplicationDefault();
    String finalText = "Ta Da! No value";
        List<AnnotateImageRequest> requests = new ArrayList<>();

        ByteString imgBytes = ByteString.readFrom(new FileInputStream("G:\\files\\type1.jpeg"));

        Image img = Image.newBuilder().setContent(imgBytes).build();
        Feature feat = Feature.newBuilder().setType(Type.TEXT_DETECTION).build();
        AnnotateImageRequest request =
                AnnotateImageRequest.newBuilder()
                        .addFeatures(feat).setImage(img).build();
        requests.add(request);

        try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
            BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
            List<AnnotateImageResponse> responses = response.getResponsesList();

            for (AnnotateImageResponse res : responses) {
                if (res.hasError()) {
                    System.out.println("Error: %s\n"+ res.getError().getMessage());
                    return "";
                }

                // For full list of available annotations, see http://g.co/cloud/vision/docs
                for (EntityAnnotation annotation : res.getTextAnnotationsList()) {
                    finalText += annotation.getDescription();
                    System.out.println("Text: %s\n" + annotation.getDescription());
                    System.out.println("Position : %s\n" + annotation.getBoundingPoly());
                }
            }
        }
        return finalText;
    }

注意:创建服务账号并下载json,步骤Create a service account

注意:我没有使用 GOOGLE_APPLICATION_CREDENTIALS 变量。所以删除了库 com.google.api.client.googleapis.auth.oauth2.GoogleCredential

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 2022-01-19
    • 2019-02-17
    • 1970-01-01
    • 2019-01-23
    • 2021-01-02
    相关资源
    最近更新 更多