Path: blob/master/Model-3/cloudvisreq.py
427 views
from __future__ import print_function1from base64 import b64encode2from os import makedirs3from os.path import join, basename4from sys import argv5import json6import requests789ENDPOINT_URL = 'https://vision.googleapis.com/v1/images:annotate'10RESULTS_DIR = 'jsons'1112def make_image_data_list(image_filenames):13"""14image_filenames is a list of filename strings15Returns a list of dicts formatted as the Vision API16needs them to be17"""18img_requests = []19with open(image_filenames, 'rb') as f:20ctxt = b64encode(f.read()).decode()21img_requests.append({22'image': {'content': ctxt},23'features': [{24'type': 'TEXT_DETECTION',25'maxResults': 126}]27})28return img_requests2930def make_image_data(image_filenames):31"""Returns the image data lists as bytes"""32imgdict = make_image_data_list(image_filenames)33return json.dumps({"requests": imgdict }).encode()343536def request_ocr(api_key, image_filenames):37response = requests.post(ENDPOINT_URL, data=make_image_data(image_filenames), params={'key': api_key}, headers={'Content-Type': 'application/json'})38return response394041if __name__ == '__main__':42api_key = "AIzaSyCSMpzBIKlZObk8Uzkx6Iavo967m7vFf0Q"43image_filenames = "test/1.jpg"44if not api_key or not image_filenames:45print("""Please supply an api key, then one or more image filenames $ python cloudvisreq.py image1.jpg image2.png""")46else:47response = request_ocr(api_key, image_filenames)48if response.status_code != 200 or response.json().get('error'):49print(response.text)50else:51for idx, resp in enumerate(response.json()['responses']):52# save to JSON file53imgname = image_filenames[idx]54jpath = join(RESULTS_DIR, basename(imgname) + '.json')55with open(jpath, 'w') as f:56datatxt = json.dumps(resp, indent=2)57print("Wrote", len(datatxt), "bytes to", jpath)58f.write(datatxt)5960# print the plaintext to screen for convenience61print("---------------------------------------------")62t = resp['textAnnotations'][0]63print(" Bounding Polygon:")64print(t['boundingPoly'])65print(" Text:")66print(t['description'])676869