-
Notifications
You must be signed in to change notification settings - Fork 0
/
ColorJudge.py
406 lines (314 loc) · 9.16 KB
/
ColorJudge.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- Python -*-
"""
@file ColorJudge.py
@brief judge the color of anemy
@date $Date$
"""
import sys
import time
sys.path.append(".")
# Import RTM module
import RTC
import OpenRTM_aist
import VelocitySwitcher_idl
import Img
# Import Service implementation class
# <rtc-template block="service_impl">
# </rtc-template>
# Import Service stub modules
# <rtc-template block="consumer_import">
import KanamuraRobotics, KanamuraRobotics__POA
import Img, Img__POA
import cv2
import numpy as np
#red
LOW_COLOR = np.array([110, 50, 50])
HIGH_COLOR = np.array([130, 255, 255])
AREA_RATIO_THRESHOLD = 0.1
# </rtc-template>
# This module's spesification
# <rtc-template block="module_spec">
colorjudge_spec = ["implementation_id", "ColorJudge",
"type_name", "ColorJudge",
"description", "judge the color of anemy ",
"version", "1.0.0",
"vendor", "VenderName",
"category", "Category",
"activity_type", "STATIC",
"max_instance", "1",
"language", "Python",
"lang_type", "SCRIPT",
"conf.default.team_color", "red",
"conf.__widget__.team_color", "radio",
"conf.__constraints__.team_color", "(red, blue)",
"conf.__type__.team_color", "long",
""]
# </rtc-template>
##
# @class ColorJudge
# @brief judge the color of anemy
#
#
class ColorJudge(OpenRTM_aist.DataFlowComponentBase):
##
# @brief constructor
# @param manager Maneger Object
#
def __init__(self, manager):
OpenRTM_aist.DataFlowComponentBase.__init__(self, manager)
self._d_cameraImage = OpenRTM_aist.instantiateDataType(Img.TimedCameraImage)
"""
"""
self._cameraImageIn = OpenRTM_aist.InPort("cameraImage", self._d_cameraImage)
self._d_color = OpenRTM_aist.instantiateDataType(RTC.TimedLong)
"""
"""
self._colorOut = OpenRTM_aist.OutPort("color", self._d_color)
"""
"""
self._colorSwitcherPort = OpenRTM_aist.CorbaPort("colorSwitcher")
"""
"""
self._colorSwitcherService = OpenRTM_aist.CorbaConsumer(interfaceType=KanamuraRobotics.VelocitySwitcherService)
# initialize of configuration-data.
# <rtc-template block="init_conf_param">
"""
- Name: team_color
- DefaultValue: red
"""
self._team_color = ["red"]
# </rtc-template>
##
#
# The initialize action (on CREATED->ALIVE transition)
# formaer rtc_init_entry()
#
# @return RTC::ReturnCode_t
#
#
def onInitialize(self):
# Bind variables and configuration variable
self.bindParameter("team_color", self._team_color, "red")
# Set InPort buffers
self.addInPort("cameraImage",self._cameraImageIn)
# Set OutPort buffers
self.addOutPort("color",self._colorOut)
# Set service provider to Ports
# Set service consumers to Ports
self._colorSwitcherPort.registerConsumer("KanamuraRobotics::VelocitySwitcherService", "VelocitySwitcherService", self._colorSwitcherService)
# Set CORBA Service Ports
self.addPort(self._colorSwitcherPort)
self._detect_count = 0
self._detect_count_threshold = 45
return RTC.RTC_OK
###
##
## The finalize action (on ALIVE->END transition)
## formaer rtc_exiting_entry()
##
## @return RTC::ReturnCode_t
#
##
#def onFinalize(self):
#
# return RTC.RTC_OK
###
##
## The startup action when ExecutionContext startup
## former rtc_starting_entry()
##
## @param ec_id target ExecutionContext Id
##
## @return RTC::ReturnCode_t
##
##
#def onStartup(self, ec_id):
#
# return RTC.RTC_OK
###
##
## The shutdown action when ExecutionContext stop
## former rtc_stopping_entry()
##
## @param ec_id target ExecutionContext Id
##
## @return RTC::ReturnCode_t
##
##
#def onShutdown(self, ec_id):
#
# return RTC.RTC_OK
##
#
# The activated action (Active state entry action)
# former rtc_active_entry()
#
# @param ec_id target ExecutionContext Id
#
# @return RTC::ReturnCode_t
#
#
def onActivated(self, ec_id):
print("onActivated")
retval = self._colorSwitcherService._ptr().setSwitch(True)
print("retval = %s" % retval)
return RTC.RTC_OK
##
#
# The deactivated action (Active state exit action)
# former rtc_active_exit()
#
# @param ec_id target ExecutionContext Id
#
# @return RTC::ReturnCode_t
#
#
def onDeactivated(self, ec_id):
print("onDeactivated")
return RTC.RTC_OK
def _detectColorArea(self, img):
cameraImage = np.fromstring(img.data.image.raw_data,
dtype=np.uint8).reshape(img.data.image.height,
img.data.image.width, -1)
pos = find_specific_color(img,
AREA_RATIO_THRESHOLD,
LOW_COLOR,
HIGH_COLOR)
if pos is not None:
cv2.circle(cameraImage, pos, 10, (0,0,255), -1)
return pos, cameraImage
def _do_something(self):
print("im sleep")
retval = self._colorSwitcherService._ptr().setSwitch(False)
retval = self._colorSwitcherService._ptr().setSwitch(True)
pass
##
#
# The execution action that is invoked periodically
# former rtc_active_do()
#
# @param ec_id target ExecutionContext Id
#
# @return RTC::ReturnCode_t
#
#
def onExecute(self, ec_id):
if self._cameraImageIn.isNew():
img = self._cameraImageIn.read()
pos, cameraImage = self._detectColorArea(img)
#resizedCameraImage = cv2.resize(cameraImage, (img.data.image.width*4, img.data.image.height*4))
if pos is not None:
self._detect_count = self._detect_count + 1
print("Detect Count = %d" % self._detect_count)
else:
self._detect_count = 0
cv2.imshow('frame', cv2.cvtColor(cameraImage, cv2.COLOR_BGR2RGB))
cv2.waitKey(1)
if self._detect_count > self._detect_count_threshold:
self._do_something()
self._detect_count = 0
return RTC.RTC_OK
###
##
## The aborting action when main logic error occurred.
## former rtc_aborting_entry()
##
## @param ec_id target ExecutionContext Id
##
## @return RTC::ReturnCode_t
##
##
#def onAborting(self, ec_id):
#
# return RTC.RTC_OK
###
##
## The error action in ERROR state
## former rtc_error_do()
##
## @param ec_id target ExecutionContext Id
##
## @return RTC::ReturnCode_t
##
##
#def onError(self, ec_id):
#
# return RTC.RTC_OK
###
##
## The reset action that is invoked resetting
## This is same but different the former rtc_init_entry()
##
## @param ec_id target ExecutionContext Id
##
## @return RTC::ReturnCode_t
##
##
#def onReset(self, ec_id):
#
# return RTC.RTC_OK
###
##
## The state update action that is invoked after onExecute() action
## no corresponding operation exists in OpenRTm-aist-0.2.0
##
## @param ec_id target ExecutionContext Id
##
## @return RTC::ReturnCode_t
##
##
#def onStateUpdate(self, ec_id):
#
# return RTC.RTC_OK
###
##
## The action that is invoked when execution context's rate is changed
## no corresponding operation exists in OpenRTm-aist-0.2.0
##
## @param ec_id target ExecutionContext Id
##
## @return RTC::ReturnCode_t
##
##
#def onRateChanged(self, ec_id):
#
# return RTC.RTC_OK
def find_specific_color(frame, AREA_RATIO_THRESHOLD, LOW_COLOR, HIGH_COLOR):
#h,w,c = frame.shape
c = 3
h = frame.data.image.height
w = frame.data.image.width
#print(h, w)
frame = np.fromstring(frame.data.image.raw_data, dtype = np.uint8).reshape(h, w, -1)
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
ex_img = cv2.inRange(hsv, LOW_COLOR, HIGH_COLOR)
_,contours,hierarchy = cv2.findContours(ex_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
areas = np.array(list(map(cv2.contourArea,contours)))
if len(areas) == 0 or np.max(areas) / (h*w) < AREA_RATIO_THRESHOLD:
#print("the area is too small")
return None
else:
max_idx = np.argmax(areas)
max_area = areas[max_idx]
result = cv2.moments(contours[max_idx])
x = int(result["m10"]/result["m00"])
y = int(result["m01"]/result["m00"])
return (x,y)
def ColorJudgeInit(manager):
profile = OpenRTM_aist.Properties(defaults_str=colorjudge_spec)
manager.registerFactory(profile,
ColorJudge,
OpenRTM_aist.Delete)
def MyModuleInit(manager):
ColorJudgeInit(manager)
# Create a component
comp = manager.createComponent("ColorJudge")
def main():
mgr = OpenRTM_aist.Manager.init(sys.argv)
mgr.setModuleInitProc(MyModuleInit)
mgr.activateManager()
mgr.runManager()
if __name__ == "__main__":
main()