質問編集履歴

2

ソースコードの貼りかえ

2019/07/02 14:22

投稿

0zer0
0zer0

スコア11

test CHANGED
File without changes
test CHANGED
@@ -24,39 +24,89 @@
24
24
 
25
25
  ```Python3
26
26
 
27
- ---------------------------------------------------------------------------
27
+ import base64
28
28
 
29
- UnboundLocalError Traceback (most recent call last)
29
+ import requests
30
30
 
31
- <ipython-input-48-979a5a6d593d> in <module>()
32
-
33
- 38 img = "/content/testtest2.jpg"
34
-
35
- 39 key = "AIzaSyB1pHeQQwxjs8AE7T615wcvpRJbzmg0np4"
36
-
37
- ---> 40 data = ocr(img, key)
38
-
39
- 41 print(data)
31
+ import json
40
-
41
- 42
42
32
 
43
33
 
44
34
 
45
- <ipython-input-48-979a5a6d593d> in ocr(image_file, access_token)
35
+ def ocr(image_file, access_token=None):
46
36
 
47
- 32 except KeyError:
37
+ with open(image_file, 'rb') as image:
48
38
 
49
- 33 pass
39
+ base64_image = base64.b64encode(image.read()).decode()
50
40
 
51
- ---> 34 print("textの値は?" + str(text))
41
+ # base64_image = image.read()
52
42
 
53
- 35 return text
43
+
54
44
 
55
- 36
45
+ url = 'https://vision.googleapis.com/v1/images:annotate?key={}'.format(access_token)
56
46
 
47
+ header = {'Content-Type': 'application/json'}
57
48
 
49
+ body = {
58
50
 
51
+ 'requests': [{
52
+
53
+ 'image': {
54
+
55
+ 'content': base64_image,
56
+
57
+ },
58
+
59
+ 'features': [{
60
+
61
+ 'type': 'TEXT_DETECION',
62
+
63
+ 'maxResults': 1,
64
+
65
+ }]
66
+
67
+
68
+
69
+ }]
70
+
71
+ }
72
+
59
- UnboundLocalError: local variable 'text' referenced before assignment
73
+ response = requests.post(url, headers=header, json=body).json()
74
+
75
+ # jsonで吐き出し response
76
+
77
+ # fw = open('vision_response.json','w')
78
+
79
+ # json.dump(response.fw.indent=4)
80
+
81
+
82
+
83
+ # print("responseの値は?" + str(response))
84
+
85
+ try:
86
+
87
+ text = response['responses'][0]['textAnnotations'][0]['description'] if len(response['responses'][0]) > 0 else ''
88
+
89
+ except KeyError:
90
+
91
+ pass
92
+
93
+ print("textの値は?" + str(text))
94
+
95
+ return text
96
+
97
+
98
+
99
+ # imgの画像ファイルのあるPATHは環境に合わせて変更する
100
+
101
+ img = "/content/testtest2.jpg"
102
+
103
+ key = "AIzaSyB1pHeQQwxjs8AE7T615wcvpRJbzmg0np4"
104
+
105
+ data = ocr(img, key)
106
+
107
+ print(data)
108
+
109
+
60
110
 
61
111
  ```
62
112
 

1

本文訂正

2019/07/02 14:22

投稿

0zer0
0zer0

スコア11

test CHANGED
File without changes
test CHANGED
@@ -2,11 +2,7 @@
2
2
 
3
3
 
4
4
 
5
- ここに質問の内容を詳しく書いてください。
6
-
7
- (例)PHP(CakePHP)で●●なシステムを作っています。
8
-
9
- ■■な機能実装中に以下のエラーメッセージが発生しました。
5
+ 名刺からテキスト抽出するプログラムを作成中に以下のエラーメッセージが発生
10
6
 
11
7
 
12
8
 
@@ -75,7 +71,3 @@
75
71
 
76
72
 
77
73
  ### 補足情報(FW/ツールのバージョンなど)
78
-
79
-
80
-
81
- 名刺からテキストを抽出するプログラム