光学式文字認識(OCR)による手書き入力検出
Vision API では、画像からテキストを検出、抽出できます。
DOCUMENT_TEXT_DETECTIONは画像(またはファイル)からテキストを抽出します。レスポンスは高密度のテキストやドキュメント向けに最適化されます。ページ、ブロック、段落、単語、改行の情報が JSON に含まれます。
DOCUMENT_TEXT_DETECTION の用途の一つとして、画像内の手書き文字の検出が挙げられます。

ドキュメント テキストの検出リクエスト
Google Cloud プロジェクトと認証を設定する
Google Cloud プロジェクトをまだ作成していない場合は、ここで作成します。このセクションを開いて手順を確認してください。
-
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 role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. 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.enablepermission. Learn how to grant roles. -
Install the Google Cloud CLI.
-
連携 ID を使用するように gcloud CLI を構成します。
詳細については、連携 ID を使用して gcloud CLI にログインするをご覧ください。
-
gcloud CLI を初期化するには、次のコマンドを実行します。
gcloud initローカル画像にあるドキュメント テキストを検出する
Vision API を使用して、ローカル画像ファイルに特徴検出を実行できます。
REST リクエストの場合は、リクエストの本文で画像ファイルのコンテンツを base64 エンコード文字列として送信します。
gcloudとクライアント ライブラリ リクエストの場合は、リクエストにローカル イメージへのパスを指定します。REST
リクエストのデータを使用する前に、次のように置き換えます。
- BASE64_ENCODED_IMAGE: バイナリ画像データの base64 表現(ASCII 文字列)。これは次のような文字列になります。
/9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==
- PROJECT_ID: 実際の Google Cloud プロジェクト ID。
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 OKHTTP ステータス コードと 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
リクエストのデータを使用する前に、次のように置き換えます。
- CLOUD_STORAGE_IMAGE_URI: Cloud Storage バケット内の有効な画像ファイルへのパス。少なくとも、ファイルに対する読み取り権限が必要です。例:
gs://cloud-samples-data/vision/handwriting_image.png
- PROJECT_ID: 実際の Google Cloud プロジェクト ID。
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 OKHTTP ステータス コードと 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 処理を指定できるようになりました。現在サポートされているリージョンは次のとおりです。
us: 米国のみeu: 欧州連合
ロケーション
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ではなく URIeu-vision.googleapis.comを使用します。- 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
米国でのみデータを保存して処理する場合は、前述の方法で米国のエンドポイント(
us-vision.googleapis.com)を使用します。クライアント ライブラリを使用してロケーションを設定する
Vision API クライアント ライブラリは、デフォルトでグローバル API エンドポイント(
vision.googleapis.com)にアクセスします。欧州連合でのみデータを保存して処理するには、エンドポイント(eu-vision.googleapis.com)を明示的に設定する必要があります。以下のサンプルコードは、この設定を構成する方法を示しています。REST
リクエストのデータを使用する前に、次のように置き換えます。
- REGION_ID: 有効なリージョンのロケーション ID のいずれか。
us: 米国のみeu: 欧州連合
- CLOUD_STORAGE_IMAGE_URI: Cloud Storage バケット内の有効な画像ファイルへのパス。少なくとも、ファイルに対する読み取り権限が必要です。例:
gs://cloud-samples-data/vision/handwriting_image.png
- PROJECT_ID: 実際の Google Cloud プロジェクト ID。
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 OKHTTP ステータス コードと 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" } } } ] } - BASE64_ENCODED_IMAGE: バイナリ画像データの base64 表現(ASCII 文字列)。これは次のような文字列になります。