-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdetect.py
1383 lines (972 loc) · 50.4 KB
/
detect.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import logging as log
import math
import datetime
import json
import os
import argparse
import socket
from pathlib import Path
import numpy as np
import numpy.ma as ma
import cv2
from skimage.morphology import disk
import matplotlib.pyplot as plt
import scipy
import circle_fit
INPUT_DIR = "video"
OUTPUT_DIR = "video_processed"
INPUT_FILE = "A6000_10mm_960px.mp4"
MAP_FILE = "2678_data_3_i-1725881.json"
# MAP_FILE = "2633_data_0_i-1303443.json"
SVG_FILE = "debug.svg"
DATA_FILE = "detections.json"
GROUND_TRUTH_FILE = "../blender/ground_truth.json"
ERROR_FILE = "error.json"
UDP_ADDR_RX = ""
UDP_PORT_RX = 5004
UDP_ADDR_TX = "192.168.178.255"
UDP_PORT_TX = 5005
IMAGE_DIMENSIONS = [960, 540]
# --------------------------------------------------
SEGMENTATION_HSV = "hsv"
SEGMENTATION_SOTSU = "singleotsu"
SEGMENTATION_DOTSU = "doubleotsu"
# --------------------------------------------------
THRESHOLD_SQUEEZE = 0.25
THRESHOLD_PRESS = 0.05
ROLLING_BUFFER_LEN = 60
MIN_DETECTED_KEYPOINTS = 3
SEGMENTATION = SEGMENTATION_DOTSU
UNDISTORT = True
CROP_CIRCLE = False
# OUTPUT_FRAMERATE = 30.027
OUTPUT_FRAMERATE = 25
# --------------------------------------------------
# DEBUG
DRAW_LABELS = False
EXPORT_MAP = False
# --------------------------------------------------
MAX_ROT = 6
COLORS = [(255, 0, 0), (0, 255, 0)]
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 1.0
font_scale_med = 0.75
font_scale_small = 0.5
font_color = (255, 255, 255)
font_thickness = 2
font_thickness_med = 1
kernel3 = np.ones((3, 3), np.uint8)
kernel5 = np.ones((5, 5), np.uint8)
kernel7 = np.ones((10, 10), np.uint8)
map_data = {}
with open(MAP_FILE, "r") as f:
map_data = json.load(f)
lookup = map_data["lookup_table"]
neighbour_distances_map = {}
for qrs in lookup.values():
neighbour_distances_map["{}|{}|{}".format(*qrs)] = np.zeros([ROLLING_BUFFER_LEN])
neighbour_distances_map["{}|{}|{}".format(*qrs)][:] = np.nan
event_squeeze = 0
event_press = 0
ground_truth = None
error = []
circlemask = np.zeros([540, 960], dtype=np.uint8)
cv2.circle(circlemask, [960//2, 540//2], (540-60)//2, (255, 255, 255), -1)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
# --------------------------------------------------
params_round = cv2.SimpleBlobDetector_Params()
params_round.minDistBetweenBlobs = 15 #30
params_round.filterByColor = False
params_round.filterByArea = True
params_round.minArea = 200
params_round.maxArea = 5000
# resized
# params_round.minArea = 120
# params_round.maxArea = 1000
params_round.filterByInertia = True
params_round.minInertiaRatio = 0.3
params_round.maxInertiaRatio = 1.0
params_round.filterByConvexity = True
params_round.minConvexity = 0.5
params_round.maxConvexity = 1.0
detector_round = cv2.SimpleBlobDetector_create(params_round)
# --------------------------------------------------
distortion_coeff = np.zeros([1, 5], dtype=np.float64)
distortion_coeff[0, 0] = 3.0 #1.3
camera_matrix = np.identity(3)
camera_matrix[0, 2] = IMAGE_DIMENSIONS[0]/2
camera_matrix[1, 2] = IMAGE_DIMENSIONS[1]/2
camera_matrix[0, 0] = IMAGE_DIMENSIONS[0]
camera_matrix[1, 1] = camera_matrix[0, 0]
# --------------------------------------------------
def prepare_output_frame(channel1, channel2, channel3, channel4):
output_frame = np.zeros((1080, 1920, 3), np.uint8)
output_frame[0:540, 0:960] = channel1 # top left
output_frame[0:540, 960:] = channel2 # top right
output_frame[540:, 0:960] = channel3 # bottom left
output_frame[540:, 960:] = channel4 # bottom right
if DRAW_LABELS:
label_channel2 = "marker points"
label_channel3 = "filtered"
label_channel4 = "processed"
offset = (12, 35)
output_frame = cv2.putText(output_frame, "input", (offset[0], offset[1]), font, font_scale, (0, 0, 0), font_thickness+10, cv2.LINE_AA)
output_frame = cv2.putText(output_frame, label_channel2, (960+offset[0], offset[1]), font, font_scale, (0, 0, 0), font_thickness+10, cv2.LINE_AA)
output_frame = cv2.putText(output_frame, label_channel3, (offset[0], 540+offset[1]), font, font_scale, (0, 0, 0), font_thickness+10, cv2.LINE_AA)
output_frame = cv2.putText(output_frame, label_channel4, (960+offset[0], 540+offset[1]), font, font_scale, (0, 0, 0), font_thickness+10, cv2.LINE_AA)
output_frame = cv2.putText(output_frame, "input", (offset[0], offset[1]), font, font_scale, (255, 255, 255), font_thickness, cv2.LINE_AA)
output_frame = cv2.putText(output_frame, label_channel2, (960+offset[0], offset[1]), font, font_scale, (255, 255, 255), font_thickness, cv2.LINE_AA)
output_frame = cv2.putText(output_frame, label_channel3, (offset[0], 540+offset[1]), font, font_scale, (255, 255, 255), font_thickness, cv2.LINE_AA)
output_frame = cv2.putText(output_frame, label_channel4, (960+offset[0], 540+offset[1]), font, font_scale, (255, 255, 255), font_thickness, cv2.LINE_AA)
return output_frame
def process(img, preprocessed_keypoints=None):
info = {
"rotation": None,
"press": None,
"press_values": {},
"squeeze": None,
"push": None,
"found_patterns": []
}
# event variables
global event_squeeze
global event_press
event_squeeze = event_squeeze * 0.8
event_press = event_press * 0.8
output_frame = None
hsv = None
keypoints = None
channel3 = img
if img is not None:
# undistort captured image
if UNDISTORT:
img = cv2.undistort(img, camera_matrix, distortion_coeff, None, None)
crop = 0.10
img = cv2.resize(img[
int(540*crop/2):int(540-(540*crop/2)),
int(960*crop/2):int(960-(960*crop/2))],
(960, 540))
if CROP_CIRCLE:
img[circlemask == 0] = [0, 0, 0]
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
if SEGMENTATION == SEGMENTATION_HSV:
# blue channel
low_0 = [95-10, 20, 50]
high_0 = [140, 255, 255]
# green channel
low_1 = [30+5, 20, 50]
high_1 = [94-10, 255, 255]
# red channel
low_ring1 = [140+20, 100, 100]
high_ring1 = [180, 255, 255]
low_ring2 = [0, low_ring1[1], low_ring1[2]]
high_ring2 = [30-20, 255, 255]
image_0 = cv2.inRange(hsv, np.array(low_0), np.array(high_0))
filtered_0 = cv2.erode(image_0, kernel3, iterations = 2)
filtered_0 = cv2.dilate(filtered_0, kernel7, iterations = 1)
blobs_0 = detector_round.detect(filtered_0)
image_1 = cv2.inRange(hsv, np.array(low_1), np.array(high_1))
filtered_1 = cv2.erode(image_1, kernel3, iterations = 2)
filtered_1 = cv2.dilate(filtered_1, kernel7, iterations = 1)
blobs_1 = detector_round.detect(filtered_1)
ring_mask1 = cv2.inRange(hsv, np.array(low_ring1), np.array(high_ring1))
ring_mask2 = cv2.inRange(hsv, np.array(low_ring2), np.array(high_ring2))
image_ring = ring_mask1 | ring_mask2
filtered_ring = cv2.erode(image_ring, kernel3, iterations = 2)
filtered_ring = cv2.dilate(image_ring, kernel7, iterations = 1)
keypoints = np.empty([len(blobs_0) + len(blobs_1), 4], float) # X, Y, size, color
for i in range(0, len(blobs_0)):
keypoint = blobs_0[i]
keypoints[i, 0] = keypoint.pt[0] # X
keypoints[i, 1] = keypoint.pt[1] # Y
keypoints[i, 2] = keypoint.size # size
keypoints[i, 3] = 0 # color
for i in range(0, len(blobs_1)):
keypoint = blobs_1[i]
keypoints[len(blobs_0) + i, 0] = keypoint.pt[0] # X
keypoints[len(blobs_0) + i, 1] = keypoint.pt[1] # Y
keypoints[len(blobs_0) + i, 2] = keypoint.size # size
keypoints[len(blobs_0) + i, 3] = 1 # color
if args["show"] or args["write"]:
# filtered_both = np.zeros([*filtered_0.shape, 3], dtype=np.uint8)
filtered_both = cv2.cvtColor(cv2.split(hsv)[1], cv2.COLOR_GRAY2BGR)
filtered_both[filtered_ring > 0, :] = (0, 0, 255)
filtered_both[filtered_0 > 0, :] = (255, 0, 0)
filtered_both[filtered_1 > 0, :] = (0, 255, 0)
channel3 = filtered_both
elif SEGMENTATION in [SEGMENTATION_SOTSU, SEGMENTATION_DOTSU]:
resize_factor = 1
# resize_shape = [img.shape[1]//resize_factor, img.shape[0]//resize_factor]
# hsv_resized = cv2.resize(hsv, resize_shape, interpolation=cv2.INTER_AREA)
hsv_resized = hsv
blobmask_resized = None
if SEGMENTATION == SEGMENTATION_SOTSU:
low_0 = [30, 10, 20]
high_0 = [140, 255, 255]
image_0 = cv2.inRange(hsv_resized, np.array(low_0), np.array(high_0))
x_low_0 = [30, 10, 180]
x_high_0 = [140, 20, 255]
image_0_x = cv2.inRange(hsv_resized, np.array(x_low_0), np.array(x_high_0))
image_0[image_0_x > 0] = 0
filtered_0 = cv2.erode(image_0, kernel3, iterations = 2)
filtered_0 = cv2.dilate(filtered_0, kernel3, iterations = 1)
blobmask_resized = filtered_0
elif SEGMENTATION == SEGMENTATION_DOTSU:
low_0 = [20, 0, 50]
high_0 = [150, 255, 255]
img_range = cv2.inRange(hsv_resized, np.array(low_0), np.array(high_0))
filtered = cv2.erode(img_range, kernel3, iterations = 2)
filtered = cv2.dilate(filtered, kernel3, iterations = 1)
segmented_only_v = hsv_resized[:, :, 2]
segmented_only_v[filtered == 0] = 255
segmented_only_v = cv2.erode(segmented_only_v, kernel3, iterations = 2)
segmented_only_v = cv2.dilate(segmented_only_v, kernel3, iterations = 1)
ret, th_mask = cv2.threshold(segmented_only_v, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
th_mask = ~th_mask # invert the image for analysis
blobmask_resized = th_mask
detections = detector_round.detect(blobmask_resized)
keypoints = np.zeros([len(detections), 4], dtype=float)
blobs = np.zeros([len(detections), 3], dtype=float)
if len(detections) >= 2:
for i in range(0, len(detections)):
# centroid patch color
row = int(detections[i].pt[1])
col = int(detections[i].pt[0])
patch_rad = 10
row_min = max(row-patch_rad, 0)
col_min = max(col-patch_rad, 0)
row_max = min(row+patch_rad, hsv_resized.shape[0])
col_max = min(col+patch_rad, hsv_resized.shape[1])
centroid_region = hsv_resized[row_min:row_max+1, col_min:col_max+1, :]
blobs[i] = np.mean(centroid_region, axis=(0, 1))
# blobs_otsu = np.asarray(blobs + blobs_stuffing, dtype=np.uint8)
th_value_h, th_mask_h = cv2.threshold(blobs[:, 0].astype(dtype=np.uint8), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
th_value_s, th_mask_s = cv2.threshold(blobs[:, 1].astype(dtype=np.uint8), 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
for i in range(0, len(detections)):
keypoints[i, 0] = detections[i].pt[0] * resize_factor
keypoints[i, 1] = detections[i].pt[1] * resize_factor
keypoints[i, 2] = 30
# otsu
# only H
if blobs[i, 0] > th_value_h:
keypoints[i, 3] = 0
else:
keypoints[i, 3] = 1
if args["show"] or args["write"]:
# show patches with color indicator point in the center
channel3 = cv2.resize(cv2.cvtColor(blobmask_resized, cv2.COLOR_GRAY2BGR), [img.shape[1], img.shape[0]], interpolation=cv2.INTER_AREA)
for i in range(0, len(keypoints)):
keypoint = keypoints[i]
c = np.zeros([1, 1, 3], dtype=np.uint8)
c[0, 0, :] = [int(blobs[i, 0]), 255, 255] # viz only Hue channel
c = cv2.cvtColor(c, cv2.COLOR_HSV2BGR)
c = c[0, 0].tolist()
cv2.circle(channel3, [int(keypoint[0]), int(keypoint[1])], int(keypoint[2]/2)*2, c, -1)
for i in range(0, len(keypoints)):
cv2.circle(channel3, [int(keypoints[i][0]), int(keypoints[i][1])], 8, COLORS[int(keypoints[i][3])], -1)
else:
log.error("unknown segmentation: {}".format(SEGMENTATION))
sys.exit(-1)
else:
img = np.zeros([540, 960, 3], dtype=np.uint8)
hsv = np.zeros([540, 960, 3], dtype=np.uint8)
channel3 = img
keypoints = np.empty([len(preprocessed_keypoints), 4], float) # X, Y, size, color
for i in range(0, len(preprocessed_keypoints)):
keypoints[i][0] = preprocessed_keypoints[i][0] + 960/2
keypoints[i][1] = preprocessed_keypoints[i][1] + 540/2
keypoints[i][2] = preprocessed_keypoints[i][2]
keypoints[i][3] = preprocessed_keypoints[i][3]
if args["show"] or args["write"]:
image_with_keypoints = cv2.cvtColor(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), cv2.COLOR_GRAY2BGR)
info_img = np.zeros((540, 960, 3), np.uint8)
channel1 = img
channel2 = image_with_keypoints
channel4 = info_img
output_frame = prepare_output_frame(channel1, channel2, channel3, channel4)
if keypoints.shape[0] <= 7:
return output_frame, info
# NEIGHBOURS
# rows: keypoints, columns: rotation positions, depth: QRS hexagon coordinates
rotation_pos = np.zeros([keypoints.shape[0], MAX_ROT, 3], dtype=int)
rotation_pos_valid = np.zeros([keypoints.shape[0], MAX_ROT], dtype=bool)
# keypoints, rotation positions, neighbours keypoint index
neighbour_pos = np.zeros([keypoints.shape[0], MAX_ROT, 6], dtype=int)
# keypoints
avg_circularity = np.full([keypoints.shape[0]], np.nan)
neighbour_distances = np.full([keypoints.shape[0]], np.nan)
neighbour_distances_diffratio = np.full([keypoints.shape[0]], np.nan)
distances = scipy.spatial.distance.cdist(keypoints[:, 0:2], keypoints[:, 0:2])
for i in range(0, keypoints.shape[0]):
neighbour_indices = np.argsort(distances[i])[1:7]
# sanity check: is the main blob really in the center? If not the blob lies on the border of the image
if abs(np.mean(keypoints[neighbour_indices, 0]) - keypoints[i, 0]) > 20 or abs(np.mean(keypoints[neighbour_indices, 1]) - keypoints[i, 1]) > 20:
continue
neighbour_order = np.argsort([get_rot(*keypoints[ind, 0:2], offset=keypoints[i, 0:2]) for ind in neighbour_indices]) # order ascending
# order is ascending, so counter-clockwise, but values are stored
# clockwise (flat top hex, starting at 1 o'clock). So reverse array:
neighbour_order = np.flip(neighbour_order)
# calculate circularity for squeeze
distances_neighbours = scipy.spatial.distance.cdist(keypoints[neighbour_indices[neighbour_order], 0:2], [keypoints[i, 0:2]]) # distance from center to neighbours
mean_distances_neighbours = np.mean(distances_neighbours)
# sanity check 2: does the pattern include an outlier neighbour? (happens when a single point was lost during blob detection)
if np.max(distances_neighbours) > mean_distances_neighbours * 1.20:
continue
# ratio of diff of min/max distance
avg_circularity[i] = ((np.max(distances_neighbours)-np.min(distances_neighbours))/mean_distances_neighbours)
neighbour_distances[i] = mean_distances_neighbours
for rot_step in range(0, 6):
pattern = [keypoints[i, 3]]
rotated_order = np.roll(neighbour_order, rot_step)
for n_index in rotated_order:
pattern.append(keypoints[neighbour_indices[n_index], 3])
pattern_pos = find_in_table(pattern)
if not pattern_pos is None:
rotation_pos[i, rot_step] = pattern_pos
neighbour_pos[i, rot_step] = [neighbour_indices[ind] for ind in rotated_order]
rotation_pos_valid[i, rot_step] = True
matching_neighbours = np.zeros([keypoints.shape[0], 6], dtype=int)
for i in range(0, rotation_pos.shape[0]):
for rot_step in range(0, rotation_pos.shape[1]):
if not rotation_pos_valid[i, rot_step]:
continue
# check if all keypoint neighbours are real neighbours on the map as well
detected_keypoint = keypoints[i]
neighbours_of_detected_keypoint = neighbour_pos[i][rot_step]
hex_coordinate_of_detected_keypoint = rotation_pos[i, rot_step]
hex_coordinates_of_map_neighbours = get_neighbours(*hex_coordinate_of_detected_keypoint)
for ind in neighbours_of_detected_keypoint:
if not rotation_pos_valid[ind, rot_step]:
continue
hex_coordinates_of_detected_keypoints_neighbour = rotation_pos[ind, rot_step]
if hex_coordinates_of_detected_keypoints_neighbour.tolist() in hex_coordinates_of_map_neighbours:
matching_neighbours[i, rot_step] += 1
rot_values = np.argmax(matching_neighbours, axis=1)
# min number of confirmed neighbours to be valid
rotation_pos_valid[np.max(matching_neighbours, axis=1) <= 3] = False
map_detected = {}
for i in range(0, rot_values.shape[0]):
map_detected["{}|{}|{}".format(*rotation_pos[i, rot_values[i]])] = True
# using rot_values as a list of indices to filter along the second dimensions (ie. column) requires
# take_along_axis as well as expand_dims to match dimensions
num_detected_keypoints = np.count_nonzero(np.take_along_axis(rotation_pos_valid, np.expand_dims(rot_values, axis=1), axis=1))
if num_detected_keypoints < MIN_DETECTED_KEYPOINTS:
return output_frame, info
for i in range(0, keypoints.shape[0]):
if not rotation_pos_valid[i, rot_values[i]]:
continue
qrs = rotation_pos[i, rot_values[i]]
# circular buffer for cheap (TODO: basically anything else would be faster)
buffer = neighbour_distances_map["{}|{}|{}".format(*qrs)]
buffer = np.roll(neighbour_distances_map["{}|{}|{}".format(*qrs)], -1)
buffer[-1] = neighbour_distances[i]
neighbour_distances_map["{}|{}|{}".format(*qrs)] = buffer
# calculate rotation
blob_rot = None
src = []
dst = []
for i in range(0, keypoints.shape[0]):
if not rotation_pos_valid[i, rot_values[i]]:
continue
# flip Y axis (math coordinate system is bottom left)
# normalization not necessary, that's done by align_vectors()
src.append([keypoints[i, 0], 540-keypoints[i, 1], 0])
x, y = pointy_hex_to_pixel(*rotation_pos[i, rot_values[i]])
dst.append([x, y, 0])
src = np.asarray(src, dtype=float)
dst = np.asarray(dst, dtype=float)
# center around origin (scipy's Kabsch algorithm does not do that)
src = src - np.mean(src, axis=0)
dst = dst - np.mean(dst, axis=0)
try:
# align_vectors() is scipy's wrapper for Kabsch's algorithm
estimated_rot, rmsd = scipy.spatial.transform.Rotation.align_vectors(dst, src)
blob_rot = estimated_rot.as_euler("XYZ")
if math.isclose(blob_rot[0], 180):
blob_rot = None
elif blob_rot[2] < 0:
blob_rot = math.tau + blob_rot[2]
else:
blob_rot = blob_rot[2]
except Exception as e:
log.error("processing rotation failed: {}".format(e))
if args["ground_truth"]:
error.append({
"frame": frame_counter,
"rotation": blob_rot,
"rotation_deg": math.degrees(blob_rot),
"gt_rotation": ground_truth[frame_counter]["rotation"],
"gt_rotation_deg": math.degrees(ground_truth[frame_counter]["rotation"]),
})
info["rotation"] = blob_rot
# detect squeeze
if np.nanmean(avg_circularity) > THRESHOLD_SQUEEZE:
event_squeeze += 1
if event_squeeze >= 2:
info["squeeze"] = True
else:
info["squeeze"] = False
# detect press
if np.count_nonzero(neighbour_distances) > 0:
max_patterns = []
max_patterns_neighbours = []
for i in range(0, keypoints.shape[0]):
if np.isnan(neighbour_distances[i]):
continue
qrs = rotation_pos[i, rot_values[i]]
key = "{}|{}|{}".format(*qrs)
mean = np.nanmean(neighbour_distances_map[key])
if not np.isnan(mean):
val = (neighbour_distances[i] - mean)/mean
neighbour_distances_diffratio[i] = val
info["press_values"][key] = val
if val > THRESHOLD_PRESS:
max_patterns.append(key)
max_patterns_neighbours.append(get_neighbours_keys(*qrs)) # TODO: uargh
for i in range(0, len(max_patterns)):
count = 0
for n in max_patterns_neighbours[i]:
if n in max_patterns:
count += 1
if count >= 5:
event_press += 1
if event_press >= 2:
info["press"] = True
else:
info["press"] = False
# detect push
# CENTROID OF ALL DETECTED POINTS
pos = np.zeros([2], dtype=float)
for i in range(0, keypoints.shape[0]):
if not rotation_pos_valid[i, rot_values[i]]:
continue
pos = np.add(pos, keypoints[i, 0:2])
if num_detected_keypoints > 3:
pos /= num_detected_keypoints
# normalize for square with a side length of image width
# caveat: number will exceed [-1, 1] for diagonals
pos = [
(pos[0]-IMAGE_DIMENSIONS[0]/2)/(IMAGE_DIMENSIONS[0]/2)*-1,
(pos[1]-IMAGE_DIMENSIONS[1]/2)/(IMAGE_DIMENSIONS[0]/2)*-1,
]
info["push"] = pos
# viz
if args["show"] or args["write"]:
info_img[:] = (77, 77, 77)
if info["press"]:
info_img[:] = (0, 0, 120)
if info["squeeze"]:
info_img[:] = (0, 120, 0)
for i in range(0, keypoints.shape[0]):
if rotation_pos_valid[i][rot_values[i]]:
# cv2.circle(image_with_keypoints, [int(keypoints[i][0]), int(keypoints[i][1])], int(keypoints[i][2]/2), (255, 255, 255), -1)
cv2.circle(image_with_keypoints, [int(keypoints[i][0]), int(keypoints[i][1])], 8, (255, 255, 255), -1)
else:
# cv2.circle(image_with_keypoints, [int(keypoints[i][0]), int(keypoints[i][1])], int(keypoints[i][2]/2), (0, 0, 0), -1)
cv2.circle(image_with_keypoints, [int(keypoints[i][0]), int(keypoints[i][1])], 8, (0, 0, 0), -1)
for i in range(keypoints.shape[0]):
color = (255, 0, 0)
if keypoints[i, 3] == 1:
color = (0, 255, 0)
cv2.circle(image_with_keypoints, [int(keypoints[i, 0]), int(keypoints[i, 1])], int(keypoints[i, 2]/2), color, 4)
# map detections
dist = 10
for key in map_data["data"]:
q, r, s = [int(c) for c in key.split("|")]
x, y = pointy_hex_to_pixel(q, r, s, hex_size=dist, center=[960-150, 540-140])
color = (0, 0, 0)
if map_data["data"][key] == 0:
color = (50, 0, 0)
elif map_data["data"][key] == 1:
color = (0, 50, 0)
if key in map_detected:
color = [255 if c > 0 else 0 for c in color]
cv2.circle(info_img, [int(x), int(y)], 6, color, -1)
if EXPORT_MAP:
export_dist = 40
export_diam = 25
map_image = np.zeros([1000, 1000, 4], dtype=np.uint8)
for key in map_data["data"]:
q, r, s = [int(c) for c in key.split("|")]
x, y = pointy_hex_to_pixel(q, r, s, hex_size=export_dist, center=[1000//2, 1000//2])
color = (0, 0, 0)
if map_data["data"][key] == 0:
color = (100, 0, 0, 90)
elif map_data["data"][key] == 1:
color = (0, 100, 0, 90)
if key in map_detected:
color = [255 if c > 0 else 0 for c in color]
cv2.circle(map_image, [int(x), int(y)], export_diam, color, -1)
cv2.imwrite(os.path.join("export_map", "{}.png".format(frame_counter)), map_image)
# fill empty images in sequence
map_image = np.zeros([1000, 1000, 4], dtype=np.uint8)
for key in map_data["data"]:
q, r, s = [int(c) for c in key.split("|")]
x, y = pointy_hex_to_pixel(q, r, s, hex_size=export_dist, center=[1000//2, 1000//2])
color = (0, 0, 0)
if map_data["data"][key] == 0:
color = (100, 0, 0, 90)
elif map_data["data"][key] == 1:
color = (0, 100, 0, 90)
cv2.circle(map_image, [int(x), int(y)], export_diam, color, -1)
for i in range(0, frame_counter):
filename = os.path.join("export_map", "{}.png".format(i))
if not os.path.exists(filename):
cv2.imwrite(filename, map_image)
# map pressure
for key in map_data["data"]:
q, r, s = [int(c) for c in key.split("|")]
x, y = pointy_hex_to_pixel(q, r, s, hex_size=dist, center=[960-150, 140])
color = [128, 128, 128]
val = 0
if key in info["press_values"]:
val = info["press_values"][key] * 1000
color = (128, 128+val, 128-val)
if info["press_values"][key] > THRESHOLD_PRESS:
color = (255, 255, 255)
color = [255 if c > 255 else int(c) for c in color]
cv2.circle(info_img, [int(x), int(y)], 6, color, -1)
# rotation
if blob_rot is not None:
angle = math.degrees(blob_rot)
cv2.putText(info_img, "Rotation: {:5.2f} deg".format(angle), (10, 100), font, font_scale, (255, 255, 255), 2, cv2.LINE_AA)
cv2.line(channel2, (960//2, 540//2), (int(960/2+300*math.cos(blob_rot)), int(540/2+300* math.sin(blob_rot))), (255, 255, 255), thickness=10)
if args["ground_truth"]:
gt = math.degrees(ground_truth[frame_counter]["rotation"])
cv2.putText(info_img,
"gt: {:5.2f} | diff: {:5.2f}".format(gt, angle-gt, -1),
(400, 100), font, font_scale, (255, 255, 255), 2, cv2.LINE_AA)
cv2.rectangle(channel2, (30, 540-50-30), (30+290, 540-30), (255, 255, 255), -1)
# cv2.rectangle(channel2, (30, 540-50-30), (30+290, 540-30), (50, 50, 50), 2)
cv2.putText(channel2, "Rotation: {:6.2f} deg".format(angle), (30+15, 540-30-16), font, font_scale_med, (0, 0, 0), font_thickness_med, cv2.LINE_AA)
# squeeze
if np.count_nonzero(avg_circularity) > 0:
cv2.putText(info_img, "Avg circularity: {:5.2f}".format(np.nanmean(avg_circularity)), (10, 200), font, font_scale, (255, 255, 255), 2, cv2.LINE_AA)
cv2.putText(info_img, "Squeeze: {}".format("X" if info["squeeze"] else "_"), (10, 250), font, font_scale, (255, 255, 255), 2, cv2.LINE_AA)
if info["squeeze"]:
cv2.rectangle(channel2, (320+15, 540-50-30), (335+140, 540-30), (255, 255, 255), -1)
cv2.putText(channel2, "Squeeze".format(angle), (325+30, 540-30-16), font, font_scale_med, (0, 0, 0), font_thickness_med, cv2.LINE_AA)
# press
if np.count_nonzero(neighbour_distances) > 0:
cv2.putText(info_img, "Distances: {:5.0f} | {:5.0f} | {:5.0f}".format(
np.nanmin(neighbour_distances),
np.nanmax(neighbour_distances),
np.nanmean(neighbour_distances)), (10, 350), font, font_scale, (255, 255, 255), 2, cv2.LINE_AA)
cv2.putText(info_img, "Press: {}".format("X" if info["press"] else "_"), (10, 400), font, font_scale, (255, 255, 255), 2, cv2.LINE_AA)
if info["press"]:
cv2.rectangle(channel2, (320+15, 540-50-30), (335+140, 540-30), (255, 255, 255), -1)
cv2.putText(channel2, "Press".format(angle), (325+50, 540-30-16), font, font_scale_med, (0, 0, 0), font_thickness_med, cv2.LINE_AA)
# debug
for i in range(0, keypoints.shape[0]):
if not np.isnan(neighbour_distances[i]):
val = None
qrs = rotation_pos[i, rot_values[i]]
val = neighbour_distances_diffratio[i] * 100
if val is not None and abs(val) > 5:
cv2.putText(image_with_keypoints, "{:3.0f}".format(val),
(int(keypoints[i, 0]-18), int(keypoints[i, 1]+5)), font, font_scale_small, (0, 0, 0), 1+5, cv2.LINE_AA)
cv2.putText(image_with_keypoints, "{:3.0f}".format(val),
(int(keypoints[i, 0]-18), int(keypoints[i, 1]+5)), font, font_scale_small, (255, 255, 255), 1, cv2.LINE_AA)
# push
if info["push"] is not None:
if abs(info["push"][0])+abs(info["push"][1]) > 0.2 and (args["show"] or args["write"]):
cv2.line(channel2,
(960//2, 540//2),
(int(960/2 + pos[0]*960/2), int(540/2 + pos[1]*960/2)),
(0, 0, 255), thickness=10)
output_frame = prepare_output_frame(channel1, channel2, channel3, channel4)
if args["svg"] is True:
write_svg(keypoints, rotation_pos, rotation_pos_valid, rot_values)
for key in map_data["data"]:
if key in map_detected:
info["found_patterns"].append(key)
return output_frame, info
def pointy_hex_to_pixel(q, r, s, hex_size=1, center=[0, 0]):
x = hex_size * (math.sqrt(3) * q + math.sqrt(3)/2 * r)
y = hex_size * (3./2 * r)
return (x + center[0], y + center[1])
def find_in_table(values):
try:
key = " ".join([str(int(x)) for x in values])
return lookup[key]
except KeyError as ke:
return None
def get_rot(x, y, offset=(0, 0)): # returns turn (1 = full rotation)
deg = 0
# y = ((offset[0]*2)-y - offset[1]) # flip Y axis to bottom 0
y = (y - offset[1])
x = (x - offset[0])
turn = math.atan2(y, x) - math.pi # atan2 [PI, -PI]
return -(turn / math.tau)
def get_neighbours(q, r, s):
return [
[q+1, r-1, s+0], # top right (1 o'clock)
[q+1, r+0, s-1], # right (3 o'clock)
[q+0, r+1, s-1], # ...
[q-1, r+1, s+0],
[q-1, r+0, s+1],
[q+0, r-1, s+1], # top left (11 o'clock)
]
def get_neighbours_keys(q, r, s):
return ["{}|{}|{}".format(*qrs) for qrs in get_neighbours(q, r, s)]
def write_svg(keypoints, rotation_pos, rotation_pos_valid, rot_values):
with open(SVG_FILE, "w") as f:
f.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n")
f.write("<?xml-stylesheet href=\"style.css\" type=\"text/css\" title=\"main_stylesheet\" alternate=\"no\" media=\"screen\" ?>\n")
f.write("<svg baseProfile=\"tiny\" version=\"1.2\" width=\"{}{}\" height=\"{}{}\" \n".format(960, "px", 540, "px"))
f.write("xmlns=\"http://www.w3.org/2000/svg\" xmlns:ev=\"http://www.w3.org/2001/xml-events\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n")
f.write("xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\"")
f.write(">\n")
f.write("<defs />\n")
f.write("<style>\n")
# f.write(".blob {opacity: 0.1;}")
# for i in range(0, len(keypoints)):
# f.write(".map-blob-{}:hover ~ .blob-{} {{opacity: 1.0;}}\n".format(i, i))
# f.write(".map-blob-{}:hover {{opacity: 0.0;}}\n".format(i, i))
f.write("</style>\n")
# layer base
f.write("<g inkscape:groupmode=\"layer\" id=\"{}\" inkscape:label=\"{}\">\n".format("layer1", "base"))
for i in range(0, len(keypoints)):
p = keypoints[i]
color = "blue"
if p[3] == 1:
color = "green"
f.write("<circle cx=\"{}\" cy=\"{}\" r=\"{}\" fill=\"{}\"/>\n".format(p[0], p[1], p[2]/2, color))
f.write("</g>")
# layer keypoint ID
f.write("<g inkscape:groupmode=\"layer\" id=\"{}\" inkscape:label=\"{}\">\n".format("layer2", "keypoint IDs"))
for i in range(0, len(keypoints)):
p = keypoints[i]
f.write("<text x=\"{}\" y=\"{}\" text-anchor=\"middle\" fill=\"white\">{}</text>".format(p[0], p[1]+5, str(i)))
f.write("</g>")
# layer map
f.write("<g inkscape:groupmode=\"layer\" id=\"{}\" inkscape:label=\"{}\">\n".format("layer3", "map"))
dist = 8
center = [960-80, 540-70]
for key in map_data["data"].keys():
q, r, s = [int(c) for c in key.split("|")]
x, y = pointy_hex_to_pixel(q, r, s, hex_size=dist, center=center)
color = "blue"
if map_data["data"][key] == 1:
color = "green"
# cv2.circle(info_img, [offset[0]+dist*l, offset[1]+dist*k], 6, color, -1)
f.write("<circle cx=\"{}\" cy=\"{}\" r=\"{}\" fill=\"{}\" opacity=\"0.25\" />\n".format(x, y, 4, color))
f.write("</g>")
# layer map blobs
f.write("<g inkscape:groupmode=\"layer\" id=\"{}\" inkscape:label=\"{}\" >\n".format("layer4", "map blob"))
for i in range(0, rotation_pos.shape[0]):
if not rotation_pos_valid[i, rot_values[i]]:
continue
q, r, s = rotation_pos[i, rot_values[i]]
color="blue"
if map_data["data"]["{}|{}|{}".format(q, r, s)]:
color = "green"
x, y = pointy_hex_to_pixel(q, r, s, hex_size=dist, center=center)
f.write("<circle cx=\"{}\" cy=\"{}\" r=\"{}\" fill=\"{}\" opacity=\"1.0\" class=\"map-blob map-blob-{}\" ".format(x, y, 4, color, i))
f.write("onmouseover=\"document.getElementById('blob-{}').style.opacity = 1.0;\" ".format(i))
f.write("onmouseout=\"document.getElementById('blob-{}').style.opacity = 0.0;\" ".format(i))
f.write("/>\n")
f.write("</g>\n")
# layer blobs
for i in range(0, rotation_pos.shape[0]):
if not rotation_pos_valid[i, rot_values[i]]:
continue
# use display:none to set the layer to disabled in inkscape
f.write("<g inkscape:groupmode=\"layer\" id=\"blob-{}\" opacity=\"0.0\" inkscape:label=\"blob {}\" >\n".format(i, i))
rot_value = rot_values[i]
p = keypoints[i]
f.write("<circle cx=\"{}\" cy=\"{}\" r=\"{}\" fill=\"none\" stroke-width=\"5\" stroke=\"red\" class=\"blob\" />\n".format(p[0], p[1], p[2]/2))
q, r, s = rotation_pos[i, rot_values[i]]
f.write("<text x=\"800\" y=\"300\" text-anchor=\"left\" fill=\"black\">rotation: {}</text>".format(rot_value))
f.write("<text x=\"800\" y=\"320\" text-anchor=\"left\" fill=\"black\">coordinates: {:5.1f} {:5.1f}</text>".format(keypoints[i, 0], (keypoints[i, 1])))
f.write("<text x=\"800\" y=\"340\" text-anchor=\"left\" fill=\"black\">hex: {}, {}, {}</text>".format(q, r, s))
# correct detected snippet for info box
dist = 22
center = [880, 200]
neighbours = get_neighbours(q, r, s)
offset = pointy_hex_to_pixel(q, r, s, hex_size=dist)
center = [center[0]-offset[0], center[1]-offset[1]]
for c in [[q, r, s]] + neighbours:
x, y = pointy_hex_to_pixel(*c, hex_size=dist, center=center)
color = "blue"
if map_data["data"]["{}|{}|{}".format(*c)] == 1:
color = "green"
f.write("<circle cx=\"{}\" cy=\"{}\" r=\"{}\" fill=\"{}\" opacity=\"0.25\" />\n".format(x, y, 10, color))
f.write("</g>\n")
# layer blobs
# for i in range(0, rotation_pos.shape[0]):
# if found_map_positions[i][0] is ma.masked: