Skip to content

Instantly share code, notes, and snippets.

@auycro
Created February 4, 2022 03:14
Show Gist options
  • Save auycro/be2a7d0b76f97a19e7711b028782f560 to your computer and use it in GitHub Desktop.
Save auycro/be2a7d0b76f97a19e7711b028782f560 to your computer and use it in GitHub Desktop.
golang google-vision-api detectText
// Sample vision-quickstart uses the Google Cloud Vision API to label an image.
// https://cloud.google.com/vision/docs/ocr
package main
import (
"context"
"fmt"
"log"
"os"
vision "cloud.google.com/go/vision/apiv1"
)
func main() {
path := os.Args[1]
detectText(path)
}
func detectText(filename string) {
ctx := context.Background()
// Creates a client.
client, err := vision.NewImageAnnotatorClient(ctx)
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
defer client.Close()
file, err := os.Open(filename)
if err != nil {
log.Fatalf("Failed to read file: %v", err)
}
defer file.Close()
image, err := vision.NewImageFromReader(file)
if err != nil {
log.Fatalf("Failed to create image: %v", err)
}
annotations, err := client.DetectTexts(ctx, image, nil, 10)
if err != nil {
log.Fatalf("Failed to detect labels: %v", err)
}
fmt.Println("Labels:")
for _, annotation := range annotations {
fmt.Println(annotation.Description)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment