/
imageRecognition.py
236 lines (205 loc) · 7.44 KB
/
imageRecognition.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
import base64
import httplib2
import urllib2, json
import numpy as np
import cv2
import sys
import time
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from picamera.array import PiRGBArray
from picamera import PiCamera
#
# The url template to retrieve the discovery document for trusted testers.
DISCOVERY_URL='https://{api}.googleapis.com/$discovery/rest?version={apiVersion}'
MAX_NUM_IMAGE_DETECTION = 5
inputFlag = False
filename = 'panasonic2.jpg'
def getImage():
# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(640, 480))
# print("setting is end!")
# allow the camera to warmup
# time.sleep(0.1)
dst = None
# capture frames from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
# grab the raw NumPy array representing the image, then initialize the timestamp
# and occupied/unoccupied text
image = frame.array
mtx =np.array([[100, 0, 320], [0, 100, 240], [0, 0, 1]], dtype=np.float32)
dist = np.array([-0.009, 0.0, 0.0, 0.0], dtype=np.float32)
h, w = image.shape[:2]
newcameramtx, roi=cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))
# undistort
dst = cv2.undistort(image, mtx, dist, None, newcameramtx)
break
return dst
#
def imgeDeterminParamCheck(mode):
if mode == 'LOGO_DETECTION':
return True
elif mode == 'LABEL_DETECTION':
return True
elif mode == 'FACE_DETECTION':
return True
elif mode == 'TEXT_DETECTION':
return True
else:
return False
#
def imageDetermin(mode, compStr, rect):
del rect[:]
rect.append(-1)
rect.append(-1)
rect.append(-1)
rect.append(-1)
if imgeDeterminParamCheck(mode) == False:
return '-1'
#
"""Run a label request on a single image"""
if inputFlag == True:
img = cv2.imread(filename, 1)
else:
img = getImage()
if img is None:
return '-1'
img = cv2.resize(img, (int(480.0/img.shape[0]*img.shape[1]), 480) )
#
credentials = GoogleCredentials.get_application_default()
service = discovery.build('vision', 'v1', credentials=credentials,
discoveryServiceUrl=DISCOVERY_URL)
result, imgencode = cv2.imencode('.jpg', img)
data = np.array(imgencode)
image_content = base64.b64encode(data.tostring())
service_request = service.images().annotate(body={
'requests': [{
'image': {
'content': image_content.decode('UTF-8')
},
'features': [{
'type': mode,
'maxResults': MAX_NUM_IMAGE_DETECTION
}]
}]
})
response = service_request.execute()
detectFlag = False
detectList = []
annotations = None
#
size = len(response['responses'][0])
print "size:" + str(size)
if size >= 1:
#
if mode == 'LABEL_DETECTION':
annotations = response['responses'][0]['labelAnnotations']
for label_num in range(0, len(annotations)):
label = annotations[label_num]['description']
score = annotations[label_num]['score']
print('Found label: %s, score: %f' % (label, score))
detectList.append(label)
if compStr in label:
detectFlag = True
reStr = compStr
break
if detectFlag == False:
reStr = detectList[0]
return reStr
#
elif mode == 'LOGO_DETECTION':
annotations = response['responses'][0]['logoAnnotations']
for label_num in range(0, len(annotations)):
logo = annotations[label_num]['description']
score = annotations[label_num]['score']
print('Found logo: %s, score: %f' % (logo, score))
detectList.append(logo)
if compStr in logo:
detectFlag = True
reStr = compStr
break
if detectFlag == False:
reStr = detectList[0]
#
elif mode == 'FACE_DETECTION':
annotations = response['responses'][0]['faceAnnotations']
joyVal = annotations[0]['joyLikelihood']
angVal = annotations[0]['angerLikelihood']
sorVal = annotations[0]['sorrowLikelihood']
sprVal = annotations[0]['surpriseLikelihood']
print ('joyVal %s' % joyVal)
print ('angVal %s' % angVal)
print ('sorVal %s' % sorVal)
print ('sprVal %s' % sprVal)
if joyVal == 'VERY_LIKELY' or joyVal == 'LIKELY' or joyVal == 'POSSIBLE':
reStr = 'JOY'
elif angVal == 'VERY_LIKELY' or angVal == 'LIKELY' or joyVal == 'POSSIBLE':
reStr = 'ANGER'
elif sorVal == 'VERY_LIKELY' or sorVal == 'LIKELY' or joyVal == 'POSSIBLE':
reStr = 'SORROW'
elif sprVal == 'VERY_LIKELY' or sprVal == 'LIKELY' or joyVal == 'POSSIBLE':
reStr = 'SURPRISE'
else :
reStr = 'NORMAL'
#
elif mode == 'TEXT_DETECTION':
annotations = response['responses'][0]['textAnnotations']
txt = annotations[0]['description']
print ('txt:%s' % txt )
if compStr in txt:
reStr = compStr
else:
reStr = '-1'
#
print annotations[0]['boundingPoly']['vertices']
if annotations[0]['boundingPoly']['vertices'][0].has_key('x'):
rect[0] = annotations[0]['boundingPoly']['vertices'][0]['x']
else :
rect[0] = 0
if annotations[0]['boundingPoly']['vertices'][0].has_key('y'):
rect[1] = annotations[0]['boundingPoly']['vertices'][0]['y']
else :
rect[1] = 0
rect[2] = annotations[0]['boundingPoly']['vertices'][2]['x']
rect[3] = annotations[0]['boundingPoly']['vertices'][2]['y']
#
cv2.rectangle(img, (rect[0],rect[1]), (rect[2],rect[3]), (255,255,255), 5)
cv2.imshow('nametag1.jpg', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
return reStr
#
else :
return '-1'
if __name__ == '__main__':
argvs = sys.argv # コマンドライン引数を格納したリストの取得
argc = len(argvs) # 引数の個数
if argc == 2:
inputFlag = True
filename = argvs[1]
rect = []
print 'FACE_DETECTION'
text = imageDetermin('FACE_DETECTION', 'JOY', rect)
print text
print rect
print ''
print 'LABEL_DETECTION'
text = imageDetermin('LABEL_DETECTION', 'dog', rect)
print text
print rect
print ''
print 'TEXT_DETECTION'
text = imageDetermin('TEXT_DETECTION', 'Staff', rect)
print text
print rect
print ''
print 'LOGO_DETECTION'
text = imageDetermin('LOGO_DETECTION', 'panasonic', rect)
print text
print rect