Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Cette page explique comment détecter le texte d'une image à l'aide de l'API de reconnaissance optique de caractères (OCR) sur l'appliance Google Distributed Cloud (GDC) isolée du réseau.
Le service OCR de Vertex AI sur l'appliance GDC air-gapped détecte le texte dans les images à l'aide de la méthode d'API BatchAnnotateImages. Le service accepte les fichiers JPEG et PNG pour les images.
Avant de commencer
Pour pouvoir utiliser l'API OCR, vous devez disposer d'un projet pour lequel cette API est activée, ainsi que des identifiants appropriés.
Vous pouvez également installer des bibliothèques clientes pour faciliter les appels à l'API. Pour en savoir plus, consultez Configurer un projet de reconnaissance de caractères.
Détecter le texte des fichiers JPEG et PNG
La méthode BatchAnnotateImages détecte le texte d'un lot de fichiers JPEG ou PNG.
Vous envoyez directement le fichier à partir duquel vous souhaitez détecter du texte en tant que contenu dans la requête API. Le système renvoie le texte détecté au format JSON dans la réponse de l'API.
Vous devez spécifier des valeurs pour les champs du corps JSON de votre requête API. Le tableau suivant décrit les champs du corps de la requête que vous devez fournir lorsque vous utilisez la méthode d'API BatchAnnotateImages pour vos requêtes de détection de texte :
Champs du corps de la requête
Description du champ
content
Images contenant du texte à détecter. Vous fournissez la représentation en base64 (chaîne ASCII) de vos données d'image binaires.
type
Le type de détection de texte dont vous avez besoin à partir de l'image.
Spécifiez l'une des deux fonctionnalités d'annotation :
TEXT_DETECTION détecte et extrait le texte de toute image. La réponse JSON inclut la chaîne extraite, les mots individuels et leurs cadres de délimitation.
DOCUMENT_TEXT_DETECTION extrait également le texte d'une image, mais le service optimise la réponse pour les textes et les documents denses. Le fichier JSON comprend des informations sur les pages, les blocs, les paragraphes, les mots et les blancs.
Facultatif. Liste des langues à utiliser pour la détection de texte.
Le système interprète une valeur vide pour ce champ comme une détection automatique de la langue.
Vous n'avez pas besoin de définir le champ language_hints pour les langues basées sur l'alphabet latin.
Si vous connaissez la langue du texte de l'image, le réglage de ce paramètre améliore les résultats.
Envoyer une requête d'API
Envoyez une requête à l'API pré-entraînée OCR à l'aide de la méthode de l'API REST. Sinon, interagissez avec l'API pré-entraînée de reconnaissance optique des caractères à partir d'un script Python pour détecter le texte des fichiers JPEG ou PNG.
Les exemples suivants montrent comment détecter du texte dans une image à l'aide de l'OCR :
REST
Pour détecter du texte dans des images à l'aide de la méthode de l'API REST, procédez comme suit :
Enregistrez le fichier request.json suivant pour le corps de votre requête :
BASE64_ENCODED_IMAGE : représentation en base64 (chaîne ASCII) de vos données d'image binaires. Cette chaîne commence par des caractères qui ressemblent à /9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==.
FEATURE_TYPE : type de détection de texte dont vous avez besoin à partir de l'image. Les valeurs autorisées sont TEXT_DETECTION ou DOCUMENT_TEXT_DETECTION.
LANGUAGE_HINT : balises de langue BCP-47 à utiliser comme indices de langue pour la détection de texte, par exemple en-t-i0-handwrit. Ce champ est facultatif. Si vous ne saisissez aucune valeur, le système interprète cela comme une détection automatique de la langue.
Ajoutez le code suivant au script Python que vous avez créé :
fromgoogle.cloudimportvisionimportgoogle.authfromgoogle.auth.transportimportrequestsfromgoogle.api_core.client_optionsimportClientOptionsaudience="https://ENDPOINT:443"api_endpoint="ENDPOINT:443"defvision_client(creds):opts=ClientOptions(api_endpoint=api_endpoint)returnvision.ImageAnnotatorClient(credentials=creds,client_options=opts)defmain():creds=Nonetry:creds,project_id=google.auth.default()creds=creds.with_gdch_audience(audience)req=requests.Request()creds.refresh(req)print("Got token: ")print(creds.token)exceptExceptionase:print("Caught exception"+str(e))raiseereturncredsdefvision_func(creds):vc=vision_client(creds)image={"content":"BASE64_ENCODED_IMAGE"}features=[{"type_":vision.Feature.Type.FEATURE_TYPE}]# Each requests element corresponds to a single image. To annotate more# images, create a request element for each image and add it to# the array of requestsreq={"image":image,"features":features}metadata=[("x-goog-user-project","projects/PROJECT_ID")]resp=vc.annotate_image(req,metadata=metadata)print(resp)if__name__=="__main__":creds=main()vision_func(creds)
BASE64_ENCODED_IMAGE : représentation en base64 (chaîne ASCII) de vos données d'image binaires. Cette chaîne commence par des caractères qui ressemblent à /9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==.
FEATURE_TYPE : type de détection de texte dont vous avez besoin à partir de l'image. Les valeurs autorisées sont TEXT_DETECTION ou DOCUMENT_TEXT_DETECTION.
PROJECT_ID : ID de votre projet.
Enregistrez le script Python.
Exécutez le script Python pour détecter le texte dans l'image :
pythonSCRIPT_NAME
Remplacez SCRIPT_NAME par le nom que vous avez donné à votre script Python, par exemple vision.py.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/04 (UTC)."],[],[],null,["# Detect text in images\n\nThis page shows you how to detect image text using the\nOptical Character Recognition (OCR) API on Google Distributed Cloud (GDC) air-gapped appliance.\n\nThe OCR service of Vertex AI on\nGDC air-gapped appliance detects text in images using the\n`BatchAnnotateImages` API method. The service supports JPEG and PNG files for\nimages.\n\nBefore you begin\n----------------\n\nBefore you can start using the OCR API, you must have a project\nwith the OCR API enabled and have the appropriate credentials.\nYou can also install client libraries to help you make calls to the API. For\nmore information, see [Set up a character recognition project](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vai-set-up-ocr).\n\nDetect text from JPEG and PNG files\n-----------------------------------\n\nThe `BatchAnnotateImages` method detects text from a batch of JPEG or PNG files.\nYou send the file from which you want to detect text directly as content in the\nAPI request. The system returns the resulting detected text in JSON format in\nthe API response.\n\nYou must specify values for the fields in the JSON body of your API request. The\nfollowing table contains a description of the request body fields you must\nprovide when you use the `BatchAnnotateImages` API method for your text\ndetection requests:\n\n### Make an API request\n\nMake a request to the OCR pre-trained API using the REST API\nmethod. Otherwise, interact with the OCR pre-trained API from a\nPython script to detect text from JPEG or PNG files.\n| **Note:** The `BatchAnnotateImages` API method only supports a single request per batch call.\n\nThe following examples show how to detect text in an image using\nOCR: \n\n### REST\n\nFollow these steps to detect text in images using the REST API method:\n\n1. Save the following `request.json` file for your request body:\n\n cat \u003c\u003c- EOF \u003e request.json\n {\n \"requests\": [\n {\n \"image\": {\n \"content\": \u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-err\"\u003eBASE\u003c/span\u003e\u003cspan class=\"devsite-syntax-mi\"\u003e64\u003c/span\u003e\u003cspan class=\"devsite-syntax-err\"\u003e_ENCODED_IMAGE\u003c/span\u003e\u003c/var\u003e\n },\n \"features\": [\n {\n \"type\": \"\u003cvar translate=\"no\"\u003eFEATURE_TYPE\u003c/var\u003e\"\n }\n ],\n \"image_context\": {\n \"language_hints\": [\n \"\u003cvar translate=\"no\"\u003eLANGUAGE_HINT_1\u003c/var\u003e\",\n \"\u003cvar translate=\"no\"\u003eLANGUAGE_HINT_2\u003c/var\u003e\",\n ...\n ]\n }\n }\n ]\n }\n EOF\n\n Replace the following:\n - \u003cvar translate=\"no\"\u003eBASE64_ENCODED_IMAGE\u003c/var\u003e: the Base64 representation (ASCII string) of your binary image data. This string begins with characters that look similar to `/9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==`.\n - \u003cvar translate=\"no\"\u003eFEATURE_TYPE\u003c/var\u003e: the type of text detection you need from the image. Allowed values are `TEXT_DETECTION` or `DOCUMENT_TEXT_DETECTION`.\n - \u003cvar translate=\"no\"\u003eLANGUAGE_HINT\u003c/var\u003e: the BCP 47 language tags to use as language hints for text detection, such as `en-t-i0-handwrit`. This field is optional and the system interprets an empty value as automatic language detection.\n2. [Get an authentication token](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-api-auth).\n\n3. Make the request:\n\n ### curl\n\n curl -X POST \\\n -H \"Authorization: Bearer \u003cvar translate=\"no\"\u003eTOKEN\u003c/var\u003e\" \\\n -H \"x-goog-user-project: projects/\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e\" \\\n -H \"Content-Type: application/json; charset=utf-8\" \\\n -d @request.json \\\n https://\u003cvar translate=\"no\"\u003eENDPOINT\u003c/var\u003e/v1/images:annotate\n\n Replace the following:\n - \u003cvar translate=\"no\"\u003eTOKEN\u003c/var\u003e: [the authentication token](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-api-auth) you obtained.\n - \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e: your project ID.\n - \u003cvar translate=\"no\"\u003eENDPOINT\u003c/var\u003e: the OCR endpoint that you use for your organization. For more information, [view service status and endpoints](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-api-status).\n\n ### PowerShell\n\n $headers = @{\n \"Authorization\" = \"Bearer \u003cvar translate=\"no\"\u003eTOKEN\u003c/var\u003e\"\n \"x-goog-user-project\" = \"projects/\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e\"\n }\n\n Invoke-WebRequest\n -Method POST\n -Headers $headers\n -ContentType: \"application/json; charset=utf-8\"\n -InFile request.json\n -Uri \"\u003cvar translate=\"no\"\u003eENDPOINT\u003c/var\u003e/v1/images:annotate\" | Select-Object -Expand Content\n\n Replace the following:\n - \u003cvar translate=\"no\"\u003eTOKEN\u003c/var\u003e: [the authentication token](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-api-auth) you obtained.\n - \u003cvar translate=\"no\"\u003eENDPOINT\u003c/var\u003e: the OCR endpoint that you use for your organization. For more information, [view service status and endpoints](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-api-status).\n\n### Python\n\nFollow these steps to use the OCR service from a Python\nscript to detect text in an image:\n\n1. [Install the latest version of the OCR client library](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-install-libraries).\n\n2. [Set the required environment variables on a Python script](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vai-set-up-ocr#set-env-var).\n\n3. [Authenticate your API request](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-api-auth).\n\n4. Add the following code to the Python script you created:\n\n from google.cloud import vision\n import google.auth\n from google.auth.transport import requests\n from google.api_core.client_options import ClientOptions\n\n audience = \"https://\u003cvar translate=\"no\"\u003eENDPOINT\u003c/var\u003e:443\"\n api_endpoint=\"\u003cvar translate=\"no\"\u003eENDPOINT\u003c/var\u003e:443\"\n\n def vision_client(creds):\n opts = ClientOptions(api_endpoint=api_endpoint)\n return vision.https://cloud.google.com/python/docs/reference/vision/latest/google.cloud.vision_v1.services.image_annotator.ImageAnnotatorClient.html(credentials=creds, client_options=opts)\n\n def main():\n creds = None\n try:\n creds, project_id = google.auth.default()\n creds = creds.with_gdch_audience(audience)\n req = requests.Request()\n creds.refresh(req)\n print(\"Got token: \")\n print(creds.token)\n except Exception as e:\n print(\"Caught exception\" + str(e))\n raise e\n return creds\n\n def vision_func(creds):\n vc = vision_client(creds)\n image = {\"content\": \"\u003cvar translate=\"no\"\u003eBASE64_ENCODED_IMAGE\u003c/var\u003e\"}\n features = [{\"type_\": vision.https://cloud.google.com/python/docs/reference/vision/latest/google.cloud.vision_v1.types.Feature.html.Type.\u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-n\"\u003eFEATURE_TYPE\u003c/span\u003e\u003c/var\u003e}]\n # Each requests element corresponds to a single image. To annotate more\n # images, create a request element for each image and add it to\n # the array of requests\n req = {\"image\": image, \"features\": features}\n\n metadata = [(\"x-goog-user-project\", \"projects/\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e\")]\n\n resp = vc.annotate_image(req,metadata=metadata)\n\n print(resp)\n\n if __name__==\"__main__\":\n creds = main()\n vision_func(creds)\n\n Replace the following:\n - \u003cvar translate=\"no\"\u003eENDPOINT\u003c/var\u003e: the OCR endpoint that you use for your organization. For more information, [view service status and endpoints](/distributed-cloud/hosted/docs/latest/appliance/application/ao-user/vertex-ai-api-status).\n - \u003cvar translate=\"no\"\u003eBASE64_ENCODED_IMAGE\u003c/var\u003e: the Base64 representation (ASCII string) of your binary image data. This string begins with characters that look similar to `/9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==`.\n - \u003cvar translate=\"no\"\u003eFEATURE_TYPE\u003c/var\u003e: the type of text detection you need from the image. Allowed values are `TEXT_DETECTION` or `DOCUMENT_TEXT_DETECTION`.\n - \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e: your project ID.\n5. Save the Python script.\n\n6. Run the Python script to detect text in the image:\n\n python \u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-n\"\u003eSCRIPT_NAME\u003c/span\u003e\u003c/var\u003e\n\n Replace \u003cvar translate=\"no\"\u003eSCRIPT_NAME\u003c/var\u003e with the name you gave to your\n Python script, such as `vision.py`."]]