简体   繁体   中英

Where does API key go in Google Cloud Vision API?

Want to use Google's Cloud Vision API for OCR. Using the python sample code here we have:

def detect_text(path):
"""Detects text in the file."""
client = vision.ImageAnnotatorClient()

with io.open(path, 'rb') as image_file:
    content = image_file.read()

image = types.Image(content=content)

response = client.text_detection(image=image)
texts = response.text_annotations
print('Texts:')

for text in texts:
    print('\n"{}"'.format(text.description))

    vertices = (['({},{})'.format(vertex.x, vertex.y)
                for vertex in text.bounding_poly.vertices])

    print('bounds: {}'.format(','.join(vertices)))

Where do I put my API key? I (obviously) can't authenticate without it.

From the docs ,

If you plan to use a service account with client library code, you need to set an environment variable.

Provide the credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. Replace [PATH] with the location of the JSON file you downloaded in the previous step.

For example:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

So it looks like you should create a service account, download a credentials file, and set up an environmental variable to point to it.

There are two ways through which you can authenticate

  1. Exporting the credential file as an environment variable. Here is a sample code:
from google.cloud import vision

def get_text_from_image(image_file):
        os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = "./creds/xxxx-xxxxx.json"
        try:
            # process_image is a method to convert numpy array to bytestream
            # (not of interest in this context hence not including it here)
            byte_img = process_image_to_bytes(image_file)
            client = vision.ImageAnnotatorClient()
            image = vision.Image(content=byte_img)
            response = client.text_detection(image=image)
            texts = response.text_annotations
            return texts
        except BaseException as e:
            print(str(e))

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] is doing the work here

  1. Using oauth2
from google.cloud import vision
from google.oauth2 import service_account

def get_text_from_image(image_file):
        creds = service_account.Credentials.from_service_account_file("./creds/xxx-xxxxx.json")
        try:
            # process_image is a method to convert numpy array to bytestream
            # (not of interest in this context hence not including it here)
            byte_img = process_image_to_bytes(image_file)
            client = vision.ImageAnnotatorClient(credentials=creds)
            image = vision.Image(content=byte_img)
            response = client.text_detection(image=image)
            texts = response.text_annotations
            return texts
        except BaseException as e:
            print(str(e))

Here we are using the google-auth library to create a credential file from the JSON credential file and passing that object to ImageAnnotatorClient for authentication.

Hope these sample snippets helped you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM