-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_new_template.py
1956 lines (1610 loc) · 83.8 KB
/
main_new_template.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
from threading import Thread
from collections import deque
import json
import time
from tkinter import messagebox
from tkinter import Label, ttk
from tkinter import filedialog
import cv2
import os
import tkinter as tk
from PIL import Image, ImageTk
import analysis
import csv
import sys
import pandas as pd
#-----------------------------to do main
#indication of clothes
#dlouhy touch nezbarvi timeline
#timeline2 doesnt show yellow if touch starts in one zone and ends in let say 5 zones after it will higlight only two zones
#------------------------------to do features
#second display
#guide na zacatku
#analysis
#deleting confidential data
#indication of saving
#frame loading indication
#play button
#-----------------------------to do bugs
#loading second video doesnt work
#loading frames not showing
#-----------------------------to do optimizition
#pri drzeni sipky to prestane stihat
#saving doesnt have to happen for all the touches every time
#-----------------------------done
#move to specific frame
#optimize
#2x diagram size
#scroling
#7framu shift a button
#note different path
#2x zelena rozbije timeline
#novej diagram s hlavou
#pri skoku mimo buffer se nenacte nova fotka
#looking
#independent new looking
#ghost touch
class ClothApp:
def __init__(self, master, on_close_callback):
# Vytvoření nového okna pomocí Toplevel
self.top_level = tk.Toplevel(master)
self.top_level.title("Clothes App")
self.top_level.geometry("225x348") # Double the original dimensions for the window size
self.on_close_callback = on_close_callback
self.f = tk.Frame(self.top_level, bg='red')
self.f.grid(row=1, column=0, sticky="nsew")
self.dots = {}
self.img = Image.open("icons/diagram.png") # Upravte cestu k obrázku
self.img = self.img.resize((int(self.img.width*0.5), int(self.img.height*0.5)), Image.LANCZOS) # Resize the image to double the original dimensions
self.photo2 = ImageTk.PhotoImage(self.img)
self.canvas2 = tk.Canvas(self.f, width=self.img.width, height=self.img.height, bg='red') # Adjust canvas size
self.canvas2.pack()
self.canvas2.create_image(0, 0, anchor="nw", image=self.photo2)
self.canvas2.bind("<Button-1>", self.add_dot) # Pravé tlačítko pro přidání tečky
self.canvas2.bind("<Button-2>", self.remove_dot) # Prostřední tlačítko pro odstranění tečky
self.top_level.protocol("WM_DELETE_WINDOW", self.on_close)
def on_close(self):
# Zavolání callback funkce s daty teček při uzavření okna
self.on_close_callback(self.dots)
self.top_level.destroy() # Uzavření okna
def add_dot(self, event):
dot_id = self.canvas2.create_oval(event.x-5, event.y-5, event.x+5, event.y+5, fill="red")
self.dots[dot_id] = (event.x, event.y)
print("INFO: Clothes dots: ", self.dots)
def remove_dot(self, event):
closest_dot = self.canvas2.find_closest(event.x, event.y)[0]
if closest_dot in self.dots:
del self.dots[closest_dot]
self.canvas2.delete(closest_dot)
print("Dots:", self.dots)
class Video:
def __init__(self, video_path):
self.video_path = video_path
self.current_frame = 0 # Starting at frame 0
self.current_frame_zone = 0
self.number_frames_in_zone = 100
self.video_name = None
self.total_frames = self.get_total_frames()
self.number_zones = int(self.total_frames/self.number_frames_in_zone) + 1
self.frames_dir = None
self.data = {}
self.data_path_to_csv = None
self.dots = []
self.dataRH = {}
self.dataRH_path_to_csv = None
self.dataLH = {}
self.dataLH_path_to_csv = None
self.dataRL = {}
self.dataRL_path_to_csv = None
self.dataLL = {}
self.dataLL_path_to_csv = None
self.datalooking_path_to_csv = None
self.datalooking = {}
self.datalookingRH = {}
self.datalookingLH = {}
self.datalookingRL = {}
self.datalookingLL = {}
self.datalookingRH_path_to_csv = None
self.datalookingLH_path_to_csv = None
self.datalookingRL_path_to_csv = None
self.datalookingLL_path_to_csv = None
self.is_touchRH = False
self.is_touchLH = False
self.is_touchRL = False
self.is_touchLL = False
self.touch_to_next_zone = [False for _ in range(self.number_zones)]
self.last_green = [(10, 10),(5, 5),(50, 50)]
self.play = False
self.frame_rate = None
self.parameter_button1_state_dict = {}
self.parameter_button2_state_dict = {}
self.parameter_button3_state_dict = {}
self.dataNotes_path_to_csv = None
self.program_version = '4.0 new template'
self.parameter1_name = None
self.parameter2_name = None
self.parameter3_name = None
self.clothes_file_path = None
def get_total_frames(self):
cap = cv2.VideoCapture(self.video_path)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
cap.release()
#print("total_frame -1:",total_frames -1)
return total_frames -1
def get_frame(self, frame_number):
cap = cv2.VideoCapture(self.video_path)
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_number)
success, frame = cap.read()
cap.release()
if success:
return frame
else:
return None
class LabelingApp(tk.Tk):
def __init__(self):
super().__init__()
self.title('Labeling Application')
self.geometry('1200x1000')
self.protocol("WM_DELETE_WINDOW", self.on_close)
self.video = None
self.photo = None
self.pil_frame = None
self.current_dot_item_id = [None]
self.data_clothes = {}
self.touch = False
self.is_touch_timeline = False
self.color_start = "blue"
self.color_during = "yellow"
self.color_end = "red"
self.frame_cache = {}
self.image = None
self.diagram_size, self.minimal_touch_lenght = self.load_config()
self.img_buffer = {}
self.play = False
self.play_thread_on = False
# Create frames for video, timeline, and diagram
self.old_width = None
self.old_height = None
self.video_frame = tk.Frame(self, bg='gray')
self.timeline_frame = tk.Frame(self, bg='grey',height=50)
self.notes_file_path = None
self.progress = {}
self.frame_rate = None
#self.looking_dic = {}
#self.cat3_mp4looking= None
self.timeline2_canvas = tk.Canvas(self.timeline_frame, bg='lightgrey', height=30)
self.timeline2_canvas.pack(fill=tk.X, expand=True, pady=(0, 5)) # Add padding below the first timeline
self.timeline2_canvas.bind("<Button-1>", self.on_timeline2_click) # Bind click event
self.timeline_canvas = tk.Canvas(self.timeline_frame, bg='lightgrey', height=50)
self.timeline_canvas.pack(fill=tk.X, expand=True, pady=(10, 0)) # Add padding above the second timeline
self.timeline_canvas.bind("<Button-1>", self.on_timeline_click) # Bind click event
self.control_frame = tk.Frame(self, bg='lightgrey',height=100)
#self.control_frame_2 = tk.Frame(self, bg='red',height=100)
self.diagram_frame = tk.Frame(self, bg='lightgrey')
# Span across both columns
self.video_frame.grid(row=1, column=0, sticky="nsew")
self.timeline_frame.grid(row=2, column=0, sticky="ew")
self.control_frame.grid(row=0, column=0, columnspan=1, sticky="ew")
#self.control_frame_2.grid(row=0, column=0, columnspan=1, sticky="ew")
self.diagram_frame.grid(row=0, column=1, rowspan=3, sticky="ns")
# Configure the main window to make the video and timeline frames resizable
self.columnconfigure(0, weight=1)
self.rowconfigure(1, weight=1) # Video frame
self.rowconfigure(2, weight=0) # Timeline frame, adjust weight as needed
#self.timeline_canvas.bind("<Configure>", lambda event: self.draw_timeline())
#self.timeline2_canvas.bind("<Configure>", lambda event: self.draw_timeline2())
# Initialize GUI components for each section
self.init_controls()
self.init_video()
self.init_timeline()
image_path = "icons/diagram0.png"
img = Image.open(image_path)
self.photo = ImageTk.PhotoImage(img)
if self.diagram_size == "large":
scale = 1
else:
scale = 0.5
self.diagram_canvas = tk.Canvas(self.diagram_frame, bg='lightgrey', width=int(450*scale), height=int(696*scale))
self.diagram_canvas.pack(padx=10, pady=10)
self.diagram_canvas.create_image(0, 0, anchor="nw", image=self.photo)
self.diagram_canvas.bind("<Button-3>",lambda event: self.on_diagram_click(event,right = False))
self.diagram_canvas.bind("<Button-1>",lambda event: self.on_diagram_click(event,right = True))
self.diagram_canvas.bind("<Button-2>", self.on_middle_click)
self.bind("<Right>", lambda event: self.next_frame(1))
self.bind("<Left>", lambda event: self.next_frame(-1))
self.bind("<Shift-Right>", lambda event: self.next_frame(7))
self.bind("<Shift-Left>", lambda event: self.next_frame(-7))
self.bind("<MouseWheel>", self.on_mouse_wheel) # Windows
self.video_frame.bind('<Configure>', self.on_resize)
self.init_diagram()
self.background_thread = Thread(target=self.background_update)
self.background_thread.daemon = True
#self.periodic_call()
def on_resize(self, event):
# Function to handle resize events
print("INFO: Resized to {}x{}".format(event.width, event.height))
self.img_buffer.clear()
if self.video:
self.display_first_frame()
# Add your code here to clear and reload the image buffer
def background_update(self, frame_number=None):
while True:
time.sleep(0.02)
#print("buffer lenght = ",len(self.img_buffer))
if self.video is not None:
#print("video")
frame_number = self.video.current_frame
if frame_number < 0:
print("ERROR: Frame number cannot be negative")
return
if frame_number > self.video.total_frames:
print("ERROR: Frame number cannot be bigger than max number of frames")
return
# Load and buffer frames from 10 frames before to 10 frames after the current frame
start_frame = max(0, frame_number - 50) # Ensure we do not go below frame 0
end_frame = min(self.video.total_frames, frame_number + 100) # Ensure we do not go beyond the last frame
#current frame:
if frame_number not in self.img_buffer:
frame_path = os.path.join(self.video.frames_dir, f"frame{frame_number}.jpg")
try:
img = Image.open(frame_path)
img = self.resize_frame(img)
photo_img = ImageTk.PhotoImage(img)
self.img_buffer[frame_number] = photo_img # Store the image in the buffer
print(f"INFO: Loading current frame {frame_number}")
self.display_first_frame()
except Exception as e:
print(f"ERROR: Opening or processing frame {i}: {str(e)}")
continue
for i in range(frame_number, end_frame + 1):
if i not in self.img_buffer: # Check if frame is already buffered
frame_path = os.path.join(self.video.frames_dir, f"frame{i}.jpg")
try:
img = Image.open(frame_path)
img = self.resize_frame(img)
photo_img = ImageTk.PhotoImage(img)
self.img_buffer[i] = photo_img # Store the image in the buffer
#print(f"Loading frame {i}")
except Exception as e:
print(f"ERROR: Opening or processing frame {i}: {str(e)}")
continue
for i in range(frame_number, start_frame-1, -1):
if i not in self.img_buffer: # Check if frame is already buffered
frame_path = os.path.join(self.video.frames_dir, f"frame{i}.jpg")
try:
img = Image.open(frame_path)
img = self.resize_frame(img)
photo_img = ImageTk.PhotoImage(img)
self.img_buffer[i] = photo_img # Store the image in the buffer
#print(f"Loading frame {i}")
except Exception as e:
print(f"ERROR: Opening or processing frame {i}: {str(e)}")
continue
# Clean up the buffer to hold only the 20 relevant frames
current_frame = self.video.current_frame
buffer_range = 200
# Define the range of frames you want to keep in the buffer
start_frame = current_frame - buffer_range
end_frame = current_frame + buffer_range
# Identify keys (frames) that are outside the buffer range
keys_to_remove = [k for k in self.img_buffer if k < start_frame or k > end_frame]
# Remove the identified frames from the buffer
for k in keys_to_remove:
del self.img_buffer[k]
#print("INFO: Deleting frame number: ",k)
def load_paramter_name(self):
with open('config.json', 'r') as file:
config = json.load(file)
parameter1 = config.get('parameter1', 'Parameter 1') # Default to 'medium' if not specified
parameter2 = config.get('parameter2', 'Parameter 2') # Default to 'medium' if not specified
parameter3 = config.get('parameter3', 'Parameter 3') # Default to 'medium' if not specified
self.video.parameter1_name = parameter1
self.video.parameter2_name = parameter2
self.video.parameter3_name = parameter3
self.par1_btn.config(text=parameter1)
self.par2_btn.config(text=parameter2)
self.par3_btn.config(text=parameter3)
self.par1_btn.config(text=f"{parameter1}")
self.par2_btn.config(text=f"{parameter2}")
self.par3_btn.config(text=f"{parameter3}")
def load_config(self):
with open('config.json', 'r') as file:
config = json.load(file)
diagram_size = config.get('diagram_size', 'small') # Default to 'medium' if not specified
minimal_touch_lenght = config.get('minimal_touch_lenght', '280')
print("INFO: Loaded diagram size:", diagram_size)
return diagram_size, minimal_touch_lenght
#diagram
def on_mouse_wheel(self, event):
if event.delta > 0 or event.num == 4: # Scrolling up
self.next_frame(-1)
elif event.delta < 0 or event.num == 5: # Scrolling down
self.next_frame(1)
def on_middle_click(self, event):
# Get the currently selected limb data dictionary based on the option selected
limb_key = f'data{self.option_var_1.get()}'
limb_data = getattr(self.video, limb_key, {})
scale = 1 if self.diagram_size == "large" else 0.5
# Current frame to check
current_frame = self.video.current_frame
# Check if there are coordinates for the current frame
if current_frame in limb_data:
details = limb_data[current_frame]
closest_distance = float('inf')
closest_index = None
# Iterate through coordinates in the current frame to find the closest point
for index, (x, y) in enumerate(details['xy']):
distance = ((x*scale - event.x)**2 + (y*scale - event.y)**2)**0.5
if distance <= 20 and distance < closest_distance:
closest_distance = distance
closest_index = index
# Delete the closest point if a suitable one was found
if closest_index is not None:
del details['xy'][closest_index] # Remove the coordinate from the list
# If there are no coordinates left for the frame, remove the frame entry
if not details['xy']:
del limb_data[current_frame]
# Optional: Update the canvas or UI to reflect the change3
# This might involve re-drawing the frame or adjusting UI elements
print(f"INFO: Deleted point {closest_index} from frame {current_frame}")
def on_diagram_click(self, event,right):
if right:
onset = "On"
else:
onset = "Off"
#self.video.last_green = [None, None]
x_pos, y_pos = event.x, event.y
scale = 1 if self.diagram_size == "large" else 2
x_pos *= scale
y_pos *= scale
zone_results = self.find_image_with_white_pixel(x_pos, y_pos)
print("INFO: Zone:",zone_results)
#zones = ', '.join([result[0] for result in zone_results if result])
print(f"INFO: Click on diagram at: x={x_pos}, y={y_pos}")
current_frame = self.video.current_frame
option = self.option_var_1.get()
target_attr = f"data{option}" if hasattr(self.video, f"data{option}") else "data"
target_data = getattr(self.video, target_attr, {})
print(f"INFO: Writing to {option} ...")
setattr(self.video, f"is_touch{option}", True)
if current_frame in target_data and 'xy' in target_data[current_frame]:
target_data[current_frame]['xy'].append((x_pos, y_pos))
target_data[current_frame]['Zone'].append(zone_results[0])
else:
target_data[current_frame] = {
'xy': [(x_pos, y_pos)],
'Onset': onset,
'Bodypart': option,
'Look': "No",
'Zone':zone_results
}
def find_last_green(self,data):
#print("data to find last green dot:",data)
keys = sorted(data.keys(), reverse=True) # Sort keys in descending order
start = self.video.current_frame
for key in keys:
if key <= start: # Only consider keys <= start
if data[key]['Onset'] == 'Off':
#print('last onset is Off')
self.video.last_green = [(None, None)]
return None
elif data[key]['Onset'] == 'On':
#print('last onset is On')
xy = data[key]['xy'][-1]
#print("INFO: xy last data: ",data[key]['xy'])
x = xy[0]
y = xy[1]
self.video.last_green = data[key]['xy']
return None
self.video.last_green = [(None, None)]
return None # Return None if no match is found
def on_radio_click(self):
#print("changing higlight")
touch = False
if self.option_var_1.get() == "RH":
image_path = "icons/RH_new_template.png"
if self.video:
touch = self.video.is_touchRH
elif self.option_var_1.get() == "LH":
if self.video:
touch = self.video.is_touchLH
image_path = "icons/LH_new_template.png"
elif self.option_var_1.get() == "RL":
if self.video:
touch = self.video.is_touchRL
image_path = "icons/RL_new_template.png"
elif self.option_var_1.get() == "LL":
if self.video:
touch = self.video.is_touchLL
image_path = "icons/LL_new_template.png"
#self.bool_var = touch
#self.display_text_var.set("Touch" if self.bool_var else "No Touch")
img = Image.open(image_path)
if self.diagram_size == "large":
scale = 1
else:
scale = 0.5
img = img.resize((int(img.width * scale),int(img.height * scale)), Image.LANCZOS)
self.photo = ImageTk.PhotoImage(img)
self.diagram_canvas.create_image(0, 0, anchor="nw", image=self.photo)
self.draw_timeline()
self.draw_timeline2()
def periodic_print_dot(self):
# Nejprve odstranit všechny předchozí body z plátna
self.diagram_canvas.delete("all") # Odstraní vše z plátna, můžete chtít odstranit jen specifické body
self.on_radio_click()
self.color_looking()
dot_size = 5
#self.draw_eyes()
if self.diagram_size == "large":
scale = 1
else:
scale = 0.5
if self.video and hasattr(self.video, 'data'):
if self.option_var_1.get() == "RH":
data = self.video.dataRH
elif self.option_var_1.get() == "LH":
data = self.video.dataLH
elif self.option_var_1.get() == "RL":
data = self.video.dataRL
elif self.option_var_1.get() == "LL":
data = self.video.dataLL
self.find_last_green(data)
frame_data = data.get(self.video.current_frame, {})
if 'xy' in frame_data:
for x, y in frame_data['xy']:
onset = frame_data.get('Onset', "Off")
if onset == "On":
color = 'green'
else:
color = 'red'
# Vytvoření bodu pro každou dvojici souřadnic
self.diagram_canvas.create_oval(x*scale - dot_size, y*scale - dot_size, x*scale + dot_size, y*scale + dot_size, fill=color)
#dot_size = 15
#self.diagram_canvas.create_oval(x - dot_size, y - dot_size, x + dot_size, y + dot_size, outline=color, fill='', width=5)
#last dot
#print("Last_green:",self.video.last_green)
array_xy = self.video.last_green
#print("INFO: Array_xy:",array_xy)
for i in range(len(array_xy)):
x_last, y_last = array_xy[i]
if x_last != None:
self.diagram_canvas.create_oval(x_last*scale - dot_size, y_last*scale - dot_size, x_last*scale + dot_size, y_last*scale + dot_size, outline='green', fill='')
# Periodicky volat tuto funkci
self.after(300, self.periodic_print_dot)
def periodic_print_dot_thread(self):
# Nejprve odstranit všechny předchozí body z plátna
while True:
self.diagram_canvas.delete("all") # Odstraní vše z plátna, můžete chtít odstranit jen specifické body
self.on_radio_click()
self.color_looking()
dot_size = 5
#self.draw_eyes()
if self.diagram_size == "large":
scale = 1
else:
scale = 0.5
if self.video and hasattr(self.video, 'data'):
if self.option_var_1.get() == "RH":
data = self.video.dataRH
elif self.option_var_1.get() == "LH":
data = self.video.dataLH
elif self.option_var_1.get() == "RL":
data = self.video.dataRL
elif self.option_var_1.get() == "LL":
data = self.video.dataLL
self.find_last_green(data)
frame_data = data.get(self.video.current_frame, {})
if 'xy' in frame_data:
for x, y in frame_data['xy']:
onset = frame_data.get('Onset', "Off")
if onset == "On":
color = 'green'
else:
color = 'red'
# Vytvoření bodu pro každou dvojici souřadnic
self.diagram_canvas.create_oval(x*scale - dot_size, y*scale - dot_size, x*scale + dot_size, y*scale + dot_size, fill=color)
#dot_size = 15
#self.diagram_canvas.create_oval(x - dot_size, y - dot_size, x + dot_size, y + dot_size, outline=color, fill='', width=5)
#last dot
#print("Last_green:",self.video.last_green)
x_last, y_last = self.video.last_green
if x_last != None:
self.diagram_canvas.create_oval(x_last*scale - dot_size, y_last*scale - dot_size, x_last*scale + dot_size, y_last*scale + dot_size, outline='green', fill='')
# Periodicky volat tuto funkci
time.sleep(0.5)
def draw_eyes(self):
#print("drawing eyes")
x1 = 152/2
y1 = 129/2
x2 = 215/2
y2 = 129/2
dot_size = 5 # Velikost bodu můžete upravit podle potřeby
# Vytvořit "dot" jako malý kruh (oval) na souřadnicích x, y
if self.option_var_2.get() == 'L':
color = self.color_during
elif self.option_var_2.get() == 'NL':
color = 'black'
elif self.option_var_2.get() == 'DNK':
color = 'grey'
self.diagram_canvas.create_oval(x1 - dot_size, y1 - dot_size, x1 + dot_size, y1 + dot_size, fill=color)
self.diagram_canvas.create_oval(x2 - dot_size, y2 - dot_size, x2 + dot_size, y2 + dot_size, fill=color)
def find_image_with_white_pixel(self, x, y):
# List to hold the names of the images where the pixel is white
x = int(x)
y = int(y)
directory = "icons/zones3_new_template"
images_with_white_pixel = []
# Iterate over all files in the given directory
for filename in os.listdir(directory):
# Construct full file path
file_path = os.path.join(directory, filename)
# Ensure file is an image
if os.path.isfile(file_path) and file_path.endswith(('.png', '.jpg', '.jpeg')):
# Read image in grayscale
image = cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)
# Check if the image was loaded correctly
if image is None:
continue
# Check if the pixel at (x, y) is white
if image[y, x] == 0:
images_with_white_pixel.append(filename.rsplit('.', 1)[0])
#print("zone:", images_with_white_pixel)
return images_with_white_pixel
return ['NN']
#timeline
def on_timeline_click(self, event):
if self.video and self.video.total_frames > 0:
click_position = event.x
canvas_width = self.timeline_canvas.winfo_width()
frame_number = int(click_position / canvas_width * self.video.number_frames_in_zone)
if self.video.total_frames >= frame_number+self.video.number_frames_in_zone*self.video.current_frame_zone:
self.video.current_frame = frame_number+self.video.number_frames_in_zone*self.video.current_frame_zone
self.display_first_frame()
else:
print("ERROR: Frame Number")
def on_timeline2_click(self,event):
if self.video and self.video.total_frames > 0:
click_position = event.x
canvas_width = self.timeline2_canvas.winfo_width()
frame_number = int(click_position / canvas_width * self.video.number_zones)
if frame_number < self.video.current_frame_zone:
self.touch = False
self.video.current_frame_zone = frame_number
print("INFO: Current zone: ",self.video.current_frame_zone)
self.video.current_frame = self.video.number_frames_in_zone*self.video.current_frame_zone
self.display_first_frame()
#self.display_first_frame(frame_number)
def draw_timeline2(self):
self.timeline2_canvas.delete("all") # Clear existing drawings
if self.video and self.video.total_frames > 0:
canvas_width = self.timeline2_canvas.winfo_width()
sector_width = canvas_width / self.video.number_zones
# Assume `self.video.zone_touches` is a list where each index represents a zone and the value is a boolean indicating if a touch occurred.
# This list needs to be calculated or updated elsewhere in your code based on actual touch data.
for frame in range(self.video.number_zones):
left = frame * sector_width
right = left + sector_width
top = 0
bottom = 100
# Check if there is at least one touch in the current frame zone
has_touch = self.check_zone_for_touch(frame) # This function needs to be defined or replace this with your logic
if frame == self.video.current_frame_zone:
fill_color = 'blue'
elif has_touch:
fill_color = self.color_during
else:
fill_color = 'gray'
self.timeline2_canvas.create_rectangle(left, top, right, bottom, fill=fill_color, outline='black')
def check_zone_for_touch(self, zone_index):
# Dynamically calculate the number of frames per zone if not predefined
frames_per_zone = 100
# Calculate the frame range for the given zone
start_frame = zone_index * frames_per_zone
end_frame = (zone_index + 1) * frames_per_zone
# Retrieve the limb data based on the currently selected limb
selected_limb_key = f'data{self.option_var_1.get()}'
limb_data = getattr(self.video, selected_limb_key, {})
# Check for 'On' touch data within this range
return any(details.get('Onset') in {'On', 'Off'} for frame_idx, details in limb_data.items()
if start_frame <= frame_idx < end_frame)
def draw_timeline(self):
self.timeline_canvas.delete("all") # Clear existing drawings
if not (self.video and self.video.total_frames > 0):
return
canvas_width = self.timeline_canvas.winfo_width()
sector_width = canvas_width / self.video.number_frames_in_zone
offset = self.video.number_frames_in_zone * self.video.current_frame_zone
# Determine the data source based on option
data_source = {
'RH': self.video.dataRH,
'LH': self.video.dataLH,
'RL': self.video.dataRL,
'LL': self.video.dataLL
}
data = data_source.get(self.option_var_1.get(), self.video.data)
# Initialize variables
top = 0
bottom = 100
self.is_touch_timeline = False if self.video.current_frame_zone == 0 else self.video.touch_to_next_zone[self.video.current_frame_zone]
# Function to determine color based on data presence and type
def get_color(frame_idx, data):
if frame_idx > self.video.total_frames:
return 'black'
details = data.get(frame_idx, {})
array = details.get('xy', (None, None))
# Check if array is None or if it doesn't contain at least one element
if array is None or not array:
return self.color_during if self.is_touch_timeline else 'grey'
# Ensure the first element of array is not None and is subscriptable
if len(array) >= 1 and array[0] and array[0][0] is not None:
if details.get('Onset') == 'On':
self.is_touch_timeline = True
return 'green'
else:
self.is_touch_timeline = False
return 'red'
else:
return self.color_during if self.is_touch_timeline else 'grey'
# Draw each frame in the timeline
for frame in range(self.video.number_frames_in_zone):
left = frame * sector_width
right = left + sector_width
frame_offset = frame + offset
color = get_color(frame_offset, data)
self.timeline_canvas.create_rectangle(left, top, right, bottom, fill=color, outline='black')
# Special case for the current frame
if frame_offset == self.video.current_frame:
self.timeline_canvas.create_rectangle(left, top, right, bottom, fill='blue', outline='black')
# Check if the zone ends with a touch and safely update the list
if frame == self.video.number_frames_in_zone - 1:
if self.video.current_frame_zone + 1 < len(self.video.touch_to_next_zone):
self.video.touch_to_next_zone[self.video.current_frame_zone + 1] = (color == self.color_during)
elif self.video.current_frame_zone + 1 == len(self.video.touch_to_next_zone): # Safely extend the list if at the end
self.video.touch_to_next_zone.append(color == self.color_during)
def update_frame_counter(self):
if self.video:
current_frame_text = f"{self.video.current_frame} / {self.video.total_frames}"
self.frame_counter_label.config(text=current_frame_text)
else:
self.frame_counter_label.config(text="0 / 0")
self.video.current_frame_zone = int(self.video.current_frame/self.video.number_frames_in_zone)
#self.draw_timeline2()
#self.update_diagram()
def display_first_frame(self, frame_number=None):
#self.background_thread.run()
if frame_number is None:
frame_number = self.video.current_frame
else:
self.video.current_frame = frame_number
if frame_number < 0:
print("ERROR: Frame number cannot be negative.")
return
if frame_number > self.video.total_frames:
print("ERROR: Frame number cannot be bigger than the maximum number of frames.")
return
# Check if the frame is already in the buffer
if frame_number in self.img_buffer:
photo_img = self.img_buffer[frame_number]
if hasattr(self, 'frame_label') and self.frame_label:
self.frame_label.configure(image=photo_img)
else:
self.frame_label = tk.Label(self.video_frame, image=photo_img)
self.frame_label.pack(expand=True)
self.loading_label.config(text="Buffer Loaded", bg='green')
self.image = photo_img # Keep a reference to prevent garbage collection
else:
print("INFO: Frame not in buffer. You may need to wait or trigger a buffer update.")
self.loading_label.config(text="Buffer Loading", bg='red')
#self.background_thread.run()
#self.display_first_frame()
#rame = cv2.imread(first_frame_path)
#if frame is not None:
# Convert the frame to PIL format for resizing
#pil_frame = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
#self.pil_frame = pil_frame
# Resize the frame to fit the display area
#display_width = self.video_frame.winfo_width()
#display_height = self.video_frame.winfo_height()
#print("display_width:",display_width)
#print("display_height:",display_height)
#resized_frame = self.resize_frame()
# Convert back to ImageTk format
#frame_image = ImageTk.PhotoImage(image=resized_frame)
#if hasattr(self, 'frame_label'):
#self.frame_label.configure(image=frame_image)
#else:
#self.frame_label = tk.Label(self.video_frame, image=frame_image)
#self.frame_label.pack(expand=True)
#self.frame_label.image = frame_image # Keep a reference!
#else:
# print(f"Error loading frame {frame_number}.")
self.update_frame_counter()
#self.draw_timeline()
#self.draw_timeline2()
def resize_frame(self, img):
# Get current dimensions of the video frame for resizing
display_width = self.video_frame.winfo_width()
display_height = self.video_frame.winfo_height()
# Calculate the new size maintaining the aspect ratio
original_width, original_height = img.size
aspect_ratio = original_width / original_height
if display_width / display_height > aspect_ratio:
new_width = int(display_height * aspect_ratio)
new_height = display_height
else:
new_width = display_width
new_height = int(display_width / aspect_ratio)
# Resize the image using high-quality downsampling
self.old_width = new_width
self.old_height = new_height
resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
#if img == resized_img:
#print("no differenc in resizing")
#else:
#print("resizing")
return resized_img
def show_frame(self):
pass
def next_frame(self,number_of_frames):
#self.option_var_2.set("DNK")
#number of frames is: -10,-1,1,10
if self.video != None:
if number_of_frames > 0:
# Implement what happens when 'Next Frame' is clicked
if self.video.current_frame+number_of_frames > self.video.total_frames:
self.video.current_frame = self.video.total_frames
else:
self.video.current_frame = self.video.current_frame+number_of_frames
#self.update_diagram()
#print("Go next for:",number_of_frames)
self.display_first_frame()
self.draw_timeline()
self.draw_timeline2()
elif number_of_frames < 0:
if self.video.current_frame+number_of_frames < 0:
self.video.current_frame = 0
else:
self.video.current_frame = self.video.current_frame+number_of_frames
#print("Go back for:",number_of_frames)
self.display_first_frame()
self.draw_timeline()
self.draw_timeline2()
else:
print("ERROR: Wrong number of frames.")
#looking_data = self.get_looking_data_for_frame(self.video.current_frame)
#self.option_var_2.set(looking_data)
else:
print("ERROR: Video = None")
#if self.option_var_2.get() == "L" or self.option_var_2.get() == "NL":
#self.save_looking()
def color_looking(self):
if self.video is not None:
# Reset button colors
self.do_not_know_btn.config(bg='lightgray')
self.not_looking_btn.config(bg='lightgray')
self.looking_btn.config(bg='lightgray')
# Get the dictionary based on self.option_var_1.get()
option_var = self.option_var_1.get() # This gets "RH", "LH", "RL", or "LL"
attribute_name = f"datalooking{option_var}" # Create the attribute name
# Check if the attribute exists in self.video
if hasattr(self.video, attribute_name):
data_dict = getattr(self.video, attribute_name)
# Now, use this dictionary for timeline coloring
if self.video.current_frame in data_dict:
details = data_dict.get(self.video.current_frame, {})
look = details.get('Look', '')
if look == "DNK":
self.do_not_know_btn.config(bg='green')
elif look == "L":
self.looking_btn.config(bg='green')
elif look == "NL":
self.not_looking_btn.config(bg='green')
self.update_button_colors()
def update_button_colors(self):
"""Periodically update button colors based on the current state in the dictionaries."""
# Dictionary mapping parameter numbers to their corresponding state dictionaries
parameter_dicts = {
1: self.video.parameter_button1_state_dict,
2: self.video.parameter_button2_state_dict,
3: self.video.parameter_button3_state_dict,
}
# Dictionary mapping parameter numbers to their corresponding buttons
parameter_buttons = {
1: self.par1_btn,
2: self.par2_btn,
3: self.par3_btn,
}
# Get the current frame (key)
key = self.video.current_frame
# Iterate over each parameter number and corresponding button
for param_num, param_dict in parameter_dicts.items():
# Get the current state for this parameter
current_state = param_dict.get(key, None)
# Update the corresponding button's color based on its state
if current_state is None:
parameter_buttons[param_num].config(bg='lightgrey') # Default color
elif current_state == "ON":
parameter_buttons[param_num].config(bg='green') # Button is ON
elif current_state == "OFF":
parameter_buttons[param_num].config(bg='red') # Button is OFF
# Optionally, you can schedule this function to be called periodically
# Example: self.root.after(1000, self.update_button_colors)
def parameter_dic_insert(self, parameter):
"""Toggle the state of the button between 'ON', 'OFF', and None dynamically for any parameter."""
# Dictionary mapping parameter numbers to their corresponding state dictionaries
parameter_dicts = {
1: self.video.parameter_button1_state_dict,
2: self.video.parameter_button2_state_dict,
3: self.video.parameter_button3_state_dict,
}
# Dictionary mapping parameter numbers to their corresponding buttons (if needed)
parameter_buttons = {
1: self.par1_btn,
2: self.par2_btn,
3: self.par3_btn,
}
# Retrieve the current frame (key)
key = self.video.current_frame
# Get the state dictionary for the given parameter
current_dict = parameter_dicts.get(parameter)
# Get the current state for the given key (default is None)
current_state = current_dict.get(key, None)