光学式文字認識(OCR)による手書き入力検出
Vision API では、画像からテキストを検出、抽出できます。
DOCUMENT_TEXT_DETECTION
は画像(またはファイル)からテキストを抽出します。レスポンスは高密度のテキストやドキュメント向けに最適化されます。ページ、ブロック、段落、単語、改行の情報が JSON に含まれます。DOCUMENT_TEXT_DETECTION の用途の一つとして、画像内の手書き文字の検出が挙げられます。
使ってみる
Google Cloud を初めて使用される方は、アカウントを作成して、実際のシナリオでの Cloud Vision API のパフォーマンスを評価してください。新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $300 分を差し上げます。
Cloud Vision API の無料トライアルドキュメント テキスト検出リクエスト
Google Cloud プロジェクトと認証を設定する
Google Cloud プロジェクトをまだ作成していない場合は、ここで作成します。このセクションを開いて手順を確認してください。
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator
(
roles/resourcemanager.projectCreator
), which contains theresourcemanager.projects.create
permission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Vision API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin
), which contains theserviceusage.services.enable
permission. Learn how to grant roles. -
Install the Google Cloud CLI.
-
外部 ID プロバイダ(IdP)を使用している場合は、まず連携 ID を使用して gcloud CLI にログインする必要があります。
-
gcloud CLI を初期化するには、次のコマンドを実行します。
gcloud init
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator
(
roles/resourcemanager.projectCreator
), which contains theresourcemanager.projects.create
permission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Vision API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin
), which contains theserviceusage.services.enable
permission. Learn how to grant roles. -
Install the Google Cloud CLI.
-
外部 ID プロバイダ(IdP)を使用している場合は、まず連携 ID を使用して gcloud CLI にログインする必要があります。
-
gcloud CLI を初期化するには、次のコマンドを実行します。
gcloud init
- BASE64_ENCODED_IMAGE: バイナリ画像データの base64 表現(ASCII 文字列)。これは次のような文字列になります。
/9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==
- PROJECT_ID: 実際の Google Cloud プロジェクト ID。
- CLOUD_STORAGE_IMAGE_URI: Cloud Storage バケット内の有効な画像ファイルへのパス。少なくとも、ファイルに対する読み取り権限が必要です。例:
gs://cloud-samples-data/vision/handwriting_image.png
- PROJECT_ID: 実際の Google Cloud プロジェクト ID。
us
: 米国のみeu
: 欧州連合- https://eu-vision.googleapis.com/v1/projects/PROJECT_ID/locations/eu/images:annotate
- https://eu-vision.googleapis.com/v1/projects/PROJECT_ID/locations/eu/images:asyncBatchAnnotate
- https://eu-vision.googleapis.com/v1/projects/PROJECT_ID/locations/eu/files:annotate
- https://eu-vision.googleapis.com/v1/projects/PROJECT_ID/locations/eu/files:asyncBatchAnnotate
- REGION_ID: 有効なリージョンのロケーション ID のいずれか。
us
: 米国のみeu
: 欧州連合
- CLOUD_STORAGE_IMAGE_URI: Cloud Storage バケット内の有効な画像ファイルへのパス。少なくとも、ファイルに対する読み取り権限が必要です。例:
gs://cloud-samples-data/vision/handwriting_image.png
- PROJECT_ID: 実際の Google Cloud プロジェクト ID。
ローカル画像内のドキュメント テキストの検出
Vision API を使用して、ローカル画像ファイルに特徴検出を実行できます。
REST リクエストの場合は、リクエストの本文で画像ファイルのコンテンツを base64 エンコード文字列として送信します。
gcloud
とクライアント ライブラリ リクエストの場合は、リクエストにローカル イメージへのパスを指定します。
REST
リクエストのデータを使用する前に、次のように置き換えます。
HTTP メソッドと URL:
POST https://vision.googleapis.com/v1/images:annotate
リクエストの本文(JSON):
{ "requests": [ { "image": { "content": "BASE64_ENCODED_IMAGE" }, "features": [ { "type": "DOCUMENT_TEXT_DETECTION" } ] } ] }
リクエストを送信するには、次のいずれかのオプションを選択します。
curl
リクエスト本文を request.json
という名前のファイルに保存して、次のコマンドを実行します。
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: PROJECT_ID" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://vision.googleapis.com/v1/images:annotate"
PowerShell
リクエスト本文を request.json
という名前のファイルに保存して、次のコマンドを実行します。
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_ID" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/images:annotate" | Select-Object -Expand Content
リクエストが成功すると、サーバーは 200 OK
HTTP ステータス コードと JSON 形式のレスポンスを返します。
レスポンス
{ "responses": [ { "textAnnotations": [ { "locale": "en", "description": "O Google Cloud Platform\n", "boundingPoly": { "vertices": [ { "x": 14, "y": 11 }, { "x": 279, "y": 11 }, { "x": 279, "y": 37 }, { "x": 14, "y": 37 } ] } }, ], "fullTextAnnotation": { "pages": [ { "property": { "detectedLanguages": [ { "languageCode": "en" } ] }, "width": 281, "height": 44, "blocks": [ { "property": { "detectedLanguages": [ { "languageCode": "en" } ] }, "boundingBox": { "vertices": [ { "x": 14, "y": 11 }, { "x": 279, "y": 11 }, { "x": 279, "y": 37 }, { "x": 14, "y": 37 } ] }, "paragraphs": [ { "property": { "detectedLanguages": [ { "languageCode": "en" } ] }, "boundingBox": { "vertices": [ { "x": 14, "y": 11 }, { "x": 279, "y": 11 }, { "x": 279, "y": 37 }, { "x": 14, "y": 37 } ] }, "words": [ { "property": { "detectedLanguages": [ { "languageCode": "en" } ] }, "boundingBox": { "vertices": [ { "x": 14, "y": 11 }, { "x": 23, "y": 11 }, { "x": 23, "y": 37 }, { "x": 14, "y": 37 } ] }, "symbols": [ { "property": { "detectedLanguages": [ { "languageCode": "en" } ], "detectedBreak": { "type": "SPACE" } }, "boundingBox": { "vertices": [ { "x": 14, "y": 11 }, { "x": 23, "y": 11 }, { "x": 23, "y": 37 }, { "x": 14, "y": 37 } ] }, "text": "O" } ] }, ] } ], "blockType": "TEXT" } ] } ], "text": "Google Cloud Platform\n" } } ] }
Go
このサンプルを試す前に、Vision クイックスタート: クライアント ライブラリの使用にある Go の設定を完了してください。 詳細については、Vision Go API のリファレンス ドキュメントをご覧ください。
Vision に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。
// detectDocumentText gets the full document text from the Vision API for an image at the given file path.
func detectDocumentText(w io.Writer, file string) error {
ctx := context.Background()
client, err := vision.NewImageAnnotatorClient(ctx)
if err != nil {
return err
}
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
image, err := vision.NewImageFromReader(f)
if err != nil {
return err
}
annotation, err := client.DetectDocumentText(ctx, image, nil)
if err != nil {
return err
}
if annotation == nil {
fmt.Fprintln(w, "No text found.")
} else {
fmt.Fprintln(w, "Document Text:")
fmt.Fprintf(w, "%q\n", annotation.Text)
fmt.Fprintln(w, "Pages:")
for _, page := range annotation.Pages {
fmt.Fprintf(w, "\tConfidence: %f, Width: %d, Height: %d\n", page.Confidence, page.Width, page.Height)
fmt.Fprintln(w, "\tBlocks:")
for _, block := range page.Blocks {
fmt.Fprintf(w, "\t\tConfidence: %f, Block type: %v\n", block.Confidence, block.BlockType)
fmt.Fprintln(w, "\t\tParagraphs:")
for _, paragraph := range block.Paragraphs {
fmt.Fprintf(w, "\t\t\tConfidence: %f", paragraph.Confidence)
fmt.Fprintln(w, "\t\t\tWords:")
for _, word := range paragraph.Words {
symbols := make([]string, len(word.Symbols))
for i, s := range word.Symbols {
symbols[i] = s.Text
}
wordText := strings.Join(symbols, "")
fmt.Fprintf(w, "\t\t\t\tConfidence: %f, Symbols: %s\n", word.Confidence, wordText)
}
}
}
}
}
return nil
}
Java
このサンプルを試す前に、Vision API クイックスタート: クライアント ライブラリの使用にある Java の設定を完了してください。詳細については、Vision API Java のリファレンス ドキュメントをご覧ください。
public static void detectDocumentText(String filePath) throws 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.DOCUMENT_TEXT_DETECTION).build();
AnnotateImageRequest request =
AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
client.close();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.format("Error: %s%n", res.getError().getMessage());
return;
}
// For full list of available annotations, see http://g.co/cloud/vision/docs
TextAnnotation annotation = res.getFullTextAnnotation();
for (Page page : annotation.getPagesList()) {
String pageText = "";
for (Block block : page.getBlocksList()) {
String blockText = "";
for (Paragraph para : block.getParagraphsList()) {
String paraText = "";
for (Word word : para.getWordsList()) {
String wordText = "";
for (Symbol symbol : word.getSymbolsList()) {
wordText = wordText + symbol.getText();
System.out.format(
"Symbol text: %s (confidence: %f)%n",
symbol.getText(), symbol.getConfidence());
}
System.out.format(
"Word text: %s (confidence: %f)%n%n", wordText, word.getConfidence());
paraText = String.format("%s %s", paraText, wordText);
}
// Output Example using Paragraph:
System.out.println("%nParagraph: %n" + paraText);
System.out.format("Paragraph Confidence: %f%n", para.getConfidence());
blockText = blockText + paraText;
}
pageText = pageText + blockText;
}
}
System.out.println("%nComplete annotation:");
System.out.println(annotation.getText());
}
}
}
Node.js
このサンプルを試す前に、Vision クイックスタート: クライアント ライブラリの使用にある Node.js の設定を完了してください。詳細については、Vision Node.js API のリファレンス ドキュメントをご覧ください。
Vision に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。
// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');
// Creates a client
const client = new vision.ImageAnnotatorClient();
/**
* TODO(developer): Uncomment the following line before running the sample.
*/
// const fileName = 'Local image file, e.g. /path/to/image.png';
// Read a local image as a text document
const [result] = await client.documentTextDetection(fileName);
const fullTextAnnotation = result.fullTextAnnotation;
console.log(`Full text: ${fullTextAnnotation.text}`);
fullTextAnnotation.pages.forEach(page => {
page.blocks.forEach(block => {
console.log(`Block confidence: ${block.confidence}`);
block.paragraphs.forEach(paragraph => {
console.log(`Paragraph confidence: ${paragraph.confidence}`);
paragraph.words.forEach(word => {
const wordText = word.symbols.map(s => s.text).join('');
console.log(`Word text: ${wordText}`);
console.log(`Word confidence: ${word.confidence}`);
word.symbols.forEach(symbol => {
console.log(`Symbol text: ${symbol.text}`);
console.log(`Symbol confidence: ${symbol.confidence}`);
});
});
});
});
});
Python
このサンプルを試す前に、Vision クイックスタート: クライアント ライブラリの使用にある Python の設定を完了してください。詳細については、Vision Python API のリファレンス ドキュメントをご覧ください。
Vision に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。
def detect_document(path):
"""Detects document features in an image."""
from google.cloud import vision
client = vision.ImageAnnotatorClient()
with open(path, "rb") as image_file:
content = image_file.read()
image = vision.Image(content=content)
response = client.document_text_detection(image=image)
for page in response.full_text_annotation.pages:
for block in page.blocks:
print(f"\nBlock confidence: {block.confidence}\n")
for paragraph in block.paragraphs:
print("Paragraph confidence: {}".format(paragraph.confidence))
for word in paragraph.words:
word_text = "".join([symbol.text for symbol in word.symbols])
print(
"Word text: {} (confidence: {})".format(
word_text, word.confidence
)
)
for symbol in word.symbols:
print(
"\tSymbol: {} (confidence: {})".format(
symbol.text, symbol.confidence
)
)
if response.error.message:
raise Exception(
"{}\nFor more info on error messages, check: "
"https://cloud.google.com/apis/design/errors".format(response.error.message)
)
その他の言語
C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET 用の Vision リファレンス ドキュメントをご覧ください。
PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の Vision リファレンス ドキュメントをご覧ください。
Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の Vision リファレンス ドキュメントをご覧ください。
リモート画像でドキュメント テキストを検出する
Vision API を使用すると、Cloud Storage またはウェブ上にあるリモート画像ファイルに特徴検出を実行できます。リモート ファイル リクエストを送信するには、リクエストの本文でファイルのウェブ URL または Cloud Storage URI を指定します。
REST
リクエストのデータを使用する前に、次のように置き換えます。
HTTP メソッドと URL:
POST https://vision.googleapis.com/v1/images:annotate
リクエストの本文(JSON):
{ "requests": [ { "image": { "source": { "imageUri": "CLOUD_STORAGE_IMAGE_URI" } }, "features": [ { "type": "DOCUMENT_TEXT_DETECTION" } ] } ] }
リクエストを送信するには、次のいずれかのオプションを選択します。
curl
リクエスト本文を request.json
という名前のファイルに保存して、次のコマンドを実行します。
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: PROJECT_ID" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://vision.googleapis.com/v1/images:annotate"
PowerShell
リクエスト本文を request.json
という名前のファイルに保存して、次のコマンドを実行します。
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_ID" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/images:annotate" | Select-Object -Expand Content
リクエストが成功すると、サーバーは 200 OK
HTTP ステータス コードと JSON 形式のレスポンスを返します。
レスポンス
{ "responses": [ { "textAnnotations": [ { "locale": "en", "description": "O Google Cloud Platform\n", "boundingPoly": { "vertices": [ { "x": 14, "y": 11 }, { "x": 279, "y": 11 }, { "x": 279, "y": 37 }, { "x": 14, "y": 37 } ] } }, ], "fullTextAnnotation": { "pages": [ { "property": { "detectedLanguages": [ { "languageCode": "en" } ] }, "width": 281, "height": 44, "blocks": [ { "property": { "detectedLanguages": [ { "languageCode": "en" } ] }, "boundingBox": { "vertices": [ { "x": 14, "y": 11 }, { "x": 279, "y": 11 }, { "x": 279, "y": 37 }, { "x": 14, "y": 37 } ] }, "paragraphs": [ { "property": { "detectedLanguages": [ { "languageCode": "en" } ] }, "boundingBox": { "vertices": [ { "x": 14, "y": 11 }, { "x": 279, "y": 11 }, { "x": 279, "y": 37 }, { "x": 14, "y": 37 } ] }, "words": [ { "property": { "detectedLanguages": [ { "languageCode": "en" } ] }, "boundingBox": { "vertices": [ { "x": 14, "y": 11 }, { "x": 23, "y": 11 }, { "x": 23, "y": 37 }, { "x": 14, "y": 37 } ] }, "symbols": [ { "property": { "detectedLanguages": [ { "languageCode": "en" } ], "detectedBreak": { "type": "SPACE" } }, "boundingBox": { "vertices": [ { "x": 14, "y": 11 }, { "x": 23, "y": 11 }, { "x": 23, "y": 37 }, { "x": 14, "y": 37 } ] }, "text": "O" } ] }, ] } ], "blockType": "TEXT" } ] } ], "text": "Google Cloud Platform\n" } } ] }
Go
このサンプルを試す前に、Vision クイックスタート: クライアント ライブラリの使用にある Go の設定を完了してください。 詳細については、Vision Go API のリファレンス ドキュメントをご覧ください。
Vision に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。
// detectDocumentText gets the full document text from the Vision API for an image at the given file path.
func detectDocumentTextURI(w io.Writer, file string) error {
ctx := context.Background()
client, err := vision.NewImageAnnotatorClient(ctx)
if err != nil {
return err
}
image := vision.NewImageFromURI(file)
annotation, err := client.DetectDocumentText(ctx, image, nil)
if err != nil {
return err
}
if annotation == nil {
fmt.Fprintln(w, "No text found.")
} else {
fmt.Fprintln(w, "Document Text:")
fmt.Fprintf(w, "%q\n", annotation.Text)
fmt.Fprintln(w, "Pages:")
for _, page := range annotation.Pages {
fmt.Fprintf(w, "\tConfidence: %f, Width: %d, Height: %d\n", page.Confidence, page.Width, page.Height)
fmt.Fprintln(w, "\tBlocks:")
for _, block := range page.Blocks {
fmt.Fprintf(w, "\t\tConfidence: %f, Block type: %v\n", block.Confidence, block.BlockType)
fmt.Fprintln(w, "\t\tParagraphs:")
for _, paragraph := range block.Paragraphs {
fmt.Fprintf(w, "\t\t\tConfidence: %f", paragraph.Confidence)
fmt.Fprintln(w, "\t\t\tWords:")
for _, word := range paragraph.Words {
symbols := make([]string, len(word.Symbols))
for i, s := range word.Symbols {
symbols[i] = s.Text
}
wordText := strings.Join(symbols, "")
fmt.Fprintf(w, "\t\t\t\tConfidence: %f, Symbols: %s\n", word.Confidence, wordText)
}
}
}
}
}
return nil
}
Java
このサンプルを試す前に、Vision API クイックスタート: クライアント ライブラリの使用にある Java の設定を完了してください。詳細については、Vision API Java のリファレンス ドキュメントをご覧ください。
public static void detectDocumentTextGcs(String gcsPath) throws IOException {
List<AnnotateImageRequest> requests = new ArrayList<>();
ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
Image img = Image.newBuilder().setSource(imgSource).build();
Feature feat = Feature.newBuilder().setType(Type.DOCUMENT_TEXT_DETECTION).build();
AnnotateImageRequest request =
AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
client.close();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.format("Error: %s%n", res.getError().getMessage());
return;
}
// For full list of available annotations, see http://g.co/cloud/vision/docs
TextAnnotation annotation = res.getFullTextAnnotation();
for (Page page : annotation.getPagesList()) {
String pageText = "";
for (Block block : page.getBlocksList()) {
String blockText = "";
for (Paragraph para : block.getParagraphsList()) {
String paraText = "";
for (Word word : para.getWordsList()) {
String wordText = "";
for (Symbol symbol : word.getSymbolsList()) {
wordText = wordText + symbol.getText();
System.out.format(
"Symbol text: %s (confidence: %f)%n",
symbol.getText(), symbol.getConfidence());
}
System.out.format(
"Word text: %s (confidence: %f)%n%n", wordText, word.getConfidence());
paraText = String.format("%s %s", paraText, wordText);
}
// Output Example using Paragraph:
System.out.println("%nParagraph: %n" + paraText);
System.out.format("Paragraph Confidence: %f%n", para.getConfidence());
blockText = blockText + paraText;
}
pageText = pageText + blockText;
}
}
System.out.println("%nComplete annotation:");
System.out.println(annotation.getText());
}
}
}
Node.js
このサンプルを試す前に、Vision クイックスタート: クライアント ライブラリの使用にある Node.js の設定を完了してください。詳細については、Vision Node.js API のリファレンス ドキュメントをご覧ください。
Vision に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。
// Imports the Google Cloud client libraries
const vision = require('@google-cloud/vision');
// Creates a client
const client = new vision.ImageAnnotatorClient();
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
// const bucketName = 'Bucket where the file resides, e.g. my-bucket';
// const fileName = 'Path to file within bucket, e.g. path/to/image.png';
// Read a remote image as a text document
const [result] = await client.documentTextDetection(
`gs://${bucketName}/${fileName}`
);
const fullTextAnnotation = result.fullTextAnnotation;
console.log(fullTextAnnotation.text);
Python
このサンプルを試す前に、Vision クイックスタート: クライアント ライブラリの使用にある Python の設定を完了してください。詳細については、Vision Python API のリファレンス ドキュメントをご覧ください。
Vision に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。
def detect_document_uri(uri):
"""Detects document features in the file located in Google Cloud
Storage."""
from google.cloud import vision
client = vision.ImageAnnotatorClient()
image = vision.Image()
image.source.image_uri = uri
response = client.document_text_detection(image=image)
for page in response.full_text_annotation.pages:
for block in page.blocks:
print(f"\nBlock confidence: {block.confidence}\n")
for paragraph in block.paragraphs:
print("Paragraph confidence: {}".format(paragraph.confidence))
for word in paragraph.words:
word_text = "".join([symbol.text for symbol in word.symbols])
print(
"Word text: {} (confidence: {})".format(
word_text, word.confidence
)
)
for symbol in word.symbols:
print(
"\tSymbol: {} (confidence: {})".format(
symbol.text, symbol.confidence
)
)
if response.error.message:
raise Exception(
"{}\nFor more info on error messages, check: "
"https://cloud.google.com/apis/design/errors".format(response.error.message)
)
gcloud
手書き入力検出を行う場合は、次の例で示すように gcloud ml vision detect-document
コマンドを実行します。
gcloud ml vision detect-document gs://cloud-samples-data/vision/handwriting_image.png
その他の言語
C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET 用の Vision リファレンス ドキュメントをご覧ください。
PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の Vision リファレンス ドキュメントをご覧ください。
Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の Vision リファレンス ドキュメントをご覧ください。
言語を指定する(省略可)
どちらのタイプの OCR リクエストも 1 つ以上の languageHints
をサポートしています。これにより、画像内のテキストの言語を指定します。ただし、値を省略すると自動言語検出が有効になるため、通常は値を空にすることで最善の結果が得られます。ラテン アルファベット系の言語の場合、languageHints
の設定は不要です。非常にまれですが、画像内のテキストの言語がわかっている場合は、ヒントを設定すると結果が少し良くなります。(ただし、ヒントを間違えると逆効果になります)。サポートされる言語以外の言語が 1 つでも指定されていると、テキスト検出でエラーが返されます。
言語のヒントを指定する場合は、次のサンプルに示すように、リクエストの本文(request.json
ファイル)を変更し、以下の imageContext.languageHints
フィールドにサポート対象言語の文字列を指定します。
{ "requests": [ { "image": { "source": { "imageUri": "IMAGE_URL" } }, "features": [ { "type": "DOCUMENT_TEXT_DETECTION" } ], "imageContext": { "languageHints": ["en-t-i0-handwrit"] } } ] }
マルチリージョンのサポート
大陸レベルでデータ ストレージと OCR 処理を指定できるようになりました。現在サポートされているリージョンは次のとおりです。
ロケーション
Cloud Vision では、プロジェクトのリソースが保存、処理されるロケーションをある程度制御できます。特に、データを欧州連合でのみ保存して処理するように Cloud Vision を構成できます。
デフォルトでは、Cloud Vision はリソースをグローバル ロケーションに保存して処理します。つまり、Cloud Vision は、リソースが特定のロケーションやリージョンに留まることを保証しません。ロケーションとして欧州連合を選択した場合、欧州連合でのみデータが保存され、処理されます。ユーザーはどこからでもデータにアクセスできます。
API を使用してロケーションを設定する
Vision API は、グローバル API エンドポイント(vision.googleapis.com
)と、2 つのリージョン ベースのエンドポイント(EU エンドポイント eu-vision.googleapis.com
と米国エンドポイント us-vision.googleapis.com
)をサポートしています。これらのエンドポイントはリージョン固有の処理に使用します。たとえば、EU でのみデータを保存して処理する場合は、REST API 呼び出しに vision.googleapis.com
ではなく URI eu-vision.googleapis.com
を使用します。
米国でのみデータを保存して処理する場合は、前述の方法で米国のエンドポイント(us-vision.googleapis.com
)を使用します。
クライアント ライブラリを使用してロケーションを設定する
Vision API クライアント ライブラリは、デフォルトでグローバル API エンドポイント(vision.googleapis.com
)にアクセスします。EU でのみデータを保存して処理するには、エンドポイント(eu-vision.googleapis.com
)を明示的に設定する必要があります。以下のコードサンプルは、この設定を構成する方法を示しています。
REST
リクエストのデータを使用する前に、次のように置き換えます。
HTTP メソッドと URL:
POST https://REGION_ID-vision.googleapis.com/v1/projects/PROJECT_ID/locations/REGION_ID/images:annotate
リクエストの本文(JSON):
{ "requests": [ { "image": { "source": { "imageUri": "CLOUD_STORAGE_IMAGE_URI" } }, "features": [ { "type": "DOCUMENT_TEXT_DETECTION" } ] } ] }
リクエストを送信するには、次のいずれかのオプションを選択します。
curl
リクエスト本文を request.json
という名前のファイルに保存して、次のコマンドを実行します。
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: PROJECT_ID" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://REGION_ID-vision.googleapis.com/v1/projects/PROJECT_ID/locations/REGION_ID/images:annotate"
PowerShell
リクエスト本文を request.json
という名前のファイルに保存して、次のコマンドを実行します。
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_ID" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://REGION_ID-vision.googleapis.com/v1/projects/PROJECT_ID/locations/REGION_ID/images:annotate" | Select-Object -Expand Content
リクエストが成功すると、サーバーは 200 OK
HTTP ステータス コードと JSON 形式のレスポンスを返します。
レスポンス
{ "responses": [ { "textAnnotations": [ { "locale": "en", "description": "O Google Cloud Platform\n", "boundingPoly": { "vertices": [ { "x": 14, "y": 11 }, { "x": 279, "y": 11 }, { "x": 279, "y": 37 }, { "x": 14, "y": 37 } ] } }, ], "fullTextAnnotation": { "pages": [ { "property": { "detectedLanguages": [ { "languageCode": "en" } ] }, "width": 281, "height": 44, "blocks": [ { "property": { "detectedLanguages": [ { "languageCode": "en" } ] }, "boundingBox": { "vertices": [ { "x": 14, "y": 11 }, { "x": 279, "y": 11 }, { "x": 279, "y": 37 }, { "x": 14, "y": 37 } ] }, "paragraphs": [ { "property": { "detectedLanguages": [ { "languageCode": "en" } ] }, "boundingBox": { "vertices": [ { "x": 14, "y": 11 }, { "x": 279, "y": 11 }, { "x": 279, "y": 37 }, { "x": 14, "y": 37 } ] }, "words": [ { "property": { "detectedLanguages": [ { "languageCode": "en" } ] }, "boundingBox": { "vertices": [ { "x": 14, "y": 11 }, { "x": 23, "y": 11 }, { "x": 23, "y": 37 }, { "x": 14, "y": 37 } ] }, "symbols": [ { "property": { "detectedLanguages": [ { "languageCode": "en" } ], "detectedBreak": { "type": "SPACE" } }, "boundingBox": { "vertices": [ { "x": 14, "y": 11 }, { "x": 23, "y": 11 }, { "x": 23, "y": 37 }, { "x": 14, "y": 37 } ] }, "text": "O" } ] }, ] } ], "blockType": "TEXT" } ] } ], "text": "Google Cloud Platform\n" } } ] }
Go
このサンプルを試す前に、Vision クイックスタート: クライアント ライブラリの使用にある Go の設定を完了してください。 詳細については、Vision Go API のリファレンス ドキュメントをご覧ください。
Vision に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。
import (
"context"
"fmt"
vision "cloud.google.com/go/vision/apiv1"
"google.golang.org/api/option"
)
// setEndpoint changes your endpoint.
func setEndpoint(endpoint string) error {
// endpoint := "eu-vision.googleapis.com:443"
ctx := context.Background()
client, err := vision.NewImageAnnotatorClient(ctx, option.WithEndpoint(endpoint))
if err != nil {
return fmt.Errorf("NewImageAnnotatorClient: %w", err)
}
defer client.Close()
return nil
}
Java
このサンプルを試す前に、Vision API クイックスタート: クライアント ライブラリの使用にある Java の設定を完了してください。詳細については、Vision API Java のリファレンス ドキュメントをご覧ください。
ImageAnnotatorSettings settings =
ImageAnnotatorSettings.newBuilder().setEndpoint("eu-vision.googleapis.com:443").build();
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
ImageAnnotatorClient client = ImageAnnotatorClient.create(settings);
Node.js
このサンプルを試す前に、Vision クイックスタート: クライアント ライブラリの使用にある Node.js の設定を完了してください。詳細については、Vision Node.js API のリファレンス ドキュメントをご覧ください。
Vision に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。
// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');
async function setEndpoint() {
// Specifies the location of the api endpoint
const clientOptions = {apiEndpoint: 'eu-vision.googleapis.com'};
// Creates a client
const client = new vision.ImageAnnotatorClient(clientOptions);
// Performs text detection on the image file
const [result] = await client.textDetection('./resources/wakeupcat.jpg');
const labels = result.textAnnotations;
console.log('Text:');
labels.forEach(label => console.log(label.description));
}
setEndpoint();
Python
このサンプルを試す前に、Vision クイックスタート: クライアント ライブラリの使用にある Python の設定を完了してください。詳細については、Vision Python API のリファレンス ドキュメントをご覧ください。
Vision に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。
from google.cloud import vision
client_options = {"api_endpoint": "eu-vision.googleapis.com"}
client = vision.ImageAnnotatorClient(client_options=client_options)
試してみる
以下のツールのテキスト検出とドキュメント テキスト検出をお試しください。[実行] をクリックして、すでに指定済みの画像(gs://cloud-samples-data/vision/handwriting_image.png
)を使用することも、独自の画像を指定することもできます。
リクエストの本文:
{ "requests": [ { "features": [ { "type": "DOCUMENT_TEXT_DETECTION" } ], "image": { "source": { "imageUri": "gs://cloud-samples-data/vision/handwriting_image.png" } } } ] }