-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemp.py
102 lines (83 loc) · 2.5 KB
/
temp.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
import cv2
import random
import numpy as np
import rospy
from exercise6 import RecogniseColour, RecogniseColourRequest, RecogniseColourResponse
NEAREST_K = 1
class KNN:
def __init__(self):
# Cylinders
r = open("cyl_red.txt")
rdata = [l.split() for l in r.readlines()]
r.close()
g = open("cyl_green.txt")
gdata = [l.split() for l in g.readlines()]
g.close()
y = open("cyl_yellow.txt")
ydata = [l.split() for l in y.readlines()]
y.close()
b = open("cyl_blue.txt")
bdata = [l.split() for l in b.readlines()]
b.close()
red = random.sample(rdata, 100)
green = random.sample(gdata, 100)
yellow = random.sample(ydata, 100)
blue = random.sample(bdata, 100)
for i in red:
i.append(1)
for i in green:
i.append(2)
for i in yellow:
i.append(3)
for i in blue:
i.append(4)
cdata = np.array(red + green + yellow + blue)
clabels = cdata[:,-1]
cdata = cdata[:, :-1]
self.knnc = cv2.ml.KNearest_create()
self.knnc.train(cdata, cv2.ml.ROW_SAMPLE, clabels)
# Rings
r = open("ring_red.txt")
rdata = [l.split() for l in r.readlines()]
r.close()
g = open("ring_green.txt")
gdata = [l.split() for l in g.readlines()]
g.close()
bc = open("ring_black.txt")
bcdata = [l.split() for l in bc.readlines()]
bc.close()
b = open("ring_blue.txt")
bdata = [l.split() for l in b.readlines()]
b.close()
red = random.sample(rdata, 100)
green = random.sample(gdata, 100)
black = random.sample(bcdata, 100)
blue = random.sample(bdata, 100)
for i in red:
i.append(1)
for i in green:
i.append(2)
for i in black:
i.append(5)
for i in blue:
i.append(4)
rdata = np.array(red + green + black + blue)
rlabels = rdata[:,-1]
rdata = rdata[:, :-1]
self.knnr = cv2.ml.KNearest_create()
self.knnr.train(rdata, cv2.ml.ROW_SAMPLE, rlabels)
model = KNN()
def handle_recognise(req):
hist = np.array(req.hist)
t = req.type
if t == req.CYLINDER:
ret, results, neighbours, dist = model.knnc.findNearest(hist, NEAREST_K)
return RecogniseColourResponse(colour=results[0][0])
elif t == req.RING:
ret, results, neighbours, dist = model.knnr.findNearest(hist, NEAREST_K)
return RecogniseColourResponse(colour=results[0][0])
else:
return RecogniseColourResponse(colour=0)
if __name__ == "__main__":
rospy.init_node('colour_recognition_server')
s = rospy.Service('recognise_colour', RecogniseColour, handle_recognise)