Google Cloud Vision APIで光学式文字認識をpythonで実装しようとしているのですが、うまくテキストが表示されません。
実行の参考サイトは以下二つです。
https://qiita.com/AltGuNi/items/6f22f1441733da08fdc1
https://www.g104robo.com/entry/google-cloud-vision-api
実装したコードは以下になります。
APIキーは抜いています。
# -*- coding: utf-8 -*- 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 = 'img/text-tool03.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
出力結果は特にエラーがなく何も表示されません。
写真はimgフォルダに一枚入っています。
写真は「あいうえお」とシンプルに書いてあるものです。
ご教示いただけましたら幸いです。
宜しくお願い致します。
追記
# 文字認識させたい画像を./img.pngとする filepath = 'img' path = os.listdir(filepath) new_path = ','.join(path).replace(".DS_Store,","") new_dir_path = 'img/' + new_path img_base64 = img_to_base64(new_dir_path) 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
途中、print("{}".format(json.dumps(result, indent=4)))で出力した結果、以下が出ました。
{ "responses": [ {} ] }
これは、そもそも画像が読み込まれていないのでしょうか。
すいません、pathを違うもので書いてました。
def img_to_base64(filepath): filepath = 'img/text-tool03.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
上記でも出力が同じでした。
ひらがなは読めないんでしょうか。
あなたの回答
tips
プレビュー