Skip to content

Instantly share code, notes, and snippets.

@jrjames83
Created May 6, 2016 00:41
Show Gist options
  • Save jrjames83/f6f234296c3acdacc19056ce248585a3 to your computer and use it in GitHub Desktop.
Save jrjames83/f6f234296c3acdacc19056ce248585a3 to your computer and use it in GitHub Desktop.
example of google vision api for label detection
import argparse
import base64
import httplib2
import os
from apiclient.discovery import build
from oauth2client.client import GoogleCredentials
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = 'secret.json'
def main(photo_file):
'''Run a label request on a single image'''
#returns a label of what the image is
API_DISCOVERY_FILE = 'https://vision.googleapis.com/$discovery/rest?version=v1'
http = httplib2.Http()
credentials = GoogleCredentials.get_application_default().create_scoped(
['https://www.googleapis.com/auth/cloud-platform'])
credentials.authorize(http)
service = build('vision', 'v1', http, discoveryServiceUrl=API_DISCOVERY_FILE)
with open(photo_file, 'rb') as image:
image_content = base64.b64encode(image.read())
service_request = service.images().annotate(
body={
'requests': [{
'image': {
'content': image_content
},
'features': [{
'type': 'TEXT_DETECTION',
'maxResults': 1,
}]
}]
})
response = service_request.execute()
print response
#https://cloud.google.com/vision/reference/rest/v1/images/annotate
#label = response['responses'][0]['labelAnnotations'][0]['description']
#print('Found label: %s for %s' % (label, photo_file))
return 0
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'image_file', help='The image you\'d like to label.')
args = parser.parse_args()
main(args.image_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment