Skip to content

Instantly share code, notes, and snippets.



Created Mar 15, 2017
What would you like to do?
Modified Python Script for MS Computer Vision API (OCR)
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import http.client, urllib.request, urllib.parse, urllib.error, base64
import http.client, urllib.request, urllib.parse, urllib.error, base64
import os, json, argparse
api_key = os.environ['MSCV_API_KEY']
# print(api_key)
parser = argparse.ArgumentParser()
parser.add_argument("imagefile", help = "image file for ocr(png, jpg)")
args = parser.parse_args()
filename = args.imagefile
# print(filename)
headers = {
# Request headers
#'Content-Type': 'application/json',
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key': api_key,
params = urllib.parse.urlencode({
# Request parameters
'language': 'unk',
'detectOrientation ': 'true',
conn = http.client.HTTPSConnection('')
img = open(filename, 'rb').read()
conn.request("POST", "/vision/v1.0/ocr?%s" % params, img, headers)
response = conn.getresponse()
data = "utf-8")
json_dict = json.loads(data)
# print(json_dict['regions'])
for region in json_dict['regions'] :
print("region: {}".format(region['boundingBox']))
for line in region['lines'] :
print("line: {}".format(line['boundingBox']))
for word in line['words'] :
print(word['text'], end="")
# print("\n")
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment