at kaneshin
Home Talks Posts Links

21 Feb 2016
Google Cloud Vision API on Golang

go CloudVisionApi GoogleCloudPlatform

Cloud Vision API

Google announced on 2/18 the beta release of Google Cloud Vision API. Now we can submit our images to the service to understand the content of those images by encapsulating powerful machine learning models.

It quickly classifies images into thousands of categories, detects individual objects and faces within images, and finds and reads printed words contained within images.

Cloud Vision API

Getting Started with Golang

See official documentation if you’d like to read more details.

1. Enabling the Cloud Vision API

Actually, the Google Cloud Vision API is still beta release. You need to turn it on manually to be available. Let’s see and enable on your developer console.

2. Setting Up a Service Account

Set up a service account on credentials page and get a service account credentials json file.

$ export GOOGLE_APPLICATION_CREDENTIALS=~/.credentials/service_account.json

3. Get App and Submit Your Image.

I implemented an app, which is available the Google Cloud Vision API via Golang.

$ go get github.com/kaneshin/pigeon/cmd/pigeon
$ pigeon sample.png > result.json
$ pigeon gs://bucket_name/sample.png > result.json

or

$ go get github.com/kaneshin/go-cloud-vision-api
$ go-cloud-vision-api sample.png > result.json

Implementation

Getting a Vision Service by Authorized HTTP Client.

config, err := google.JWTConfigFromJSON(jsonData, vision.CloudPlatformScope)
if err != nil {
	panic(err)
}
client := config.Client(ctx)

srv, err := vision.New(client)
if err != nil {
	panic(err)
}

Creates an Annotate Image Request.

req := &vision.AnnotateImageRequest{
	// Apply image which is encoded by base64.
	Image: &vision.Image{
		Content: base64.StdEncoding.EncodeToString(imageData),
	},
	// Apply features to indicate what type of image detection.
	Features: []*vision.Feature{
		{
			MaxResults: 10,
			Type:       "FACE_DETECTION",
		},
	},
}

vision.Image can apply base64 encoded image and Google Cloud Storage URIs of the form gs://bucketname/path/to/image_filename. And vision.Feature indicates what are using detections.

Submit the Requests on Batched

// To call multiple image annotation requests.
batch := &vision.BatchAnnotateImagesRequest{
	Requests: []*vision.AnnotateImageRequest{req},
}

// Execute the "vision.images.annotate".
res, err := srv.Images.Annotate(batch).Do()
if err != nil {
	panic(err)
}

// Marshal annotations from responses
body, err := json.MarshalIndent(res.Responses, "", "  ")
if err != nil {
	panic(err)
}
fmt.Println(string(body))

Resources


Til next time,
kaneshin at 08:30