Repository navigation
Expand file tree
/
Copy pathGUI_detect.py
More file actions
1637 lines (1344 loc) · 68.9 KB
/
Copy pathGUI_detect.py
File metadata and controls
1637 lines (1344 loc) · 68.9 KB
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 argparse
import queue
import socket
import threading
import time
import tkinter as tk
from collections import Counter
from pathlib import Path
import cv2
import torch.backends.cudnn as cudnn
from PIL import Image, ImageTk
from numpy import random
import logic_tools
from CustomScrollBar import ScrollBar
from Step import Step
from logic_tools import *
from models.experimental import attempt_load
from shared import *
from utils.datasets import LoadStreams, LoadImages
from utils.general import check_img_size, check_imshow, non_max_suppression, apply_classifier, \
scale_coords, xyxy2xywh, set_logging, increment_path
from utils.plots import plot_one_box
from utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel
current_step = 0
procedure = []
gui = None
cv_queue = queue.Queue()
sensor_queue = queue.Queue()
detect_ready = threading.Event()
terminate = threading.Event()
sensor_in_use = threading.Event()
sensor_ready = threading.Event()
sensor_data_block = queue.Queue()
def detect(save_img=False):
global gui, cv_queue
source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, not opt.no_trace
save_img = not opt.nosave and not source.endswith('.txt') # save inference images
webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
('rtsp://', 'rtmp://', 'http://', 'https://'))
# Directories
save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
# Initialize
set_logging()
device = select_device(opt.device)
half = device.type != 'cpu' # half precision only supported on CUDA
# Load model
model = attempt_load(weights, map_location=device) # load FP32 model
stride = int(model.stride.max()) # model stride
imgsz = check_img_size(imgsz, s=stride) # check img_size
if trace:
model = TracedModel(model, device, opt.img_size)
if half:
model.half() # to FP16
# Second-stage classifier
classify = False
if classify:
modelc = load_classifier(name='resnet101', n=2) # initialize
modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
# Set Dataloader
vid_path, vid_writer = None, None
if webcam:
view_img = check_imshow()
cudnn.benchmark = True # set True to speed up constant image size inference
dataset = LoadStreams(source, img_size=imgsz, stride=stride)
else:
dataset = LoadImages(source, img_size=imgsz, stride=stride)
# Get names and colors
names = model.module.names if hasattr(model, 'module') else model.names
colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
# Run inference
if device.type != 'cpu':
model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
old_img_w = old_img_h = imgsz
old_img_b = 1
t0 = time.time()
for path, img, im0s, vid_cap in dataset:
img = torch.from_numpy(img).to(device)
img = img.half() if half else img.float() # uint8 to fp16/32
img /= 255.0 # 0 - 255 to 0.0 - 1.0
if img.ndimension() == 3:
img = img.unsqueeze(0)
# Warmup
if device.type != 'cpu' and (
old_img_b != img.shape[0] or old_img_h != img.shape[2] or old_img_w != img.shape[3]):
old_img_b = img.shape[0]
old_img_h = img.shape[2]
old_img_w = img.shape[3]
for i in range(3):
model(img, augment=opt.augment)[0]
# Inference
t1 = time_synchronized()
with torch.no_grad(): # Calculating gradients would cause a GPU memory leak
pred = model(img, augment=opt.augment)[0]
t2 = time_synchronized()
# Apply NMS
pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
t3 = time_synchronized()
# Apply Classifier
if classify:
pred = apply_classifier(pred, modelc, img, im0s)
# Process detections
temp = [None, None]
for i, det in enumerate(pred): # detections per image
if webcam: # batch_size >= 1
p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
else:
p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
p = Path(p) # to Path
save_path = str(save_dir / p.name) # img.jpg
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
if len(det):
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
# Print results
for c in det[:, -1].unique():
n = (det[:, -1] == c).sum() # detections per class
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
hand_count, hand_det = logic_tools.find_hands(det)
if hand_count == 2:
L_hand_det, R_hand_det = logic_tools.RL_hands(hand_det)
cv_queue.put(det)
# Write results
for *xyxy, conf, cls in reversed(det):
if save_txt: # Write to file
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
with open(txt_path + '.txt', 'a') as f:
f.write(('%g ' * len(line)).rstrip() % line + '\n')
if save_img or view_img: # Add bbox to image
if cls == 4 and hand_count == 2: # 4 is for hand (might need to change in future)
xyxy_list_tensor = torch.stack(xyxy) # convert type for comparison
if torch.all(xyxy_list_tensor == L_hand_det[:4]):
label = f"Left Hand {conf:.2f}"
plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
elif torch.all(xyxy_list_tensor == R_hand_det[:4]):
label = f"Right Hand {conf:.2f}"
plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
else:
label = f'{names[int(cls)]} {conf:.2f}'
plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
temp[i] = im0
# Print time (inference + NMS)
# print(f'{s}Done. ({(1E3 * (t2 - t1)):.1f}ms) Inference, ({(1E3 * (t3 - t2)):.1f}ms) NMS')
# Save results (image with detections)
if save_img:
if dataset.mode == 'image':
cv2.imwrite(save_path, im0)
print(f" The image with the result is saved in: {save_path}")
else: # 'video' or 'stream'
if vid_path != save_path: # new video
vid_path = save_path
if isinstance(vid_writer, cv2.VideoWriter):
vid_writer.release() # release previous video writer
if vid_cap: # video
fps = vid_cap.get(cv2.CAP_PROP_FPS)
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
else: # stream
fps, w, h = 30, im0.shape[1], im0.shape[0]
save_path += '.mp4'
vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
vid_writer.write(im0)
# allow GUI to set up properly before start (not needed on board)
# detect_ready.set()
if not detect_ready.is_set():
detect_ready.set()
time.sleep(1)
# Stream results
if view_img:
# only stack videos on webcams two inputs
if source.endswith('.txt'):
final = cv2.vconcat(temp)
else:
final = temp[0]
gui.set_frame(final)
cv2.waitKey(1) # 1 millisecond
if save_txt or save_img:
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
# print(f"Results saved to {save_dir}{s}")
print(f'Done. ({time.time() - t0:.3f}s)')
sample = 0
ewma_sd = 0 # ewma sensor data
sum_sd = 0
num_rot = 0
is_rotating = False
DEGREES_IN_ROTATION = 280 # threshold for rotation (i.e. how many degrees make up 1 rotation)
def sensor_detect():
"""
Sensor (is meant to calculate only CCW rotation)
"""
global sensor_in_use, terminate
while not terminate.is_set():
# if not using sensor tool, simply ignore data
if not sensor_in_use.is_set():
time.sleep(1)
else:
# print("sensor in use = ========x========================================")
data_dict = {}
global sensor_data_block, sensor_queue, sample, ewma_sd, sum_sd, num_rot, is_rotating
data_block = sensor_data_block.get()
for sensor in data_block:
readings = sensor.split()
key = readings[0]
if key == "Temp:":
key = "Temp"
values = readings[1]
else:
values = [float(val) for val in readings[1:] if not ":" in val]
data_dict[key] = values
angle_z = data_dict['Angle'][2]
# Read in + a lil EWMA
if sample == 0:
ewma_sd = angle_z * 1.4
else:
ewma_sd = 0.75 * ewma_sd + 0.25 * angle_z * 1.4 # 1.4 for calibration purposes
sum_sd_i = max(0, sum_sd + ewma_sd)
sample += 1
# Processing: calculates if it's rotating based on previous and current reading
is_rotating = (1 if is_rotating else -1) * 0.3 + sum_sd_i - sum_sd > 0.5
num_rot = max(num_rot, int(sum_sd / DEGREES_IN_ROTATION))
data = {
# 'sub diffx': sum_sd_i - sum_sd,
# 'avg_rot': sum_sd_i,
'rotating': is_rotating,
'degrees': sum_sd_i,
'num_rotations': num_rot,
'sample': sample
}
sum_sd = sum_sd_i
# take every 4th frame. FPS corresponds to stream FPS.
if not camera_sensor_frame_match(x=sample, sr=10, fps=30) or sample % 4 != 0: continue
sensor_queue.put(data)
time.sleep(0.1) # a bit delay to prevent thread dying
def decision_logic():
global procedure, current_step, gui, cv_queue
while True: # prevent calling before initialization
if gui is not None: break
"""
Decision making frame goes here: we're simply calling validate() on the current step. Each step has its
own `validate()` method that is defined at initialization of the procedure. The crux of decision logic is
stored in each step, since each step has different criteria (unless there's some other way to implement it)
(?) Methods that should be called here are 1) CV detect and 2) sensor detect.
:param data: a dict of CV data (bounding boxes) and sensor data. Or, evoke methods in main to get these data.
"""
# data['CV'] = blah blah
# data['sensor'] = blob blob
# data['lala'] = wawa
# TESTING ONLY: always validate to true after 10 seconds (lol)
# if procedure[current_step].validate(data):
# gui.mark_step_done(DONE)
# Currently validate function will not be used because of the code structure
# Each step has its own validate function however, the class itself cannot modify the validate function
# the validate method willb e implemented here hardcoded (at least for now...)
# initialize make step 1 to IN_PROGRESS
procedure[current_step].update_status(IN_PROGRESS)
# build substeps for step 1
gui.build_substeps(procedure[current_step])
# build tools_list for step 1
gui.build_tools(procedure[current_step])
# So basically run the validators sequentially when we revert to make sure we restart the validation properly
while not terminate.is_set():
step1_validator()
step2_validator()
step3_validator()
step4_validator()
step5_validator()
step6_validator()
step_runtime = step7_validator()
print(f"Step 7 runtime={step_runtime} secs")
# ===================== Step Logics ============================
def step1_validator():
# variables for trendline, must be initalize outside of steps
# Sub5
s3_prev_dist_Spindle = -math.inf
s3_trend_Spindle = logic_tools.Trendline.INITIALIZE
# Detections Expected: Left Hand, Right Hand, Spindle
sub_conditions = [False for i in range(5)]
while current_step == 0:
data = cv_queue.get()
num_class_detected = len(data)
# unneeded tools check (only need hands)
wanted_class = [SPINDLE, HAND]
gui.update_unwant_tools(data, wanted_class)
# SUB 0 : is there a hand?
if not sub_conditions[0]:
hand_count, hands_det = logic_tools.find_hands(data)
if hand_count >= 1:
gui.update_substep(0)
sub_conditions[0] = True
# SUB 1 : is there a spindle? (index = 7)
if not sub_conditions[1] and sub_conditions[0] == True:
spindle_count, spindle_det = logic_tools.find_class(data, SPINDLE)
if spindle_count == 1:
gui.update_substep(1)
sub_conditions[1] = True
# SUB 2 : are they overlapped? hand holding spindle?
if not sub_conditions[2] and sub_conditions[1] == True:
over_count = 0
if num_class_detected > 1:
over_count, over_det, over_dict = logic_tools.find_overlapping(data)
if over_count == 1:
single_overlap_pair = over_det[0]
# if the overlapping is between spindle and hand
if (single_overlap_pair[0][5] == SPINDLE and single_overlap_pair[1][5] == HAND) \
or (single_overlap_pair[0][5] == HAND and single_overlap_pair[1][5] == SPINDLE):
gui.update_substep(2)
sub_conditions[2] = True
# SUB 3 : leaving hand
if not sub_conditions[3] and sub_conditions[2] == True:
s3_curr_dist_Spindle = -1
if num_class_detected > 1:
hand_count, hands_det = logic_tools.find_hands(data)
over_count, over_det, over_dict = logic_tools.find_overlapping(data)
spindle_count, spindle_det = logic_tools.find_class(data, 7)
if hand_count == 1 and spindle_count == 1:
spindle_center = logic_tools.get_box_center(*spindle_det[0][:4])
hand_center = logic_tools.get_box_center(*hands_det[0][:4])
s3_curr_dist_Spindle = logic_tools.get_euclidean_distance(hand_center, spindle_center)
# Spindle Leaving Right Hand
if s3_curr_dist_Spindle > s3_prev_dist_Spindle:
s3_trend_Spindle = logic_tools.Trendline.INCREASING
elif s3_curr_dist_Spindle < s3_prev_dist_Spindle:
s3_trend_Spindle = logic_tools.Trendline.DECREASING
s3_prev_dist_Spindle = s3_curr_dist_Spindle
if num_class_detected == 1 and s3_trend_Spindle == logic_tools.Trendline.INCREASING:
gui.update_substep(3)
sub_conditions[3] = True
# SUB 4 : no overlap spingle left behind
if not sub_conditions[4] and sub_conditions[3] == True:
spindle_count, spindle_det = logic_tools.find_class(data, SPINDLE)
if spindle_count == 1 and num_class_detected == 1:
gui.update_substep(4)
sub_conditions[4] = True
if all(sub_conditions):
print("Step 1 Done")
gui.mark_step_done(DONE)
# print(f"Spindle: {spindle_count}, Hand: {hand_count}, Overlapping_Count: {over_count}, Overlapping_IOU: {iou}")
def step2_validator():
# Detections Expected: Left Hand, Right Hand, DoubleFlatBottomBracket, (Spindle)
# Both Hand hold Bracket
# Single Hand Tighten
sub_conditions = [False for i in range(9)]
while current_step == 1:
data = cv_queue.get()
num_class_detected = len(data)
wanted_class = [DOUBLEFLATS_BOTTOM_BRACKET, HAND, SPINDLE]
gui.update_unwant_tools(data, wanted_class)
# SUB 0 : is there a hand?
if not sub_conditions[0]:
hand_count, hands_det = logic_tools.find_hands(data)
if hand_count >= 1:
gui.update_substep(0)
sub_conditions[0] = True
# SUB 1 : is there a doubleflatbottombracket?
if not sub_conditions[1] and sub_conditions[0] == True:
double_flat_bb_count, _ = logic_tools.find_class(data, DOUBLEFLATS_BOTTOM_BRACKET)
if double_flat_bb_count == 1:
gui.update_substep(1)
sub_conditions[1] = True
# SUB 2 : is there a spindle?
if not sub_conditions[2] and sub_conditions[1] == True:
spindle_count, _ = logic_tools.find_class(data, SPINDLE)
if spindle_count == 1:
gui.update_substep(2)
sub_conditions[2] = True
# SUB 3: hand holding doubleflat bottom bracket
if not sub_conditions[3] and sub_conditions[2] == True:
hand_count, hand_det = logic_tools.find_class(data, HAND)
double_flat_bb_count, double_flat_bb_det = logic_tools.find_class(data, DOUBLEFLATS_BOTTOM_BRACKET)
for hand in hand_det:
overlapping, _ = logic_tools.is_overlapping(hand, double_flat_bb_det[0])
if overlapping:
gui.update_substep(3)
sub_conditions[3] = True
# SUB 4: bottom bracket completely covering spindle
if not sub_conditions[4] and sub_conditions[3] == True:
double_flat_bb_count, double_flat_bb_det = logic_tools.find_class(data, DOUBLEFLATS_BOTTOM_BRACKET)
spindle_count, spindle_det = logic_tools.find_class(data, SPINDLE)
if double_flat_bb_count and spindle_count:
double_flat_bb_det = double_flat_bb_det[0]
spindle_det = spindle_det[0]
complete_overlap = logic_tools.complete_overlap(double_flat_bb_det, spindle_det)
if complete_overlap:
gui.update_substep(4)
sub_conditions[4] = True
# SUB 5: right hand totally covering double flat bottom bracket
if not sub_conditions[5] and sub_conditions[4] == True:
hand_count, hand_det = logic_tools.find_class(data, HAND)
double_flat_bb_count, double_flat_bb_det = logic_tools.find_class(data, DOUBLEFLATS_BOTTOM_BRACKET)
if hand_count > 1:
_, R_hand = logic_tools.RL_hands(hand_det)
else:
R_hand = hand_det[0]
if double_flat_bb_count:
double_flat_bb_det = double_flat_bb_det[0]
complete_overlap = logic_tools.complete_overlap(R_hand, double_flat_bb_det)
if complete_overlap:
gui.update_substep(5)
sub_conditions[5] = True
# SUB 6: Hand is Out of Field
if not sub_conditions[6] and sub_conditions[5] == True:
hand_count, hand_det = logic_tools.find_class(data, HAND)
if hand_count == 0:
gui.update_substep(6)
sub_conditions[6] = True
# SUB 7: Reconfirm Doubleflatbottombracket is completely over spindle
if not sub_conditions[7] and sub_conditions[6] == True:
double_flat_bb_count, double_flat_bb_det = logic_tools.find_class(data, DOUBLEFLATS_BOTTOM_BRACKET)
spindle_count, spindle_det = logic_tools.find_class(data, SPINDLE)
if double_flat_bb_count and spindle_count:
double_flat_bb_det = double_flat_bb_det[0]
spindle_det = spindle_det[0]
complete_overlap = logic_tools.complete_overlap(double_flat_bb_det, spindle_det)
if complete_overlap:
gui.update_substep(7)
sub_conditions[7] = True
# SUB 8: Only Doubleflatbottombracket and spindle left behind
if not sub_conditions[8] and sub_conditions[7] == True:
double_flat_bb_count, double_flat_bb_det = logic_tools.find_class(data, DOUBLEFLATS_BOTTOM_BRACKET)
spindle_count, spindle_det = logic_tools.find_class(data, SPINDLE)
if num_class_detected == 2 and spindle_count == 1 and double_flat_bb_count == 1:
gui.update_substep(8)
sub_conditions[8] = True
# if spindle + bolt + hand overlap --> passed
# if spindle + bolt + hand location aroudn there in the middle = pass
# could add time duration for them
if all(sub_conditions):
print("Step 2 Done")
gui.mark_step_done(DONE)
def step3_validator():
# Detections Expected: Left Hand, Right Hand, Double-flats Wrench, (DoubleFlatBottomBracket), (Spindle)
s4_prev_wrench_xmin = math.inf
s4_prev_wrench_ymax = math.inf
s4_prev_wrench_ymin = math.inf
s4_turn_count = 0
s4_history = []
sub_conditions = [False for i in range(6)]
while current_step == 2:
data = cv_queue.get()
num_class_detected = len(data)
wanted_class = [DOUBLE_FLATS_WRENCH, DOUBLEFLATS_BOTTOM_BRACKET, HAND, SPINDLE]
gui.update_unwant_tools(data, wanted_class)
# find double flat wrench
if not sub_conditions[0]:
double_flat_wrench_count, _ = logic_tools.find_class(data, DOUBLE_FLATS_WRENCH)
if double_flat_wrench_count == 1:
gui.update_substep(0)
gui.update_tools(0)
sub_conditions[0] = True
# find hands
if not sub_conditions[1] and sub_conditions[0] == True:
hand_count, hands_det = logic_tools.find_hands(data)
if hand_count > 1:
gui.update_substep(1)
sub_conditions[1] = True
# overlap hands and doubleflatwrench
if not sub_conditions[2] and sub_conditions[1] == True:
hand_count, hand_det = logic_tools.find_class(data, HAND)
wrench_count, wrench_det = logic_tools.find_class(data, DOUBLE_FLATS_WRENCH)
for hand in hand_det:
overlapping, _ = logic_tools.is_overlapping(hand, wrench_det[0])
if overlapping:
gui.update_substep(2)
sub_conditions[2] = True
# complete overlap of wrench over doubleflatbracket
if not sub_conditions[3] and sub_conditions[2] == True:
double_flat_bb_count, double_flat_bb_det = logic_tools.find_class(data, DOUBLEFLATS_BOTTOM_BRACKET)
wrench_count, wrench_det = logic_tools.find_class(data, DOUBLE_FLATS_WRENCH)
if double_flat_bb_count == 1 and wrench_count == 1:
double_flat_bb_det = double_flat_bb_det[0]
wrench_det = wrench_det[0]
if double_flat_bb_count and wrench_count:
complete_overlap = logic_tools.complete_overlap(wrench_det, double_flat_bb_det)
if complete_overlap:
gui.update_substep(3)
sub_conditions[3] = True
# rotation detected and wrench completely over doubleflatbracket
if not sub_conditions[4] and sub_conditions[3] == True:
double_flat_bb_count, double_flat_bb_det = logic_tools.find_class(data, DOUBLEFLATS_BOTTOM_BRACKET)
wrench_count, wrench_det = logic_tools.find_class(data, DOUBLE_FLATS_WRENCH)
if double_flat_bb_count == 1 and wrench_count == 1:
double_flat_bb_det = double_flat_bb_det[0]
wrench_det = wrench_det[0]
if double_flat_bb_count and wrench_count:
complete_overlap = logic_tools.complete_overlap(wrench_det, double_flat_bb_det)
if complete_overlap:
# Note: in yolov7 higher y value means lower position in canvas
if ((wrench_det[0] < s4_prev_wrench_xmin + 50 and wrench_det[3] < s4_prev_wrench_ymax + 20) or
(wrench_det[0] > s4_prev_wrench_xmin + 50 and wrench_det[
1] < s4_prev_wrench_ymin + 20)):
s4_history.append("Turning")
if ((wrench_det[0] > s4_prev_wrench_xmin + 50 and wrench_det[3] > s4_prev_wrench_ymax + 20) or
(wrench_det[0] < s4_prev_wrench_xmin + 50 and wrench_det[
1] > s4_prev_wrench_ymin + 20)):
s4_history.append("Resetting")
temp_dict = dict(Counter(s4_history[-10:]))
if (temp_dict["Resetting"] > 3):
s4_history = []
s4_turn_count += 1
print(f"Finished Turn: {s4_turn_count}")
# use for turn calibrating
a = dict(Counter(s4_history))
# print(a)
s4_prev_wrench_xmin = wrench_det[0]
s4_prev_wrench_ymin = wrench_det[1]
s4_prev_wrench_ymax = wrench_det[3]
# Final turn didn't count
if wrench_count == 0 and a['Turning'] > 0:
s4_turn_count += 1
print(f"Finished Turn: {s4_turn_count}")
if s4_turn_count == 3:
gui.update_substep(4)
sub_conditions[4] = True
# hand is out of field
if not sub_conditions[5] and sub_conditions[4] == True:
hand_count, hand_det = logic_tools.find_class(data, HAND)
if hand_count == 0:
gui.update_substep(5)
sub_conditions[5] = True
# correct overlap increase/decrease
# correct wrench location or hand location
# time duration
if all(sub_conditions):
print("Step 3 Done")
gui.mark_step_done(DONE)
def step4_validator():
# Detections Expected: Left Hand, Right Hand, CrankArm, (DoubleFlatBottomBracket), (Spindle)
sub_conditions = [False for i in range(4)]
while current_step == 3:
data = cv_queue.get()
num_class_detected = len(data)
wanted_class = [CRANK_ARM, DOUBLEFLATS_BOTTOM_BRACKET, HAND, SPINDLE]
gui.update_unwant_tools(data, wanted_class)
# find crank arm
if not sub_conditions[0]:
double_flat_wrench_count, _ = logic_tools.find_class(data, CRANK_ARM)
if double_flat_wrench_count == 1:
gui.update_substep(0)
sub_conditions[0] = True
# find hand
if not sub_conditions[1] and sub_conditions[0] == True:
hand_count, hands_det = logic_tools.find_hands(data)
if hand_count > 1:
gui.update_substep(1)
sub_conditions[1] = True
# find correct overlap
if not sub_conditions[2] and sub_conditions[1] == True:
over_count, over_det, g = logic_tools.find_overlapping(data)
if over_count == 1:
single_overlap_pair = over_det[0]
# if the overlapping is between spindle and hand
if ((single_overlap_pair[0][5] == CRANK_ARM and single_overlap_pair[1][5] ==
HAND) or
(single_overlap_pair[0][5] == HAND and single_overlap_pair[1][5] ==
CRANK_ARM)):
gui.update_substep(2)
sub_conditions[2] = True
# correct location
# hand out of field
if not sub_conditions[3] and sub_conditions[2] == True:
hand_count, hand_det = logic_tools.find_class(data, HAND)
if hand_count == 0:
gui.update_substep(3)
sub_conditions[3] = True
# time duration
# correct increase/decrease
if all(sub_conditions):
print("Step 4 Done")
gui.mark_step_done(DONE)
def step5_validator():
# Detections Expected: Left Hand, Right Hand, Bolt, CrankArm
sub_conditions = [False for _ in range(5)]
bolt_time = 0
away_time = 0
while current_step == 4:
data = cv_queue.get()
num_class_detected = len(data)
wanted_class = [BOLT, CRANK_ARM, HAND]
gui.update_unwant_tools(data, wanted_class)
# SUB 0 : is there a hand?
if not sub_conditions[0]:
hand_count, hands_det = logic_tools.find_hands(data)
if hand_count:
# procedure[current_step].update_description(emoji.emojize("Found Hands 👍"))
gui.update_substep(0)
sub_conditions[0] = True
# ['found hands', 'found crank arm', 'screwing bolt into crank arm', 'screwed bolt into crank arm'']
# SUB 1 : is there a pedal wrench? (index = 7)
if not sub_conditions[1] and sub_conditions[0] == True:
crank_count, crank_det = logic_tools.find_class(data, 12)
if crank_count:
# procedure[current_step].update_description(u'Found crank arm👍')
gui.update_substep(1)
sub_conditions[1] = True
# Add rotating condition
# SUB 2 : are they overlapped? hand holding spindle?
over_count = 0
over_dict = {}
if num_class_detected > 1:
over_count, over_det, over_dict = logic_tools.find_overlapping(data)
# print(over_dict)
# SUB 3 : leaving right hand + increasing left hand
if not sub_conditions[3] and sub_conditions[1] == True:
hand_i_bolt = over_dict.get((4, 10)) or over_dict.get((10, 4))
crank_i_bolt = over_dict.get((12, 10)) or over_dict.get((10, 12))
if crank_i_bolt and hand_i_bolt:
if hand_i_bolt < 0.015 and crank_i_bolt < 0.015:
bolt_time += 1
if not sub_conditions[2]:
# procedure[current_step].update_description(u'Screwing bolt into crank arm...')
gui.update_substep(2)
sub_conditions[2] = True
if bolt_time > 30:
# procedure[current_step].update_description(u'Screwed bolt into crank arm')
gui.update_substep(3)
sub_conditions[3] = True
elif not sub_conditions[4] and sub_conditions[3]:
hand_i_bolt = over_dict.get((4, 10)) or over_dict.get((10, 4))
if not hand_i_bolt:
away_time += 1
if (away_time > 8) and not (over_dict.get((4, 12)) or over_dict.get((12, 4))):
if not (over_dict.get((4, 12)) or over_dict.get((12, 4))):
gui.update_substep(4)
sub_conditions[4] = True
if all(sub_conditions[0:5]):
print("Step 5 Done")
gui.mark_step_done(DONE)
def step6_validator():
pedal_time = 0
sub_conditions = [False for _ in range(7)]
while current_step == 5:
# ['found hands', 'found pedal', 'hand holding pedal', 'screwing pedal into crank', 'screwed pedal into crank']
data = cv_queue.get()
num_class_detected = len(data)
wanted_class = [HAND, PEDAL, PEDAL_LOCKING_WRENCH, CRANK_ARM, BOLT]
gui.update_unwant_tools(data, wanted_class)
# SUB 0 : is there a hand?
if not sub_conditions[0]:
hand_count, hands_det = logic_tools.find_hands(data)
if hand_count:
# procedure[current_step].update_description(emoji.emojize("Found Hands 👍"))
gui.update_substep(0)
sub_conditions[0] = True
# SUB 1 : is there a pedal wrench? (index = 7)
if not sub_conditions[1] and sub_conditions[0] == True:
ped_count, ped_det = logic_tools.find_class(data, 11)
if ped_count:
# procedure[current_step].update_description(u'Found pedal👍')
gui.update_substep(1)
sub_conditions[1] = True
# Add rotating condition
# SUB 2 : are they overlapped? hand holding spindle?
over_count = 0
over_dict = {}
if num_class_detected > 1:
over_count, over_det, over_dict = logic_tools.find_overlapping(data)
# print(over_dict)
# SUB 3 : leaving right hand + increasing left hand
if not sub_conditions[2] and sub_conditions[1] == True:
if over_dict.get((4, 11)) or over_dict.get((11, 4)):
# procedure[current_step].update_description(u'Hand holding pedal 👍')
gui.update_substep(2)
# print("Intersection of hand and pedal: ",over_dict.get((4,11)) or over_dict.get((11,4)))
sub_conditions[2] = True
if not sub_conditions[4] and sub_conditions[1] == True:
crank_i_pedal = over_dict.get((12, 11)) or over_dict.get((12, 11))
# crank_i_bolt = over_dict.get((12,10)) or over_dict.get((10,12))
if crank_i_pedal:
if crank_i_pedal < 0.05:
pedal_time += 1
if not sub_conditions[3]:
if pedal_time > 2:
# procedure[current_step].update_description(u'Screwing pedal into crank arm...')
gui.update_substep(3)
sub_conditions[3] = True
elif pedal_time > 45:
# procedure[current_step].update_description(u'Screwed pedal into crank arm')
gui.update_substep(4)
sub_conditions[4] = True
if sub_conditions[4] and not sub_conditions[5]:
hand_i_pedal = over_dict.get((4, 11)) or over_dict.get((4, 11))
if not hand_i_pedal:
gui.update_substep(5)
sub_conditions[5] = True
if all(sub_conditions[0:6]):
gui.mark_step_done(DONE)
def step7_validator():
"""
StepValidator for step 7: using pedal lockring wrench to install pedal
objects of interest in view:
- hand(s)
- pedal wrench
- crank arm
- pedal
- bolt
TODO: 1) does logic stop when override/revert button is clicked?
2) check for null in detection [0]
"""
# sanity check for current step
if current_step != 6:
return -1
# current_step = 6
# Detections Expected: Left Hand, Right Hand, Pedal Locking wrench, Pedal, CrankArm, Bolt
# a lil timer
start_time = time.time()
print(f"Started Step 7")
"""
A) Initial stage condition to be satisfied (i.e. condition for starting stage):
- pedal is in (proximity) of crank arm:
1) pedal intersects with crank arm
2) pedal bbox and crank bbox centers are within max + threshold from each other (???)
- bolt is in crank arm: bolt bbox is (mostly) fully within crank arm bbox (given camera is overhead)
Q: Do these conditions have to be constantly validated throughout the step?
"""
data = cv_queue.get()
wanted_class = [HAND, PEDAL, PEDAL_LOCKING_WRENCH, CRANK_ARM, BOLT]
gui.update_unwant_tools(data, wanted_class)
initial_stage_satisfied = False
condition_persistor = Persistor(frames=30, condition_name="Initial Stage")
while not initial_stage_satisfied:
t1 = time.time()
"""
TODO: don't just take the first reading lol
'proximity' might not be strict enough? (proximity + edge of crank arm?)
"""
data = cv_queue.get() # [[xyxy(4), conf(1), class(1)], ...]
# print(f"These are not the droids you're looking for.")
# if necessary objs do not exist (caveat: glitch/hidden for brief moment)
if len(data[data[:, 5] == PEDAL]) == 0 or len(data[data[:, 5] == CRANK_ARM]) == 0 or len(
data[data[:, 5] == BOLT]) == 0:
continue
# Taking the first of each class of interest found.
pedal = data[data[:, 5] == PEDAL][0]
crank_arm = data[data[:, 5] == CRANK_ARM][0]
bolt = data[data[:, 5] == BOLT][0]
# init condition 1: pedal in prox of crank arm;
pedal_crank_iou = bbox_iou(crank_arm[:4], pedal[:4])
bolt_crank_iou = bbox_iou(crank_arm[:4], bolt[:4])
# print(f"crank_arm={crank_arm}, pedal={pedal}, bolt={bolt}")
# print(f"bolt_crank={bbox_intersection(bolt, crank_arm)}/{bbox_area(bolt)}")
# print(f"pedal_crank={pedal_crank_iou}\n")
if pedal_crank_iou < 0.05 or pedal_crank_iou > 0.2 or bbox_intersection(bolt, crank_arm) + 0.001 < bbox_area(
bolt):
condition_persistor.reset()
continue
if condition_persistor.verify():
initial_stage_satisfied = True
# print(f"{time.time() - t1} seconds")
else:
condition_persistor.persist()
gui.update_substep(0) # substep 1 satisfied
# Check for Tool Existing
substeptwo_in_progress = True
while substeptwo_in_progress:
data = cv_queue.get()
# print(time.time(), data[:, 5])
# Check if there is a Pedal Locking Wrench
pedal_wrench, _ = logic_tools.find_class(data, PEDAL_LOCKING_WRENCH)
if pedal_wrench == 1:
gui.update_substep(1)
gui.update_tools(0)
substeptwo_in_progress = False
"""
B) In-progress conditions to be satisfied:
1. hand intersecting greatly with pedal wrench (for the duration of rotation being sensed/detected)
- this sub step is active as long as pedal wrench+hand combination is engaged with pedal
- rotation in bbox can be very roughly sort-of-ish detected using the center of the bbox;
but the rotation is not a smooth circle/ellipse
2. ?
Concerns:
- losing visual (use EWMA on 4 point of bbox to approximate expected location until next update? == tracking???)
- use last location? But what if obj is hidden for a long time?
(& differentiate between removed from frame vs hidden??????? this is so extra wtf)
"""
in_progress_stage_satisfied = False
num_rotations = 0
condition_persistor = Persistor(frames=10, condition_name="1 rotation")
pedal_wrench_loc_history = None
MIN_ROTATION = 3
global sensor_queue, sensor_in_use
while not in_progress_stage_satisfied:
# print("still running...")
data = cv_queue.get() # [[xyxy(4), conf(1), class(1)], ...]
# if necessary objs do not exist (caveat: glitch/hidden for brief moment)
if len(data[data[:, 5] == PEDAL_LOCKING_WRENCH]) == 0 or len(data[data[:, 5] == PEDAL]) == 0 or len(
data[data[:, 5] == HAND]) == 0:
continue
if not sensor_in_use.is_set(): sensor_in_use.set()
# print("Sensor set")
has_rotation_been_counted = False
pedal_count, pedal_det = logic_tools.find_class(data, PEDAL)
hand_count, hand_det = logic_tools.find_class(data, HAND)
pedal_wrench_count, pedal_wrench_det = logic_tools.find_class(data,PEDAL_LOCKING_WRENCH)
pedal = pedal_det[0]
hands = hand_det
pedal_wrench = pedal_wrench_det[0]
# HACK: I have to comment out the sensor code since its a blocking operation
# sensor_data = sensor_queue.get()
# print(sensor_data, "\n")
# print(pedal_wrench)
# Pure CV rotation tracking
# Basically I take the max X and Y distance from the pedal's center to the wrench's edge
# Then I determine if its in the NE or SW orientation and count rotations from there
pedal_center = logic_tools.get_box_center(pedal[0],pedal[1],pedal[2],pedal[3])
if abs(pedal_center[0] - pedal_wrench[0]) > abs(pedal_center[0] - pedal_wrench[2]):
pedal_wrench_x_distance = pedal_center[0] - pedal_wrench[0]
else:
pedal_wrench_x_distance = pedal_center[0] - pedal_wrench[2]
if abs(pedal_center[1] - pedal_wrench[1]) > abs(pedal_center[1] - pedal_wrench[3]):
pedal_wrench_y_distance = pedal_center[1] - pedal_wrench[1]
else:
pedal_wrench_y_distance = pedal_center[1] - pedal_wrench[3]
# print(pedal_wrench_x_distance, pedal_wrench_y_distance)
if pedal_wrench_x_distance > 0 and pedal_wrench_y_distance > 0:
if pedal_wrench_loc_history != "NE":
pedal_wrench_loc_history = "NE"
print("NE")
if pedal_wrench_x_distance < 0 and pedal_wrench_y_distance < 0:
if pedal_wrench_loc_history == "NE":
print("SW")
num_rotations += 1