I tried using Google Cloud Vision API in Java

Prerequisites

・ Gradle project ・ Registered GCP account (For account registration, API usage, and authentication key issuance, refer to here)

Add library

The fastest way to add a gradle library is to look it up in the Maven Repository (https://mvnrepository.com/).

compile group: 'com.google.cloud', name: 'google-cloud-vision', version: '1.100.9'

Credential settings

Authentication information is required when using the GCP API. Create credentials from the GCP console and download the JSON file

Put the downloaded JSON file in the project, execution configuration environmentadd (new) Variables are GOOGLE_APPLICATION_CREDENTIALS The value is the absolute path of the Json file.json

Executing sample code

URL of google official sample

sample.java



void main() {
        try {
            //Specify the read image
            String inputImgPath = "Absolute path.png ";

            //Extract the analysis result as a text file
            //result.Make txt
            PrintStream outputResultPath = new PrintStream(new FileOutputStream("Absolute path/result.txt"), true);

            detectText(inputImgPath, outputResultPath);
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (Exception e) {
            e.printStackTrace();
       }
}
    //Quoted from sample code
    public static void detectText(String filePath, PrintStream out) throws Exception, IOException {
          List<AnnotateImageRequest> requests = new ArrayList<>();

          ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));

          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()) {
                out.printf("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()) {
                //Output text
                out.printf("Text: %s\n", annotation.getDescription());
                //Output coordinates (delete the sentence below if you don't need it)
                out.printf("Position : %s\n", annotation.getBoundingPoly());
              }
            }
          }
        }
    }

I tried to extract the character string in the image below. 文字列.jpg

This is the extraction result.

Text:All thoughts
"Felt pen]
Paid version:Second-level writing(6,700 characters or more)Recording
Free version:Educational writing(1,006 characters) +a..?4 green
Created based on the handwritten female characters of the first grade of elementary school
Original Kanji Morimori Japanese font.

The recorded characters were not read correctly. However, it is very accurate to read this font.

If you put out the coordinates of the characters, it will come out like this.

Position : vertices {
  x: 33
  y: 53
}
vertices {
  x: 451
  y: 53
}
vertices {
  x: 451
  y: 310
}
vertices {
  x: 33
  y: 310
}

Text:all
Position : vertices {
  x: 76
  y: 58
}
vertices {
  x: 125
  y: 58
}
vertices {
  x: 125
  y: 101
}
vertices {
  x: 76
  y: 101
}
Omitted below

This time I wrote it for gradle users. The source code is difficult to understand, but try copying and using it first.

Recommended Posts

I tried using Google Cloud Vision API in Java
I tried using Elasticsearch API in Java
Try using GCP's Cloud Vision API in Java
I tried using Java8 Stream API
I tried using JWT in Java
I tried using Java REPL
I tried metaprogramming in Java
I tried Mastodon's Toot and Streaming API in Java
I tried using an extended for statement in Java
I tried using Java memo LocalDate
I tried using GoogleHttpClient of Java
I tried using Dapr in Java to facilitate microservice development
Try using the Stream API in Java
I tried the new era in Java
Try using JSON format API in Java
I tried using OpenCV with Java + Tomcat
I tried to make a talk application in Java using AI "A3RT"
[For beginners] I tried using DBUnit in Eclipse
ChatWork4j for using the ChatWork API in Java
[For beginners] I tried using JUnit 5 in Eclipse
[Java] API creation using Jerjey (Jax-rs) in eclipse
I tried to implement deep learning in Java
[API] I tried using the zip code search API
I tried to output multiplication table in Java
I tried to create Alexa skill in Java
Try using the COTOHA API parsing in Java
I tried using Gson
I tried using TestNG
I tried using Galasa
Zabbix API in Java
I tried using a database connection in Android development
I tried to implement Firebase push notification in Java
I tried to operate SQS using AWS Java SDK
# 2 [Note] I tried to calculate multiplication tables in Java.
I tried to create a Clova skill in Java
I tried to make a login function in Java
I tried using Log4j2 on a Java EE server
[Java] I tried to implement Yahoo API product search
I tried passing Java Silver in 2 weeks without knowing Java
I tried to implement the Euclidean algorithm in Java
~ I tried to learn functional programming in Java now ~
I tried scraping a stock chart using Java (Jsoup)
I tried to find out what changed in Java 9
Try using RocksDB in Java
I made roulette in Java.
I tried using azure cloud-init
Java Stream API in 5 minutes
I tried Drools (Java, InputStream)
I tried using Apache Wicket
Object-oriented child !? I tried Deep Learning in Java (trial edition)
I tried to introduce UI animation to Pokedex using Poké API
Elasticsearch Operation via REST API using Apache HttpClient in Java
Create QR code for Google Authenticator using ZXing in Java
I tried to convert a string to a LocalDate type in Java
Translate using Microsoft Translator Text API in Java (Japanese → English)
Tips for using Salesforce SOAP and Bulk API in Java
I tried to make a client of RESAS-API in Java
I was addicted to using Java's Stream API in Scala
I tried using the CameraX library with Android Java Fragment
I sent an email in Java
Export issues using JIRA's Java API