Handschrifterkennung mit optischer Zeichenerkennung (Optical Character Recognition, OCR)
Mithilfe der Vision API können Sie Text in Bildern erkennen und extrahieren:
DOCUMENT_TEXT_DETECTION
extrahiert Text aus einem Bild (oder einer Datei), wobei die Antwort für Fließtext und Dokumente optimiert ist. Die JSON-Datei enthält Informationen zu Seite, Block, Absatz, Wort und Worttrennung.Mit DOCUMENT_TEXT_DETECTION kann beispielsweise Handschrift in einem Bild erkannt werden.
Überzeugen Sie sich selbst
Wenn Sie mit Google Cloud noch nicht vertraut sind, erstellen Sie ein Konto, um sich von der Leistungsfähigkeit der Cloud Vision API in der Praxis zu überzeugen. Neukunden erhalten außerdem ein Guthaben von 300 $, um Arbeitslasten auszuführen, zu testen und bereitzustellen.
Cloud Vision API kostenlos testenAnfragen zur Erkennung von Dokumenttext
Projekt in Google Cloud und Authentifizierung einrichten
Wenn Sie noch kein Projekt in Google Cloud erstellt haben, tun Sie dies jetzt. Erweitern Sie diesen Abschnitt, um die Anleitung einzublenden.
- 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.
-
Wenn Sie einen externen Identitätsanbieter (IdP) verwenden, müssen Sie sich zuerst mit Ihrer föderierten Identität in der gcloud CLI anmelden.
-
Führen Sie folgenden Befehl aus, um die gcloud CLI zu initialisieren:
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.
-
Wenn Sie einen externen Identitätsanbieter (IdP) verwenden, müssen Sie sich zuerst mit Ihrer föderierten Identität in der gcloud CLI anmelden.
-
Führen Sie folgenden Befehl aus, um die gcloud CLI zu initialisieren:
gcloud init
- BASE64_ENCODED_IMAGE: Die Base64-Darstellung (ASCII-String) der Binärbilddaten. Dieser String sollte in etwa so aussehen:
/9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==
- PROJECT_ID: Projekt-ID in Google Cloud .
- CLOUD_STORAGE_IMAGE_URI: Der Pfad zu einer gültigen Bilddatei in einem Cloud Storage-Bucket. Sie müssen zumindest Leseberechtigungen für die Datei haben.
Beispiel:
gs://cloud-samples-data/vision/handwriting_image.png
- PROJECT_ID: Projekt-ID in Google Cloud .
us
: nur Festland-USAeu
: die Europäischen Union- 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: eine der gültigen regionalen
Standortkennungen:
us
: nur Festland-USAeu
: die Europäischen Union
- CLOUD_STORAGE_IMAGE_URI: der Pfad zu einer gültigen Bilddatei in einem Cloud Storage-Bucket. Sie müssen zumindest Leseberechtigungen für die Datei haben.
Beispiel:
gs://cloud-samples-data/vision/handwriting_image.png
- PROJECT_ID: Projekt-ID in Google Cloud .
Erkennt Dokumenttext in einem lokalen Bild
Sie können die Vision API für die Featureerkennung in einer lokalen Bilddatei verwenden.
Senden Sie bei REST-Anfragen den Inhalt der Bilddatei als base64-codierten String im Text Ihrer Anfrage.
Geben Sie für Anfragen zu gcloud
und Clientbibliotheken den Pfad zu einem lokalen Image in Ihrer Anfrage an.
REST
Ersetzen Sie folgende Werte in den Anfragedaten:
HTTP-Methode und URL:
POST https://vision.googleapis.com/v1/images:annotate
JSON-Text der Anfrage:
{ "requests": [ { "image": { "content": "BASE64_ENCODED_IMAGE" }, "features": [ { "type": "DOCUMENT_TEXT_DETECTION" } ] } ] }
Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:
curl
Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json
und führen Sie den folgenden Befehl aus:
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
Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json
und führen Sie den folgenden Befehl aus:
$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
Wenn die Anfrage erfolgreich ist, gibt der Server den HTTP-Statuscode 200 OK
und die Antwort im JSON-Format zurück.
Antwort
{ "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
Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Go-Einrichtungsanleitung in der Vision-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Go-Referenzdokumentation zur Vision API.
Richten Sie zur Authentifizierung bei Vision die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter ADC für eine lokale Entwicklungsumgebung einrichten.
// 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
Bevor Sie dieses Beispiel anwenden, folgen Sie der Anleitung für die Einrichtung von Java in der Vision API-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Java-Referenzdokumentation zur Vision API.
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
Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Node.js-Einrichtungsanleitung in der Vision-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Node.js-Referenzdokumentation zur Vision API.
Richten Sie zur Authentifizierung bei Vision die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter ADC für eine lokale Entwicklungsumgebung einrichten.
// 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
Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Python-Einrichtungsanleitung in der Vision-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Python-Referenzdokumentation zur Vision API.
Richten Sie zur Authentifizierung bei Vision die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter ADC für eine lokale Entwicklungsumgebung einrichten.
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)
)
Weitere Sprachen
C#: Folgen Sie der Anleitung zum Einrichten von C# auf der Seite der Clientbibliotheken und rufen Sie dann die Vision-Referenzdokumentation für .NET auf.
PHP: Folgen Sie der Anleitung zum Einrichten von PHP auf der Seite der Clientbibliotheken und rufen Sie dann die Vision-Referenzdokumentation für PHP auf.
Ruby: Folgen Sie der Anleitung zur Einrichtung von Ruby auf der Seite der Clientbibliotheken und rufen Sie dann die Vision-Referenzdokumentation für Ruby auf.
Dokumenttext in einem Remotebild erkennen
Sie können die Vision API verwenden, um eine Featureerkennung für eine Remote-Bilddatei durchzuführen, die sich in Cloud Storage oder im Web befindet. Zum Senden einer Remote-Dateianfrage geben Sie die URL oder den Cloud Storage-URI der Datei im Anfragetext an.
REST
Ersetzen Sie folgende Werte in den Anfragedaten:
HTTP-Methode und URL:
POST https://vision.googleapis.com/v1/images:annotate
JSON-Text der Anfrage:
{ "requests": [ { "image": { "source": { "imageUri": "CLOUD_STORAGE_IMAGE_URI" } }, "features": [ { "type": "DOCUMENT_TEXT_DETECTION" } ] } ] }
Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:
curl
Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json
und führen Sie den folgenden Befehl aus:
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
Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json
und führen Sie den folgenden Befehl aus:
$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
Wenn die Anfrage erfolgreich ist, gibt der Server den HTTP-Statuscode 200 OK
und die Antwort im JSON-Format zurück.
Antwort
{ "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
Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Go-Einrichtungsanleitung in der Vision-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Go-Referenzdokumentation zur Vision API.
Richten Sie zur Authentifizierung bei Vision die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter ADC für eine lokale Entwicklungsumgebung einrichten.
// 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
Bevor Sie dieses Beispiel anwenden, folgen Sie der Anleitung für die Einrichtung von Java in der Vision API-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Java-Referenzdokumentation zur Vision API.
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
Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Node.js-Einrichtungsanleitung in der Vision-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Node.js-Referenzdokumentation zur Vision API.
Richten Sie zur Authentifizierung bei Vision die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter ADC für eine lokale Entwicklungsumgebung einrichten.
// 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
Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Python-Einrichtungsanleitung in der Vision-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Python-Referenzdokumentation zur Vision API.
Richten Sie zur Authentifizierung bei Vision die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter ADC für eine lokale Entwicklungsumgebung einrichten.
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
Verwenden Sie für die Erkennung von Handschrift den Befehl gcloud ml vision detect-document
, wie im folgenden Beispiel gezeigt:
gcloud ml vision detect-document gs://cloud-samples-data/vision/handwriting_image.png
Weitere Sprachen
C#: Folgen Sie der Anleitung zum Einrichten von C# auf der Seite der Clientbibliotheken und rufen Sie dann die Vision-Referenzdokumentation für .NET auf.
PHP: Folgen Sie der Anleitung zum Einrichten von PHP auf der Seite der Clientbibliotheken und rufen Sie dann die Vision-Referenzdokumentation für PHP auf.
Ruby: Folgen Sie der Anleitung zur Einrichtung von Ruby auf der Seite der Clientbibliotheken und rufen Sie dann die Vision-Referenzdokumentation für Ruby auf.
Sprache festlegen (optional)
Beide Arten von OCR-Anfragen unterstützen einen oder mehrere languageHints
, die die Sprache eines beliebigen Textes im Bild angeben. Ein leerer Wert liefert jedoch in der Regel die besten Ergebnisse, weil das Weglassen eines Werts die automatische Spracherkennung ermöglicht. Bei Sprachen, die auf dem lateinischen Alphabet basieren, ist die Einstellung languageHints
nicht erforderlich. In seltenen Fällen, wenn die Sprache des Textes im Bild bekannt ist, hilft die Festlegung eines Hinweises dabei, bessere Ergebnisse zu erzielen. Dies kann jedoch ein erhebliches Hindernis sein, falls der Hinweis falsch ist. Wenn eine oder mehrere der angegebenen Sprachen nicht zu den unterstützten Sprachen zählen, gibt die Texterkennung einen Fehler zurück.
Wenn Sie einen Sprachhinweis angeben möchten, ändern Sie den Text Ihrer Anfrage (Datei request.json
), um den String einer der unterstützten Sprachen im Feld imageContext.languageHints
bereitzustellen, wie im folgenden Beispiel gezeigt:
{ "requests": [ { "image": { "source": { "imageUri": "IMAGE_URL" } }, "features": [ { "type": "DOCUMENT_TEXT_DETECTION" } ], "imageContext": { "languageHints": ["en-t-i0-handwrit"] } } ] }
Unterstützung für mehrere Regionen
Sie können jetzt Datenspeicher- und OCR-Verarbeitung auf Kontinentenebene festlegen. Folgende Regionen werden derzeit unterstützt:
Standorte
In Cloud Vision können Sie steuern, wo die Ressourcen für Ihr Projekt gespeichert und verarbeitet werden. Insbesondere können Sie Cloud Vision so konfigurieren, dass Ihre Daten nur in der Europäischen Union gespeichert und verarbeitet werden.
Standardmäßig speichert und verarbeitet Cloud Vision Ressourcen an einem globalen Standort. Das bedeutet, dass Cloud Vision nicht garantiert, dass Ihre Ressourcen an einem bestimmten Standort oder in einer bestimmten Region verbleiben. Wenn Sie den Standort Europäische Union auswählen, speichert Google Ihre Daten und verarbeitet sie nur in der Europäischen Union. Sie und Ihre Nutzer können von jedem Standort aus auf die Daten zugreifen.
Standort mithilfe der API festlegen
Die Vision API unterstützt einen globalen API-Endpunkt (vision.googleapis.com
) und zwei regionsbasierte Endpunkte: einen EU-Endpunkt (eu-vision.googleapis.com
) und einen US-Endpunkt (us-vision.googleapis.com
). Verwenden Sie diese Endpunkte für die regionsspezifische Verarbeitung. Wenn Sie Ihre Daten beispielsweise nur in der Europäischen Union speichern und verarbeiten möchten, verwenden Sie für REST API-Aufrufe den URI eu-vision.googleapis.com
anstelle von vision.googleapis.com
:
Wenn Sie Ihre Daten nur in den USA speichern und verarbeiten möchten, verwenden Sie bei den vorherigen Methoden den US-Endpunkt (us-vision.googleapis.com
).
Standort mithilfe von Clientbibliotheken festlegen
Die Vision API-Clientbibliotheken greifen standardmäßig auf den globalen API-Endpunkt (vision.googleapis.com
) zu. Wenn Sie Ihre Daten nur in der Europäischen Union speichern und verarbeiten möchten, müssen Sie den Endpunkt (eu-vision.googleapis.com
) explizit festlegen. Die folgenden Codebeispiele zeigen, wie diese Einstellung konfiguriert wird.
REST
Ersetzen Sie folgende Werte in den Anfragedaten:
HTTP-Methode und URL:
POST https://REGION_ID-vision.googleapis.com/v1/projects/PROJECT_ID/locations/REGION_ID/images:annotate
JSON-Text der Anfrage:
{ "requests": [ { "image": { "source": { "imageUri": "CLOUD_STORAGE_IMAGE_URI" } }, "features": [ { "type": "DOCUMENT_TEXT_DETECTION" } ] } ] }
Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:
curl
Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json
und führen Sie den folgenden Befehl aus:
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
Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json
und führen Sie den folgenden Befehl aus:
$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
Wenn die Anfrage erfolgreich ist, gibt der Server den HTTP-Statuscode 200 OK
und die Antwort im JSON-Format zurück.
Antwort
{ "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
Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Go-Einrichtungsanleitung in der Vision-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Go-Referenzdokumentation zur Vision API.
Richten Sie zur Authentifizierung bei Vision die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter ADC für eine lokale Entwicklungsumgebung einrichten.
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
Bevor Sie dieses Beispiel anwenden, folgen Sie der Anleitung für die Einrichtung von Java in der Vision API-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Java-Referenzdokumentation zur Vision API.
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
Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Node.js-Einrichtungsanleitung in der Vision-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Node.js-Referenzdokumentation zur Vision API.
Richten Sie zur Authentifizierung bei Vision die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter ADC für eine lokale Entwicklungsumgebung einrichten.
// 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
Bevor Sie dieses Beispiel ausprobieren, folgen Sie der Python-Einrichtungsanleitung in der Vision-Kurzanleitung zur Verwendung von Clientbibliotheken. Weitere Informationen finden Sie in der Python-Referenzdokumentation zur Vision API.
Richten Sie zur Authentifizierung bei Vision die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter ADC für eine lokale Entwicklungsumgebung einrichten.
from google.cloud import vision
client_options = {"api_endpoint": "eu-vision.googleapis.com"}
client = vision.ImageAnnotatorClient(client_options=client_options)
Jetzt testen
Probieren Sie die Text- und Dokumenttexterkennung im folgenden Tool aus. Sie können das bereits angegebene Bild (gs://cloud-samples-data/vision/handwriting_image.png
) durch Klicken auf Ausführen verwenden oder stattdessen ein eigenes Bild angeben.
Anfragetext:
{ "requests": [ { "features": [ { "type": "DOCUMENT_TEXT_DETECTION" } ], "image": { "source": { "imageUri": "gs://cloud-samples-data/vision/handwriting_image.png" } } } ] }