简体   繁体   中英

how to use Google Cloud API - Application Default Credentials for text detection

i have used following java code to detect a text of a image, but here problem is i couldn't able to authenticate correctly

 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());
            }
        }
    }
}

i am having below error message once execute this code lines

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)

following libs were used

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;

note i have used the .json file also which downloaded accring to the instruction given from this link

note :- i have set the GOOGLE_APPLICATION_CREDENTIALS variable in .bashrc file

could you please help me on this issue

I used google cloud vision api with spring boot. And able to extract text from images.

for credentials added below properties.

application.properties file:

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

added dependency in pom.xml

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

Your above function is working in the project. commented line which were defining 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;
    }

Note: Created service account and downloaded json, steps Create a service account

Note: I haven't used the GOOGLE_APPLICATION_CREDENTIALS variable. so deleted library com.google.api.client.googleapis.auth.oauth2.GoogleCredential .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM