2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaでGoogle Cloud Vision API 使ってみた

Last updated at Posted at 2020-12-27

前提条件

・gradleのプロジェクト
・GCPのアカウントを登録していること
(アカウント登録、APIの利用、認証キー発行についてはこちらを参照してください)

ライブラリの追加

gradleのライブラリの追加はMaven Repositoryで調べるのが一番早いです。

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

認証情報の設定

GCPのAPIを利用するときに認証情報が必要になります。
GCPのコンソール上から認証情報を作成し、JSONファイルをダウンロードします

ダウンロードしたJSONファイルをプロジェクトの中に入れて、実行の構成環境追加(新規)
変数にはGOOGLE_APPLICATION_CREDENTIALS
値にはJsonファイルの絶対パス.json

サンプルコードの実行

google公式サンプルのURL

sample.java

void main() {
        try {
            //読み込み画像を指定
            String inputImgPath = "絶対パス.png";

            //解析結果をテキストファイルで抽出
            //result.txtは作っておく
            PrintStream outputResultPath = new PrintStream(new FileOutputStream("絶対パス/result.txt"), true);

            detectText(inputImgPath, outputResultPath);
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (Exception e) {
            e.printStackTrace();
       }
}
    //サンプルコードより引用
    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()) {
                //テキストを出力
                out.printf("Text: %s\n", annotation.getDescription());
                //座標を出力(いらないなら下の文を消す)
                out.printf("Position : %s\n", annotation.getBoundingPoly());
              }
            }
          }
        }
    }

下の画像の文字列を抽出してみました。
文字列.jpg

抽出結果です。

Text: 全思董アォント
『フェルトペン】
有料版:第二水準ぎの演字(6,700文字以上)录
無料版:教育演字(1,006字) +a..? 4绿
小学一年生の手書女字を元に作成した
オリジナル漢字もりもりの日本語フォントです。

収録の文字が正確に読み取られていませんでした。しかしこのフォントを読み込めるのは中々精度が高いですね。

文字の座標を出すとこんな感じで出してくれます。

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

Text: 全
Position : vertices {
  x: 76
  y: 58
}
vertices {
  x: 125
  y: 58
}
vertices {
  x: 125
  y: 101
}
vertices {
  x: 76
  y: 101
}
以下省略

今回はgradle利用者を対象に書いてみました。
ソースコードは理解するのに難しいですが、最初はコピペして使ってみてください。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?