使用python调用google OCR api
def 参数:(文件目录)
proxies改成自己的,若不需要可删除
难点在于google 不希望你用paikey去验证,文档写的很不详细有没有示例代码。
作者不知道json密钥怎么封装exe,研究了好几天,希望能帮到有需要的人。
# https://cloud.google.com/vision/docs/auth
import json
key = '你的KEY'
def encode_image(path):
import base64
with open(path, 'rb') as img_file:
return base64.b64encode(img_file.read()).decode('utf8')
def googleOCR(path):
import requests
proxies = {
'http': 'http://127.0.0.1:7890',
'https': 'http://127.0.0.1:7890',
}
headers = {'Content-Type': 'application/json'}
data = {
"requests": [
{
"image": {
"content": encode_image(path)
},
"features": [
{
"type": "TEXT_DETECTION"
}
]
}
]
}
url = 'https://vision.googleapis.com/v1/images:annotate?key=' + key
response = requests.post(url, headers=headers ,data=json.dumps(data), proxies=proxies).json()
# print(result.status_code)
texts = response['responses'][0]['textAnnotations'][0]['description']
language = response['responses'][0]['textAnnotations'][0]['locale']
return texts
if __name__ == '__main__':
a = googleOCR('..\ocrtest.png')
print(a)