-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathball_detector.py
executable file
·284 lines (208 loc) · 7.69 KB
/
ball_detector.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
#!/usr/bin/env python3
"""
ROS service that implement a ball detector
"""
# Import of libraries
import sys
import time
import numpy as np
from scipy.ndimage import filters
import imutils
import cv2
import roslib
import rospy
from sensor_msgs.msg import CompressedImage
from sensoring.srv import DetectImage,DetectImageResponse
from knowledge.srv import OracleReq
## Variable for logging purpose
VERBOSE = False
detected = False
class image_feature:
"""
A class used to detect a colored ball
Attributes
-----
@param subscriber: variable that represents a subscriber to the camera topic
@type subscriber: Subscriber
@param resp_center: center of the ball
@type resp_center: int
@param resp_radius: radius of the ball
@type resp_radius: int
@param type: color of the ball
@type type: string
Methods
-----
getCenter():
Get the center of the ball
getRadius()
Get the radius of the ball
getType()
Get the color of the ball
ask_oracle(request)
Method used to ask a specific request to the oracle
callback(ros_data)
Callback function of subscribed topic.
Here images get converted and features detected
"""
def __init__(self):
"""
Constuctor. Initialize the node and the attributes, subscribe to topic of the camera
"""
rospy.init_node('image_detector', anonymous=True)
## ROS Subsriber object for getting the images
self.subscriber = rospy.Subscriber("camera1/image_raw/compressed",CompressedImage, self.callback, queue_size=1)
## Center of the ball
self.resp_center = -1
## Radius of the ball
self.resp_radius = -1
## Color of the ball
self.type = "ND"
def getCenter(self):
"""
Get the center of the ball
@returns: center of the ball
@rtype: int
"""
return self.resp_center
def getRadius(self):
"""
Get the radius of the ball
@returns: radius of the ball
@rtype: int
"""
return self.resp_radius
def getType(self):
"""
Get the color of the ball
@returns: color of the ball
@rtype: string
"""
return self.type
def ask_oracle(self,request):
"""
Method used to ask a specific request to the oracle
@param request: request message
@type request: OracleReq
@returns: response to the request
@rtype: OracleReqResponse
"""
rospy.wait_for_service('oracle_req')
try:
target_pos = rospy.ServiceProxy('oracle_req', OracleReq)
resp = target_pos(request)
return resp
except rospy.ServiceException as e:
rospy.logerr("Service call failed: %s",e)
def callback(self, ros_data):
"""
Callback function for converting the images and
detecting the features
@param ros_data: image
@type ros_data: CompressedImage
"""
global detected
if VERBOSE:
print ('received image of type: "%s"' % ros_data.format)
#direct conversion to CV2
np_arr = np.fromstring(ros_data.data, np.uint8)
image_np = cv2.imdecode(np_arr, cv2.IMREAD_COLOR) # OpenCV >= 3.0:
cv2.imshow('window', image_np)
cv2.waitKey(2)
lower = {'black':(0, 0, 0),'red':(0, 50, 50),'yellow':(25, 50, 50),'green':(50, 50, 50),'blue':(100, 50, 50),'magenta':(125, 50, 50)}
upper = {'black':(5,50,50),'red':(5, 255, 255),'yellow':(35, 255, 255),'green':(70, 255, 255),'blue':(130, 255, 255),'magenta':(150, 255, 255)}
blurred = cv2.GaussianBlur(image_np, (11, 11), 0)
hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
if detected == False:
for key, value in upper.items():
mask = cv2.inRange(hsv, lower[key], upper[key])
mask = cv2.erode(mask, None, iterations=2)
mask = cv2.dilate(mask, None, iterations=2)
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
if len(cnts) > 0:
resp = self.ask_oracle("prevDetect "+key)
if(resp.location == "False"):
self.type = key
detected = True
break
else:
mask = cv2.inRange(hsv, lower[self.type], upper[self.type])
mask = cv2.erode(mask, None, iterations=2)
mask = cv2.dilate(mask, None, iterations=2)
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
center = None
# only proceed if at least one contour was found
if len(cnts) > 0:
# find the largest contour in the mask, then use
# it to compute the minimum enclosing circle and
# centroid
c = max(cnts, key=cv2.contourArea)
((x, y), radius) = cv2.minEnclosingCircle(c)
M = cv2.moments(c)
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
# only proceed if the radius meets a minimum size
if radius > 10:
# draw the circle and centroid on the frame,
# then update the list of tracked points
cv2.circle(image_np, (int(x), int(y)), int(radius),
(0, 255, 255), 2)
cv2.circle(image_np, center, 5, (0, 0, 255), -1)
self.resp_center = center[0]
self.resp_radius = radius
else:
self.resp_center = -1
self.resp_radius = -1
detected = False
cv2.imshow('window', image_np)
cv2.waitKey(2)
class ball_info:
"""
A class used to represent a service for providing the radius,center
and color of the ball
Attributes
-----
@param ic: istance of class image_feature
@type ic: image_feature
@param s: service object
@type s: Service
Methods
-----
handle_object(req):
Received a request and reply with the center,radius and color
of the ball(the request is empty)
"""
def __init__(self):
"""
Constuctor. Initialize the node and service, create an instance of the class
image_feature
"""
rospy.init_node('image_detector', anonymous=True)
## Image feature object
self.ic = image_feature()
## ROS service object
self.s = rospy.Service('detect_image', DetectImage, self.handle_object)
def handle_object(self,req):
"""
Received a request and reply with the center,radius and color
of the ball(the request is empty)
@returns: radius and center of the ball
@rtype: DetectImageResponse
"""
resp = DetectImageResponse()
resp.object = self.ic.getType()+" "+str(self.ic.getCenter())+" "+str(self.ic.getRadius())
return resp
def main(args):
"""
Main function.Starting the node
"""
c = ball_info()
try:
rospy.spin()
except KeyboardInterrupt:
print ("Shutting down ROS Image feature detector module")
cv2.destroyAllWindows()
if __name__ == '__main__':
main(sys.argv)