Rilevamento della scrittura a mano libera con il riconoscimento ottico dei caratteri (OCR)
L'API Vision può rilevare ed estrarre testo dalle immagini:
DOCUMENT_TEXT_DETECTION
estrae il testo da un'immagine (o da un file); la risposta è ottimizzata per testo e documenti densi. Il JSON include informazioni su pagina, blocco, paragrafo, parola e interruzione.Un utilizzo specifico di DOCUMENT_TEXT_DETECTION è il rilevamento della scrittura a mano in un'immagine.
Provalo
Se non conosci Google Cloud, crea un account per valutare le prestazioni dell'API Cloud Vision in scenari reali. I nuovi clienti ricevono anche 300 $ di crediti per l'esecuzione, il test e il deployment di workload senza costi aggiuntivi.
Prova l'API Cloud Vision gratuitamenteRichieste di rilevamento del testo di documenti
Configura il progetto Google Cloud e l'autenticazione
Se non hai creato un Google Cloud progetto, fallo ora. Espandi questa sezione per le istruzioni.
- 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.
-
Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.
-
Per inizializzare gcloud CLI, esegui questo comando:
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.
-
Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.
-
Per inizializzare gcloud CLI, esegui questo comando:
gcloud init
- BASE64_ENCODED_IMAGE: la rappresentazione
in Base64 (stringa ASCII) dei dati dell'immagine binaria. Questa stringa dovrebbe essere simile alla
seguente:
/9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==
- PROJECT_ID: il tuo ID progetto Google Cloud .
- CLOUD_STORAGE_IMAGE_URI: il percorso di un file immagine valido in un bucket Cloud Storage. Devi disporre almeno dei privilegi di lettura per il file.
Esempio:
gs://cloud-samples-data/vision/handwriting_image.png
- PROJECT_ID: il tuo ID progetto Google Cloud .
us
: solo Stati Unitieu
: L'Unione Europea- 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: uno degli identificatori di località regionali validi:
us
: solo Stati Unitieu
: L'Unione Europea
- CLOUD_STORAGE_IMAGE_URI: il percorso di un file immagine valido in un bucket Cloud Storage. Devi disporre almeno dei privilegi di lettura per il file.
Esempio:
gs://cloud-samples-data/vision/handwriting_image.png
- PROJECT_ID: il tuo ID progetto Google Cloud .
Rilevamento del testo del documento in un'immagine locale
Puoi utilizzare l'API Vision per eseguire il rilevamento delle funzionalità su un file immagine locale.
Per le richieste REST, invia i contenuti del file immagine come stringa codificata in base64 nel corpo della richiesta.
Per le richieste gcloud
e delle librerie client, specifica il percorso di un'immagine locale nella tua richiesta.
REST
Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:
Metodo HTTP e URL:
POST https://vision.googleapis.com/v1/images:annotate
Corpo JSON della richiesta:
{ "requests": [ { "image": { "content": "BASE64_ENCODED_IMAGE" }, "features": [ { "type": "DOCUMENT_TEXT_DETECTION" } ] } ] }
Per inviare la richiesta, scegli una di queste opzioni:
curl
Salva il corpo della richiesta in un file denominato request.json
,
ed esegui questo comando:
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
Salva il corpo della richiesta in un file denominato request.json
,
ed esegui questo comando:
$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
Se la richiesta riesce, il server restituisce un codice di stato HTTP 200 OK
e la risposta in formato JSON.
Risposta
{ "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
Prima di provare questo esempio, segui le istruzioni di configurazione di Go nella guida rapida di Vision per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Vision Go.
Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
// 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
Prima di provare questo esempio, segui le istruzioni di configurazione di Java nella guida rapida dell'API Vision che utilizza le librerie client. Per saperne di più, consulta la documentazione di riferimento di 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
Prima di provare questo esempio, segui le istruzioni di configurazione di Node.js nella guida rapida di Vision per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Vision Node.js.
Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
// 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
Prima di provare questo esempio, segui le istruzioni di configurazione di Python nella guida rapida di Vision per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Vision Python.
Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
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)
)
Linguaggi aggiuntivi
C#: Segui le istruzioni di configurazione di C# nella pagina delle librerie client e poi visita la documentazione di riferimento di Vision per .NET.
PHP: Segui le istruzioni di configurazione di PHP nella pagina delle librerie client e poi consulta la documentazione di riferimento di Vision per PHP.
Ruby: Segui le istruzioni di configurazione di Ruby nella pagina delle librerie client e poi visita la documentazione di riferimento di Vision per Ruby.
Rilevare il testo del documento in un'immagine remota
Puoi utilizzare l'API Vision per eseguire il rilevamento delle funzionalità su un file immagine remoto che si trova in Cloud Storage o sul web. Per inviare una richiesta di file remoto, specifica l'URL web del file o l'URI Cloud Storage nel corpo della richiesta.
REST
Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:
Metodo HTTP e URL:
POST https://vision.googleapis.com/v1/images:annotate
Corpo JSON della richiesta:
{ "requests": [ { "image": { "source": { "imageUri": "CLOUD_STORAGE_IMAGE_URI" } }, "features": [ { "type": "DOCUMENT_TEXT_DETECTION" } ] } ] }
Per inviare la richiesta, scegli una di queste opzioni:
curl
Salva il corpo della richiesta in un file denominato request.json
,
ed esegui questo comando:
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
Salva il corpo della richiesta in un file denominato request.json
,
ed esegui questo comando:
$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
Se la richiesta riesce, il server restituisce un codice di stato HTTP 200 OK
e la risposta in formato JSON.
Risposta
{ "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
Prima di provare questo esempio, segui le istruzioni di configurazione di Go nella guida rapida di Vision per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Vision Go.
Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
// 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
Prima di provare questo esempio, segui le istruzioni di configurazione di Java nella guida rapida dell'API Vision che utilizza le librerie client. Per saperne di più, consulta la documentazione di riferimento di 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
Prima di provare questo esempio, segui le istruzioni di configurazione di Node.js nella guida rapida di Vision per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Vision Node.js.
Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
// 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
Prima di provare questo esempio, segui le istruzioni di configurazione di Python nella guida rapida di Vision per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Vision Python.
Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
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
Per eseguire il riconoscimento della scrittura a mano, utilizza il comando
gcloud ml vision detect-document
come mostrato nell'esempio seguente:
gcloud ml vision detect-document gs://cloud-samples-data/vision/handwriting_image.png
Linguaggi aggiuntivi
C#: Segui le istruzioni di configurazione di C# nella pagina delle librerie client e poi visita la documentazione di riferimento di Vision per .NET.
PHP: Segui le istruzioni di configurazione di PHP nella pagina delle librerie client e poi consulta la documentazione di riferimento di Vision per PHP.
Ruby: Segui le istruzioni di configurazione di Ruby nella pagina delle librerie client e poi visita la documentazione di riferimento di Vision per Ruby.
(Facoltativo) Specifica la lingua
Entrambi i tipi di richieste OCR supportano uno o più languageHints
che specificano la
lingua di qualsiasi testo nell'immagine. Tuttavia, un valore vuoto in genere produce i risultati migliori,
perché l'omissione di un valore consente il rilevamento automatico della lingua. Per le lingue basate sull'alfabeto latino, non è necessario impostare languageHints
. In rari casi, quando la lingua del testo nell'immagine è nota, l'impostazione di un suggerimento aiuta a ottenere risultati migliori (anche se può essere un ostacolo significativo se il suggerimento è errato). Il rilevamento del testo restituisce un errore se una o più delle lingue specificate non sono tra le lingue supportate.
Se scegli di fornire un suggerimento sulla lingua, modifica il corpo della richiesta
(file request.json
) per fornire la stringa di una delle lingue supportate
nel campo imageContext.languageHints
, come mostrato nel seguente esempio:
{ "requests": [ { "image": { "source": { "imageUri": "IMAGE_URL" } }, "features": [ { "type": "DOCUMENT_TEXT_DETECTION" } ], "imageContext": { "languageHints": ["en-t-i0-handwrit"] } } ] }
Supporto di più aree geografiche
Ora puoi specificare l'archiviazione dei dati a livello di continente e l'elaborazione OCR. Al momento sono supportate le seguenti regioni:
Località
Cloud Vision ti offre un certo controllo su dove vengono archiviate ed elaborate le risorse del tuo progetto. In particolare, puoi configurare Cloud Vision per archiviare ed elaborare i tuoi dati solo nell'Unione Europea.
Per impostazione predefinita, Cloud Vision archivia ed elabora le risorse in una località globale, il che significa che Cloud Vision non garantisce che le risorse rimarranno all'interno di una determinata località o regione. Se scegli la località Unione Europea, Google archivierà i tuoi dati e li elaborerà solo nell'Unione Europea. Tu e i tuoi utenti potete accedere ai dati da qualsiasi posizione.
Impostazione della posizione utilizzando l'API
L'API Vision supporta un endpoint API globale (vision.googleapis.com
) e anche
due endpoint basati sulla regione: un endpoint dell'Unione Europea
(eu-vision.googleapis.com
) e un endpoint degli Stati Uniti (us-vision.googleapis.com
). Utilizza questi endpoint per l'elaborazione specifica per regione. Ad esempio, per archiviare ed elaborare i tuoi dati solo nell'Unione Europea, utilizza l'URI eu-vision.googleapis.com
al posto di vision.googleapis.com
per le chiamate API REST:
Per archiviare ed elaborare i dati solo negli Stati Uniti, utilizza l'endpoint statunitense
(us-vision.googleapis.com
) con i metodi precedenti.
Impostare la posizione utilizzando le librerie client
Per impostazione predefinita, le librerie client dell'API Vision accedono all'endpoint API globale
(vision.googleapis.com
). Per archiviare ed elaborare i dati solo nell'Unione Europea, devi impostare esplicitamente l'endpoint (eu-vision.googleapis.com
). I seguenti esempi di codice mostrano come configurare questa impostazione.
REST
Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:
Metodo HTTP e URL:
POST https://REGION_ID-vision.googleapis.com/v1/projects/PROJECT_ID/locations/REGION_ID/images:annotate
Corpo JSON della richiesta:
{ "requests": [ { "image": { "source": { "imageUri": "CLOUD_STORAGE_IMAGE_URI" } }, "features": [ { "type": "DOCUMENT_TEXT_DETECTION" } ] } ] }
Per inviare la richiesta, scegli una di queste opzioni:
curl
Salva il corpo della richiesta in un file denominato request.json
,
ed esegui questo comando:
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
Salva il corpo della richiesta in un file denominato request.json
,
ed esegui questo comando:
$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
Se la richiesta riesce, il server restituisce un codice di stato HTTP 200 OK
e la risposta in formato JSON.
Risposta
{ "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
Prima di provare questo esempio, segui le istruzioni di configurazione di Go nella guida rapida di Vision per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Vision Go.
Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
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
Prima di provare questo esempio, segui le istruzioni di configurazione di Java nella guida rapida dell'API Vision che utilizza le librerie client. Per saperne di più, consulta la documentazione di riferimento di 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
Prima di provare questo esempio, segui le istruzioni di configurazione di Node.js nella guida rapida di Vision per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Vision Node.js.
Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
// 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
Prima di provare questo esempio, segui le istruzioni di configurazione di Python nella guida rapida di Vision per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Vision Python.
Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
from google.cloud import vision
client_options = {"api_endpoint": "eu-vision.googleapis.com"}
client = vision.ImageAnnotatorClient(client_options=client_options)
Prova
Prova il rilevamento del testo e il rilevamento del testo nei documenti nel seguente strumento. Puoi
utilizzare l'immagine già specificata
(gs://cloud-samples-data/vision/handwriting_image.png
) facendo clic su
Esegui oppure puoi specificare un'immagine personalizzata al suo posto.
Corpo della richiesta:
{ "requests": [ { "features": [ { "type": "DOCUMENT_TEXT_DETECTION" } ], "image": { "source": { "imageUri": "gs://cloud-samples-data/vision/handwriting_image.png" } } } ] }