-
Notifications
You must be signed in to change notification settings - Fork 1
/
lightfantastic-process
executable file
·355 lines (291 loc) · 8.73 KB
/
lightfantastic-process
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
#!/usr/bin/python3
#
# lightfantastic
# https://github.com/anfractuosity/lightfantastic
#
import argparse
import numpy as np
import cv2
import time
import collections
import copy
import math
import time
import pickle
from operator import itemgetter
from collections import defaultdict
from collections.abc import Sequence
from itertools import tee
from math import *
from lightfantastic.ids import *
from lightfantastic.spatial import *
ZERO_COLOUR = (0, 0, 255)
# LED representation
class LED(Sequence):
def __init__(self, x, y, tim, idv):
self.x = x
self.y = y
self.idv = idv
self.timestamp = collections.deque(maxlen=100000)
self.timestamp.append(tim)
def __getitem__(self, i):
return [self.x, self.y][i]
def __len__(self):
return 2
def __eq__(self, other):
if other == None:
return False
if self == None:
return False
return self.x == other.x and self.y == other.y
def __hash__(self):
return self.idv
def addtimestamp(self, tstamp):
self.timestamp.append(tstamp)
# Detect blobs in frame
def blobdetect(frame):
lthres = 140
ret, frame = cv2.threshold(frame, lthres, 255, 0)
params = cv2.SimpleBlobDetector_Params()
params.minThreshold = lthres
params.maxThreshold = 255
params.filterByArea = False
params.filterByCircularity = False
params.filterByConvexity = False
params.filterByInertia = False
params.filterByColor = True
params.blobColor = 255
detector = cv2.SimpleBlobDetector_create(params)
return detector.detect(frame)
# Find nearest potential LED
def nearesti(allh, search, dist, spatial, rect, brute):
found = []
if brute:
for idv in allh:
ldv = allh[idv]
dst = math.sqrt((search.x - ldv.x) ** 2 + (search.y - ldv.y) ** 2)
if dst < dist:
found.append((dst, ldv))
return sorted(found, key=itemgetter(0))
else:
for idv in spatial.potential_collisions(rect, search):
found.append((None, idv))
break
return found
# Sliding window
def window(iterable, size):
iters = tee(iterable, size)
for i in range(1, size):
for each in iters[i:]:
next(each, None)
return zip(*iters)
# Convert list representing binary, to integer value
def binary(arr):
m = 0
s = 0
for o in arr:
s = s + (o * (2 ** m))
m = m + 1
return s
# Manchester decode
def mancdec(arr):
out = []
for i in range(0, len(arr), 2):
if arr[i : i + 2] == [0, 1]:
out.append(0)
elif arr[i : i + 2] == [1, 0]:
out.append(1)
return out
# Extract bits from frame differences, this then needs to be decoded
# using the mancdec function
def getbits(framediffs, fps, timethreshold):
nout = 0
bits = []
f = ((1 / fps) * 1.5) * 1000
for framediff in framediffs:
if framediff < f:
nout = nout + 1
else:
if nout * ((1 / fps) * 1000) <= timethreshold:
bits.append(1)
else:
bits.extend([1, 1])
if framediff <= timethreshold:
bits.append(0)
else:
bits.extend([0, 0])
nout = 1
return bits
# Calculate CRC checksum
def crc(val):
s = ""
for b in val:
s = s + str(b)
return binascii.crc32(s.encode("ascii")) % 256
# Get blobs from video frames
def getblobs(videofile, brute):
spatial = SpatialHash()
cap = cv2.VideoCapture(videofile)
fps = cap.get(cv2.CAP_PROP_FPS)
potentialleds = {}
blobframes = []
fcount = 0
fps = 0
frameno = 0
old = -1
uid = 0
while True:
# Calculate framerate
timestamp = int(cap.get(cv2.CAP_PROP_POS_MSEC))
fcount = fcount + 1
if fcount > fps:
frameno = frameno + 1
if timestamp > old + 1000 and frameno > 1:
fps = frameno
frameno = 0
old = timestamp
ret, frame = cap.read()
if type(frame) != np.ndarray:
break
# Find blobs, and draw them on image
lastf = frame
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blobs = blobdetect(frame)
im = cv2.drawKeypoints(
frame,
blobs,
np.array([]),
ZERO_COLOUR,
cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS,
)
cv2.imshow("Video", im)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cur = []
if fps > 20:
for k in blobs:
x = k.pt[0]
y = k.pt[1]
cur.append((x, y, k.size))
# Process blobs in current frame
for l in cur:
uid = uid + 1
search_led = LED(l[0], l[1], timestamp, uid)
rect = Rect(x1=l[0] - 1, y1=l[1] - 1, x2=l[0] + 1, y2=l[1] + 1)
nearest = nearesti(potentialleds, search_led, 8, spatial, rect, brute)
# If no previous potential LED, add this LED to potential LEDs
if len(nearest) == 0:
potentialleds[search_led.idv] = search_led
spatial.add_rect(rect, search_led)
continue
# If we found a potential previous LED, add this timestamp to it
add = True
for allv in nearest:
if allv[1].timestamp[-1] != timestamp:
o = allv[1]
o.addtimestamp(timestamp)
o.x = search_led.x
o.y = search_led.y
potentialleds[o.idv] = o
add = False
break
if add:
potentialleds[search_led.idv] = search_led
spatial.add_rect(rect, search_led)
cap.release()
return lastf, potentialleds, fps
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="CLI for lightfantastic")
parser.add_argument(
"--movie",
dest="movie",
type=argparse.FileType("r"),
help="Filename of video of lights",
required=True,
)
parser.add_argument(
"--out",
dest="out",
type=str,
help="Filename to output position of lights",
required=True,
)
parser.add_argument(
"--timethreshold",
dest="timethreshold",
nargs="?",
const=1,
type=int,
default=300,
help="Time threshold (default: 300ms)",
)
parser.add_argument(
"--brute",
dest="brute",
nargs="?",
default=False,
help="Bruteforce find nearby LEDs",
)
args = parser.parse_args()
movie = args.movie.name
timethreshold = args.timethreshold
args.movie.close()
brute = not (args.brute == False)
mp = IDs(0).manchester(IDs(0).preamble)
tagged_leds = {}
lastf, potentialleds, fps = getblobs(movie, brute)
# Find valid LEDs
for key in potentialleds:
t = potentialleds[key].timestamp
led = potentialleds[key]
if len(t) > 20:
t2 = [t[i] for i in range(1, len(t))]
old = t2[0]
out = []
for v in t2[1:]:
out.append(v - old)
old = v
bits = getbits(out, fps, timethreshold)
found = False
most = defaultdict(int)
for x in window(bits, 68):
n2 = [z for z in x]
pre = n2[:32]
if pre == mp:
m = mancdec(n2)
check = binary(m[-8:])
bbb = binary(m[16 : 16 + 10])
if crc(m[0 : 16 + 10]) == check:
most[bbb] = most[bbb] + 1
found = True
break
last = 0
idv = -1
tup = (led.x, led.y)
for k in most:
if most[k] > last:
idv = k
last = most[k]
if found:
tagged_leds[idv] = tup
# Display tagged LEDs on last processed video frame
numleds = 0
for led_id in tagged_leds:
numleds += 1
led_pos = tagged_leds[led_id]
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(
lastf,
str(led_id),
(int(led_pos[0]), int(led_pos[1])),
font,
0.3,
(0, 0, 255),
1,
cv2.LINE_AA,
)
print("Found ", numleds)
pickle.dump(tagged_leds, open(args.out, "wb"))
cv2.imshow("Video", lastf)
cv2.waitKey(0)
cv2.destroyAllWindows()