Path: blob/master/Model-5/cloudvisreq.py
427 views
from __future__ import print_function1from base64 import b64encode2from os import makedirs, remove3from os.path import join, basename4from sys import argv5import json6import requests7import glob8910ENDPOINT_URL = 'https://vision.googleapis.com/v1/images:annotate'11RESULTS_DIR = 'jsons'1213def make_image_data_list(image_filenames):14"""15image_filenames is a list of filename strings16Returns a list of dicts formatted as the Vision API17needs them to be18"""19img_requests = []20with open(image_filenames, 'rb') as f:21ctxt = b64encode(f.read()).decode()22img_requests.append({23'image': {'content': ctxt},24'features': [{25'type': 'TEXT_DETECTION',26'maxResults': 127}]28})29return img_requests3031def make_image_data(image_filenames):32"""Returns the image data lists as bytes"""33imgdict = make_image_data_list(image_filenames)34return json.dumps({"requests": imgdict }).encode()353637def request_ocr(api_key, image_filenames):38response = requests.post(ENDPOINT_URL, data=make_image_data(image_filenames), params={'key': api_key}, headers={'Content-Type': 'application/json'})39return response404142if __name__ == '__main__':43api_key = "AIzaSyCSMpzBIKlZObk8Uzkx6Iavo967m7vFf0Q"44for i in range(0,1):45image_filenames = "./4.jpg"46if not api_key or not image_filenames:47print("""Please supply an api key, then one or more image filenames $ python cloudvisreq.py image1.jpg image2.png""")48else:49response = request_ocr(api_key, image_filenames)50if response.status_code != 200 or response.json().get('error'):51print(response.text)52else:53for idx, resp in enumerate(response.json()['responses']):54# save to JSON file55print(response.text)56imgname = image_filenames[idx]57jpath = join(RESULTS_DIR, basename(imgname) + '.json')58with open(jpath, 'w') as f:59datatxt = json.dumps(resp, indent=2)60print("Wrote", len(datatxt), "bytes to", jpath)61f.write(datatxt)6263# print the plaintext to screen for convenience64print("---------------------------------------------")65t = resp['textAnnotations'][0]66print(" Bounding Polygon:")67print(t['boundingPoly'])68print(" Text:")69print(t['description'])707172