Optische Zeichenerkennung (Optical Character Recognition, OCR)
Mithilfe der Vision API können Sie Text in Bildern erkennen und extrahieren. Es gibt zwei Features für Annotationen, die die optische Zeichenerkennung unterstützen:
TEXT_DETECTION
erkennt und extrahiert Text aus beliebigen Bildern. Nehmen wir als Beispiel ein Foto von einem Straßenschild oder Verkehrszeichen. Die JSON-Datei enthält den gesamten extrahierten String sowie einzelne Wörter und deren Begrenzungsrahmen.DOCUMENT_TEXT_DETECTION
extrahiert zusätzlich Text aus einem Bild, wobei die Antwort für Fließtext und Dokumente optimiert ist. Die JSON-Datei enthält Informationen zu Seite, Block, Absatz, Wort und Worttrennung.Weitere Informationen zur
DOCUMENT_TEXT_DETECTION
erhalten Sie unter Handschrift (OCR) erkennen und Texterkennung in PDF/TIFF-Dokumenten.
Jetzt testen
Wenn Sie mit Google Cloud noch nicht vertraut sind, erstellen Sie einfach ein Konto, um die Leistungsfähigkeit von Cloud Vision in der Praxis sehen und bewerten zu können. Neukunden erhalten außerdem ein Guthaben von 300 $, um Arbeitslasten auszuführen, zu testen und bereitzustellen.
Cloud Vision kostenlos testenTexterkennungsanfragen
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/ocr/sign.jpg
- 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/ocr/sign.jpg
- PROJECT_ID: Projekt-ID in Google Cloud .
Text in einem lokalen Bild erkennen
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.
gcloud
Verwenden Sie für die Texterkennung den Befehl gcloud ml vision detect-text
, wie im folgenden Beispiel gezeigt:
gcloud ml vision detect-text ./path/to/local/file.jpg
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": "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.
Die Antwort für TEXT_DETECTION
enthält die erkannte Wortgruppe, deren Begrenzungsrahmen sowie einzelne Wörter und deren Begrenzungsrahmen.
Antwort
{ "responses": [ { "textAnnotations": [ { "locale": "en", "description": "WAITING?\nPLEASE\nTURN OFF\nYOUR\nENGINE\n", "boundingPoly": { "vertices": [ { "x": 341, "y": 828 }, { "x": 2249, "y": 828 }, { "x": 2249, "y": 1993 }, { "x": 341, "y": 1993 } ] } }, { "description": "WAITING?", "boundingPoly": { "vertices": [ { "x": 352, "y": 828 }, { "x": 2248, "y": 911 }, { "x": 2238, "y": 1148 }, { "x": 342, "y": 1065 } ] } }, { "description": "PLEASE", "boundingPoly": { "vertices": [ { "x": 1210, "y": 1233 }, { "x": 1907, "y": 1263 }, { "x": 1902, "y": 1383 }, { "x": 1205, "y": 1353 } ] } }, { "description": "TURN", "boundingPoly": { "vertices": [ { "x": 1210, "y": 1418 }, { "x": 1730, "y": 1441 }, { "x": 1724, "y": 1564 }, { "x": 1205, "y": 1541 } ] } }, { "description": "OFF", "boundingPoly": { "vertices": [ { "x": 1792, "y": 1443 }, { "x": 2128, "y": 1458 }, { "x": 2122, "y": 1581 }, { "x": 1787, "y": 1566 } ] } }, { "description": "YOUR", "boundingPoly": { "vertices": [ { "x": 1219, "y": 1603 }, { "x": 1746, "y": 1629 }, { "x": 1740, "y": 1759 }, { "x": 1213, "y": 1733 } ] } }, { "description": "ENGINE", "boundingPoly": { "vertices": [ { "x": 1222, "y": 1771 }, { "x": 1944, "y": 1834 }, { "x": 1930, "y": 1992 }, { "x": 1208, "y": 1928 } ] } } ], "fullTextAnnotation": { "pages": [ ... ] }, "paragraphs": [ ... ] }, "words": [ ... }, "symbols": [ ... } ] } ], "blockType": "TEXT" }, ... ] } ], "text": "WAITING?\nPLEASE\nTURN OFF\nYOUR\nENGINE\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.
// detectText gets text from the Vision API for an image at the given file path.
func detectText(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
}
annotations, err := client.DetectTexts(ctx, image, nil, 10)
if err != nil {
return err
}
if len(annotations) == 0 {
fmt.Fprintln(w, "No text found.")
} else {
fmt.Fprintln(w, "Text:")
for _, annotation := range annotations {
fmt.Fprintf(w, "%q\n", annotation.Description)
}
}
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.
import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.EntityAnnotation;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.protobuf.ByteString;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class DetectText {
public static void detectText() throws IOException {
// TODO(developer): Replace these variables before running the sample.
String filePath = "path/to/your/image/file.jpg";
detectText(filePath);
}
// Detects text in the specified image.
public static void detectText(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(Feature.Type.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();
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
for (EntityAnnotation annotation : res.getTextAnnotationsList()) {
System.out.format("Text: %s%n", annotation.getDescription());
System.out.format("Position : %s%n", annotation.getBoundingPoly());
}
}
}
}
}
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.
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';
// Performs text detection on the local file
const [result] = await client.textDetection(fileName);
const detections = result.textAnnotations;
console.log('Text:');
detections.forEach(text => console.log(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_text(path):
"""Detects text in the file."""
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.text_detection(image=image)
texts = response.text_annotations
print("Texts:")
for text in texts:
print(f'\n"{text.description}"')
vertices = [
f"({vertex.x},{vertex.y})" for vertex in text.bounding_poly.vertices
]
print("bounds: {}".format(",".join(vertices)))
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.
Text 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.
gcloud
Verwenden Sie für die Texterkennung den Befehl gcloud ml vision detect-text
, wie im folgenden Beispiel gezeigt:
gcloud ml vision detect-text gs://cloud-samples-data/vision/ocr/sign.jpg
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": "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.
Die Antwort für TEXT_DETECTION
enthält die erkannte Wortgruppe, deren Begrenzungsrahmen sowie einzelne Wörter und deren Begrenzungsrahmen.
Antwort
{ "responses": [ { "textAnnotations": [ { "locale": "en", "description": "WAITING?\nPLEASE\nTURN OFF\nYOUR\nENGINE\n", "boundingPoly": { "vertices": [ { "x": 341, "y": 828 }, { "x": 2249, "y": 828 }, { "x": 2249, "y": 1993 }, { "x": 341, "y": 1993 } ] } }, { "description": "WAITING?", "boundingPoly": { "vertices": [ { "x": 352, "y": 828 }, { "x": 2248, "y": 911 }, { "x": 2238, "y": 1148 }, { "x": 342, "y": 1065 } ] } }, { "description": "PLEASE", "boundingPoly": { "vertices": [ { "x": 1210, "y": 1233 }, { "x": 1907, "y": 1263 }, { "x": 1902, "y": 1383 }, { "x": 1205, "y": 1353 } ] } }, { "description": "TURN", "boundingPoly": { "vertices": [ { "x": 1210, "y": 1418 }, { "x": 1730, "y": 1441 }, { "x": 1724, "y": 1564 }, { "x": 1205, "y": 1541 } ] } }, { "description": "OFF", "boundingPoly": { "vertices": [ { "x": 1792, "y": 1443 }, { "x": 2128, "y": 1458 }, { "x": 2122, "y": 1581 }, { "x": 1787, "y": 1566 } ] } }, { "description": "YOUR", "boundingPoly": { "vertices": [ { "x": 1219, "y": 1603 }, { "x": 1746, "y": 1629 }, { "x": 1740, "y": 1759 }, { "x": 1213, "y": 1733 } ] } }, { "description": "ENGINE", "boundingPoly": { "vertices": [ { "x": 1222, "y": 1771 }, { "x": 1944, "y": 1834 }, { "x": 1930, "y": 1992 }, { "x": 1208, "y": 1928 } ] } } ], "fullTextAnnotation": { "pages": [ ... ] }, "paragraphs": [ ... ] }, "words": [ ... }, "symbols": [ ... } ] } ], "blockType": "TEXT" }, ... ] } ], "text": "WAITING?\nPLEASE\nTURN OFF\nYOUR\nENGINE\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.
// detectText gets text from the Vision API for an image at the given file path.
func detectTextURI(w io.Writer, file string) error {
ctx := context.Background()
client, err := vision.NewImageAnnotatorClient(ctx)
if err != nil {
return err
}
image := vision.NewImageFromURI(file)
annotations, err := client.DetectTexts(ctx, image, nil, 10)
if err != nil {
return err
}
if len(annotations) == 0 {
fmt.Fprintln(w, "No text found.")
} else {
fmt.Fprintln(w, "Text:")
for _, annotation := range annotations {
fmt.Fprintf(w, "%q\n", annotation.Description)
}
}
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.
import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.EntityAnnotation;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class DetectTextGcs {
public static void detectTextGcs() throws IOException {
// TODO(developer): Replace these variables before running the sample.
String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg";
detectTextGcs(filePath);
}
// Detects text in the specified remote image on Google Cloud Storage.
public static void detectTextGcs(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(Feature.Type.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();
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
for (EntityAnnotation annotation : res.getTextAnnotationsList()) {
System.out.format("Text: %s%n", annotation.getDescription());
System.out.format("Position : %s%n", annotation.getBoundingPoly());
}
}
}
}
}
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';
// Performs text detection on the gcs file
const [result] = await client.textDetection(`gs://${bucketName}/${fileName}`);
const detections = result.textAnnotations;
console.log('Text:');
detections.forEach(text => console.log(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_text_uri(uri):
"""Detects text in the file located in Google Cloud Storage or on the Web."""
from google.cloud import vision
client = vision.ImageAnnotatorClient()
image = vision.Image()
image.source.image_uri = uri
response = client.text_detection(image=image)
texts = response.text_annotations
print("Texts:")
for text in texts:
print(f'\n"{text.description}"')
vertices = [
f"({vertex.x},{vertex.y})" for vertex in text.bounding_poly.vertices
]
print("bounds: {}".format(",".join(vertices)))
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.
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": "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.
Die Antwort für TEXT_DETECTION
enthält die erkannte Wortgruppe, deren Begrenzungsrahmen sowie einzelne Wörter und deren Begrenzungsrahmen.
Antwort
{ "responses": [ { "textAnnotations": [ { "locale": "en", "description": "WAITING?\nPLEASE\nTURN OFF\nYOUR\nENGINE\n", "boundingPoly": { "vertices": [ { "x": 341, "y": 828 }, { "x": 2249, "y": 828 }, { "x": 2249, "y": 1993 }, { "x": 341, "y": 1993 } ] } }, { "description": "WAITING?", "boundingPoly": { "vertices": [ { "x": 352, "y": 828 }, { "x": 2248, "y": 911 }, { "x": 2238, "y": 1148 }, { "x": 342, "y": 1065 } ] } }, { "description": "PLEASE", "boundingPoly": { "vertices": [ { "x": 1210, "y": 1233 }, { "x": 1907, "y": 1263 }, { "x": 1902, "y": 1383 }, { "x": 1205, "y": 1353 } ] } }, { "description": "TURN", "boundingPoly": { "vertices": [ { "x": 1210, "y": 1418 }, { "x": 1730, "y": 1441 }, { "x": 1724, "y": 1564 }, { "x": 1205, "y": 1541 } ] } }, { "description": "OFF", "boundingPoly": { "vertices": [ { "x": 1792, "y": 1443 }, { "x": 2128, "y": 1458 }, { "x": 2122, "y": 1581 }, { "x": 1787, "y": 1566 } ] } }, { "description": "YOUR", "boundingPoly": { "vertices": [ { "x": 1219, "y": 1603 }, { "x": 1746, "y": 1629 }, { "x": 1740, "y": 1759 }, { "x": 1213, "y": 1733 } ] } }, { "description": "ENGINE", "boundingPoly": { "vertices": [ { "x": 1222, "y": 1771 }, { "x": 1944, "y": 1834 }, { "x": 1930, "y": 1992 }, { "x": 1208, "y": 1928 } ] } } ], "fullTextAnnotation": { "pages": [ ... ] }, "paragraphs": [ ... ] }, "words": [ ... }, "symbols": [ ... } ] } ], "blockType": "TEXT" }, ... ] } ], "text": "WAITING?\nPLEASE\nTURN OFF\nYOUR\nENGINE\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 unten die Text- und Dokumenttexterkennung aus. Sie können das bereits angegebene Bild (gs://cloud-samples-data/vision/ocr/sign.jpg
) durch Klicken auf Ausführen verwenden oder stattdessen ein eigenes Bild angeben.
Aktualisieren Sie den Wert von type
auf DOCUMENT_TEXT_DETECTION
, um die Erkennung von Dokumenttext auszuprobieren.
Anfragetext:
{ "requests": [ { "features": [ { "type": "TEXT_DETECTION" } ], "image": { "source": { "imageUri": "gs://cloud-samples-data/vision/ocr/sign.jpg" } } } ] }