Created
July 2, 2019 09:50
-
-
Save tetsunosuke/9939a050d3696a4b838fee422ea6825b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import base64 | |
import json | |
import os | |
GOOGLE_CLOUD_VISION_API_URL = 'https://vision.googleapis.com/v1/images:annotate?key=' | |
API_KEY = 'こちらにAPIキーを' | |
# APIを呼び、認識結果をjson型で返す | |
def request_cloud_vison_api(image_base64): | |
api_url = GOOGLE_CLOUD_VISION_API_URL + API_KEY | |
req_body = json.dumps({ | |
'requests': [{ | |
'image': { | |
'content': image_base64.decode('utf-8') # jsonに変換するためにstring型に変換する | |
}, | |
'features': [{ | |
'type': 'TEXT_DETECTION', # ここを変更することで分析内容を変更できる | |
'maxResults': 10, | |
}] | |
}] | |
}) | |
res = requests.post(api_url, data=req_body) | |
return res.json() | |
# 画像読み込み | |
def img_to_base64(filepath): | |
filepath = 'red.png' | |
with open(filepath, 'rb') as img: | |
img_byte = img.read() | |
return base64.b64encode(img_byte) | |
# 文字認識させたい画像を./img.pngとする | |
filepath = 'img/text-tool03.png' | |
img_base64 = img_to_base64(filepath) | |
result = request_cloud_vison_api(img_base64) | |
#認識した文字の位置など、すべての情報を出力 | |
print("{}".format(json.dumps(result, indent=4))) | |
#認識した文字のみを出力 | |
def get_fullTextAnnotation(json_data): | |
text_dict = json.loads(json_data) | |
try: | |
text_r = text_dict["responses"][0]["fullTextAnnotation"]["text"] | |
return print(text_r) | |
except: | |
print(None) | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment