前提・実現したいこと
名刺からテキストを抽出するプログラムを作成中に以下のエラーメッセージが発生
発生している問題・エラーメッセージ
UnboundLocalError: local variable 'text' referenced before assignment
該当のソースコード
Python3
1import base64 2import requests 3import json 4 5def ocr(image_file, access_token=None): 6 with open(image_file, 'rb') as image: 7 base64_image = base64.b64encode(image.read()).decode() 8 # base64_image = image.read() 9 10 url = 'https://vision.googleapis.com/v1/images:annotate?key={}'.format(access_token) 11 header = {'Content-Type': 'application/json'} 12 body = { 13 'requests': [{ 14 'image': { 15 'content': base64_image, 16 }, 17 'features': [{ 18 'type': 'TEXT_DETECION', 19 'maxResults': 1, 20 }] 21 22 }] 23 } 24 response = requests.post(url, headers=header, json=body).json() 25 # jsonで吐き出し response 26 # fw = open('vision_response.json','w') 27 # json.dump(response.fw.indent=4) 28 29 # print("responseの値は?" + str(response)) 30 try: 31 text = response['responses'][0]['textAnnotations'][0]['description'] if len(response['responses'][0]) > 0 else '' 32 except KeyError: 33 pass 34 print("textの値は?" + str(text)) 35 return text 36 37# imgの画像ファイルのあるPATHは環境に合わせて変更する 38img = "/content/testtest2.jpg" 39key = "AIzaSyB1pHeQQwxjs8AE7T615wcvpRJbzmg0np4" 40data = ocr(img, key) 41print(data) 42
試したこと
indentの調整
補足情報(FW/ツールのバージョンなど)
回答3件
あなたの回答
tips
プレビュー