teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

2

ソースコードの貼りかえ

2019/07/02 14:22

投稿

0zer0
0zer0

スコア11

title CHANGED
File without changes
body CHANGED
@@ -11,23 +11,48 @@
11
11
  ### 該当のソースコード
12
12
 
13
13
  ```Python3
14
- ---------------------------------------------------------------------------
15
- UnboundLocalError Traceback (most recent call last)
16
- <ipython-input-48-979a5a6d593d> in <module>()
17
- 38 img = "/content/testtest2.jpg"
18
- 39 key = "AIzaSyB1pHeQQwxjs8AE7T615wcvpRJbzmg0np4"
19
- ---> 40 data = ocr(img, key)
20
- 41 print(data)
14
+ import base64
15
+ import requests
21
- 42
16
+ import json
22
17
 
23
- <ipython-input-48-979a5a6d593d> in ocr(image_file, access_token)
18
+ def ocr(image_file, access_token=None):
19
+ with open(image_file, 'rb') as image:
20
+ base64_image = base64.b64encode(image.read()).decode()
21
+ # base64_image = image.read()
22
+
23
+ url = 'https://vision.googleapis.com/v1/images:annotate?key={}'.format(access_token)
24
+ header = {'Content-Type': 'application/json'}
25
+ body = {
26
+ 'requests': [{
27
+ 'image': {
28
+ 'content': base64_image,
29
+ },
30
+ 'features': [{
31
+ 'type': 'TEXT_DETECION',
32
+ 'maxResults': 1,
33
+ }]
34
+
35
+ }]
36
+ }
37
+ response = requests.post(url, headers=header, json=body).json()
38
+ # jsonで吐き出し response
39
+ # fw = open('vision_response.json','w')
40
+ # json.dump(response.fw.indent=4)
41
+
42
+ # print("responseの値は?" + str(response))
43
+ try:
44
+ text = response['responses'][0]['textAnnotations'][0]['description'] if len(response['responses'][0]) > 0 else ''
24
- 32 except KeyError:
45
+ except KeyError:
25
- 33 pass
46
+ pass
26
- ---> 34 print("textの値は?" + str(text))
47
+ print("textの値は?" + str(text))
27
- 35 return text
48
+ return text
49
+
28
- 36
50
+ # imgの画像ファイルのあるPATHは環境に合わせて変更する
29
-
30
- UnboundLocalError: local variable 'text' referenced before assignment
51
+ img = "/content/testtest2.jpg"
52
+ key = "AIzaSyB1pHeQQwxjs8AE7T615wcvpRJbzmg0np4"
53
+ data = ocr(img, key)
54
+ print(data)
55
+
31
56
  ```
32
57
 
33
58
  ### 試したこと

1

本文訂正

2019/07/02 14:22

投稿

0zer0
0zer0

スコア11

title CHANGED
File without changes
body CHANGED
@@ -1,8 +1,6 @@
1
1
  ### 前提・実現したいこと
2
2
 
3
- ここに質問の内容を詳しく書いてください。
4
- (例)PHP(CakePHP)で●●なシステムを作っています。
5
- ■■な機能実装中に以下のエラーメッセージが発生しました。
3
+ 名刺からテキスト抽出するプログラムを作成中に以下のエラーメッセージが発生
6
4
 
7
5
  ### 発生している問題・エラーメッセージ
8
6
 
@@ -36,6 +34,4 @@
36
34
 
37
35
  indentの調整
38
36
 
39
- ### 補足情報(FW/ツールのバージョンなど)
37
+ ### 補足情報(FW/ツールのバージョンなど)
40
-
41
- 名刺からテキストを抽出するプログラム