forked from kitovyj/ratrack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
821 lines (603 loc) · 35.9 KB
/
main.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
import sys
import numpy as np
import cv2
import math
import threading
import Queue
import os
import Tkinter as Tk
import ttk
import tkFileDialog
import tkMessageBox
from PIL import Image, ImageTk
from tracking import *
from geometry import *
from analyzers.intruder import *
from analyzers.evelien import *
from gui_tools import *
import config_serialization
from tracker_configurator import *
# tkinter layout management : http://zetcode.com/gui/tkinter/layout/
def calculate_scale_factor(src_width, src_height, dst_width, dst_height):
k = float(src_width) / src_height
if k > float(dst_width) / dst_height:
f = float(dst_width) / src_width
return (f, 0, (dst_height - dst_width / k) / 2)
else:
f = float(dst_height) / src_height
return (f, (dst_width - dst_height * k) / 2, 0)
def fit_image(image, width, height):
rows, cols = image.shape[:2]
k = float(cols) / rows
if k > float(width) / height:
cols = width
rows = max(1, cols / k)
else:
rows = height
cols = max(1, rows * k)
return cv2.resize(image, (int(cols), int(rows)))
class TextBoxLogger:
def __init__(self, text_box):
self.text_box = text_box
def log(self, message):
self.text_box.insert(Tk.END, message + '\n')
self.text_box.yview(Tk.END)
class QueueLogger:
def __init__(self, queue):
self.queue = queue
def log(self, message):
self.queue.put(message)
class Gui:
# possible states definitions
gs_no_video_selected = 1
gs_not_started = 2
gs_running = 3
gs_paused = 4
gs_adding_animal = 5
state = gs_no_video_selected
tracker_messages_queue = Queue.Queue(200)
tracking_flow = Queue.Queue(20)
time_to_stop = threading.Event()
next_frame_semaphore = threading.Event()
run_tracking_semaphore = threading.Event()
current_frame_number = 0
current_animal_positions = []
tracking_thread = 0
#video_file_name = 'videotest.avi'
#c:\radboud\ratrack\videos\2014-03-22_20-57-44.avi
#video_file_name = 'c:/radboud/ratrack/videos/2014-03-22_20-57-44.avi'
#video_file_name = 'c:/radboud/ratrack/videos/evelien/Peppie_LM5min_19052016_.avi'
video_file_name = 'c:/radboud/ratrack/videos2014-12-01_15-25-26.avi'
video = 0
new_animal_start = geometry.Point()
new_animal_end = geometry.Point()
# initialized in arrange controls
image_width = 0
image_height = 0
image_scale_factor = 0
image_dx = 0
image_dy = 0
slider = 0
initial_geometry = '1216x800'
controls_created = False
writer = 0
debug_frame_containers = dict()
draw_one_frame = False
# evelien
evelien_circle_center = None
class AnalyzerState:
def __init__(self, factory):
self.factory = factory
self.configuration = factory.create_configuration()
self.decorator = factory.create_decorator(self.configuration)
analyzer_states = [ None, AnalyzerState(intruder.factory()), AnalyzerState(evelien.factory()) ]
# active analyzer
analyzer = None
got_first_tracking_element = False
def __init__(self):
# silly tkinter initialization
self.root = Tk.Tk()
self.root.withdraw()
self.root = Tk.Toplevel()
self.root.protocol("WM_DELETE_WINDOW", self.quit)
self.root.title("Rat tracking tool")
self.root.geometry(self.initial_geometry)
self.root.bind("<Configure>", self.on_root_resize)
buttons_left_margin = 8
buttons_top_margin = 15
buttons_width = 160
buttons_height = 35
check_height = 23
radio_height = 23
label_height = 20
buttons_space = 5
# create main menu
self.menu = Tk.Menu(self.root)
submenu = Tk.Menu(self.menu, tearoff = 0)
submenu.add_command(label = 'Delete all animals', command = self.on_delete_all_animals)
self.menu.add_cascade(label = "Objects", menu = submenu)
misc = Tk.Menu(self.menu, tearoff = 0)
misc.add_command(label = 'Source frame screenshot', command = self.on_source_screenshot)
misc.add_command(label = 'Drawn frame screenshot', command = self.on_drawn_frame_screenshot)
misc.add_command(label = 'Debug frame screenshot', command = self.on_debug_frame_screenshot)
self.menu.add_cascade(label = "Misc", menu = misc)
background = Tk.Menu(self.menu, tearoff = 0)
background.add_command(label = 'Capture the background', command = self.on_capture_background)
background.add_command(label = 'Calculate the background', command = self.on_calculate_background)
self.menu.add_cascade(label = "Background", menu = background)
self.menu.add_command(label = "Quit", command = self.on_quit)
self.root.config(menu = self.menu)
control_y = buttons_top_margin
self.select_file_button = gui_tools.create_button(self.root, "Select file", self.select_file,
buttons_left_margin, control_y, buttons_width, buttons_height)
control_y = control_y + buttons_height + buttons_space
self.start_button = gui_tools.create_button(self.root, "Run", self.start,
buttons_left_margin, control_y, buttons_width, buttons_height)
control_y = control_y + buttons_height + buttons_space
self.next_button = gui_tools.create_button(self.root, "Next", self.next,
buttons_left_margin, control_y, buttons_width, buttons_height)
control_y = control_y + buttons_height + buttons_space
self.next_button = gui_tools.create_button(self.root, "Configure tracker", self.configure_tracker,
buttons_left_margin, control_y, buttons_width, buttons_height)
control_y = control_y + buttons_height + buttons_space
self.check_show_model = gui_tools.create_check(self.root, "Show model", 1, self.on_show_model,
buttons_left_margin, control_y, buttons_width, buttons_height)
control_y = control_y + check_height + buttons_space
self.check_show_posture = gui_tools.create_check(self.root, "Show posture", 1, self.on_show_posture,
buttons_left_margin, control_y, buttons_width, buttons_height)
control_y = control_y + check_height + buttons_space
self.check_show_debug = gui_tools.create_check(self.root, "Show debug", 1, self.on_show_debug,
buttons_left_margin, control_y, buttons_width, buttons_height)
control_y = control_y + check_height + buttons_space
self.check_show_rotated = gui_tools.create_check(self.root, "Show rotated frames", 1, self.on_show_rotated,
buttons_left_margin, control_y, buttons_width, buttons_height)
control_y = control_y + check_height + buttons_space
self.check_show_analyzer_data = gui_tools.create_check(self.root, "Show analyzer data", 1, self.on_show_analyzer_data,
buttons_left_margin, control_y, buttons_width, buttons_height)
control_y = control_y + check_height + buttons_space
gui_tools.create_label(self.root, "Animal model",
buttons_left_margin, control_y, buttons_width, buttons_height)
control_y = control_y + label_height + buttons_space
self.animal_model = Tk.IntVar()
self.animal_model.set(tracking.Animal.Configuration.model_with_drive)
for m in ((tracking.Animal.Configuration.model_normal, 'Normal'),
(tracking.Animal.Configuration.model_with_drive, 'With a drive')):
gui_tools.create_radio(self.root, m[1], self.animal_model, m[0],
buttons_left_margin, control_y, buttons_width, buttons_height)
control_y = control_y + radio_height + buttons_space
control_y = control_y + buttons_space
gui_tools.create_label(self.root, "Analyzers",
buttons_left_margin, control_y, buttons_width, buttons_height)
control_y = control_y + label_height + buttons_space
self.analyzer_index = Tk.IntVar()
self.analyzer_index.set(0)
for i, a in enumerate(self.analyzer_states):
if a is None:
gui_tools.create_radio(self.root, 'None', self.analyzer_index, i,
buttons_left_margin, control_y, buttons_width, buttons_height)
else:
gui_tools.create_radio(self.root, a.factory.name, self.analyzer_index, i,
buttons_left_margin, control_y, buttons_width, buttons_height)
control_y = control_y + radio_height + buttons_space
self.configure_analyzer_button = gui_tools.create_button(self.root, "Configure analyzer", self.configure_analyzer,
buttons_left_margin, control_y, buttons_width, buttons_height)
control_y = control_y + buttons_height + buttons_space
self.root.update()
self.arrange_controls(self.root.winfo_width(), self.root.winfo_height())
self.tracking_config = config_serialization.load_tracking_config('tracking.cfg')
self.animal_config = config_serialization.load_animal_config('animal.cfg')
if os.path.isfile(self.video_file_name):
self.on_new_video()
def arrange_controls(self, width, height):
left_panel_width = 177
right_margin = 17
bottom_margin = 17
top_panel_height = 50;
containers_margin = 10
horz_space = width - left_panel_width - right_margin
vert_space = height - top_panel_height - bottom_margin
slider_length = horz_space
containers_height = (vert_space - containers_margin) / 2
containers_width = (horz_space - containers_margin) / 2
self.image_width = containers_width
self.image_height = containers_height
if self.state != self.gs_no_video_selected:
rows, cols = self.current_frame.shape[:2]
(self.image_scale_factor, self.image_dx, self.image_dy) = calculate_scale_factor(cols, rows, self.image_width, self.image_height)
if not self.controls_created:
slider_x = left_panel_width
slider_y = 0
self.slider = Tk.Scale(self.root, length = slider_length, from_ = 0, to = 100,
orient = Tk.HORIZONTAL, command = self.on_video_position_changed)
self.slider.place(x = slider_x, y = slider_y)
self.image_container = Tk.Label(self.root)
self.image_container.place(x = left_panel_width, y = top_panel_height)
# have to set fake image to switch 'width' and 'height' interpretation mode
self.image_container.image = ImageTk.PhotoImage('RGB', (1, 1))
self.image_container.config(image = self.image_container.image)
self.image_container.config(relief = Tk.GROOVE, width = containers_width, height = containers_height)
# self.image_container.config(borderwidth = 1)
self.image_container.bind('<Button-1>', self.on_left_mouse_button_down)
self.image_container.bind('<ButtonRelease-1>', self.on_left_mouse_button_up)
self.image_container.bind('<Motion>', self.on_mouse_moved)
self.debug_tabs = gui_tools.create_tabs(self.root, left_panel_width + containers_width + containers_margin, top_panel_height, containers_width, containers_height)
self.direction_image_container = Tk.Label(self.root)
self.direction_image_container.place(x = left_panel_width, y = top_panel_height + containers_height + containers_margin)
self.direction_image_container.image = ImageTk.PhotoImage('RGB', (1, 1))
self.direction_image_container.config(image = self.direction_image_container.image)
self.direction_image_container.config(relief = Tk.GROOVE, width = containers_width, height = containers_height)
self.messages_tabs = gui_tools.create_tabs(self.root, left_panel_width + containers_width + containers_margin,
top_panel_height + containers_height + containers_margin, containers_width, containers_height)
page = ttk.Frame(self.messages_tabs[1])
self.tracker_messages = Tk.Text(page)
self.tracker_messages.pack(expand = 1, fill = "both")
self.messages_tabs[1].add(page, text = "Tracker")
page = ttk.Frame(self.messages_tabs[1])
self.analyzer_messages = Tk.Text(page)
self.analyzer_messages.pack(expand = 1, fill = "both")
self.messages_tabs[1].add(page, text = "Analyzer")
self.controls_created = True;
else:
self.slider.config(length = slider_length)
self.image_container.config(width = containers_width, height = containers_height)
self.debug_tabs[0].config(width = containers_width, height = containers_height)
self.debug_tabs[0].place(x = left_panel_width + containers_width + containers_margin)
self.direction_image_container.config(width = containers_width, height = containers_height)
self.direction_image_container.place(y = top_panel_height + containers_height + containers_margin)
self.messages_tabs[0].place(x = left_panel_width + containers_width + containers_margin, y = top_panel_height + containers_height + containers_margin)
self.messages_tabs[0].config(width = containers_width, height = containers_height)
def set_image(self, container, matrix):
img = Image.fromarray(matrix)
imgtk = ImageTk.PhotoImage(image = img)
container.image = imgtk
container.configure(image = container.image)
def update_image(self):
self.set_image(self.image_container, self.current_image)
def project(self, pos):
r = geometry.Point(pos.x * self.image_scale_factor, pos.y * self.image_scale_factor)
return r;
def scaled_radius(self, r):
return r * self.image_scale_factor
def draw_animals(self):
for ap in self.current_animal_positions:
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)
yellow = (255, 255, 0)
a = ap[0]
p = ap[1]
if self.check_show_model.var.get():
ph = self.project(p.head)
pf = self.project(p.front)
pb = self.project(p.back)
hr = self.scaled_radius(a.head_radius)
fr = self.scaled_radius(a.front_radius)
br = self.scaled_radius(a.back_radius)
cv2.circle(self.current_image, pb.as_int_tuple(), int(br), white)
if not p.contracted:
cv2.circle(self.current_image, pf.as_int_tuple(), int(fr), white)
cv2.circle(self.current_image, ph.as_int_tuple(), int(hr), white)
if self.check_show_posture.var.get():
hc = self.project(p.head)
fc = self.project(p.front)
bc = self.project(p.back)
hr = self.scaled_radius(a.head_radius)
fr = self.scaled_radius(a.front_radius)
br = self.scaled_radius(a.back_radius)
fhd = geometry.distance(fc.x, fc.y, hc.x, hc.y)
fbd = geometry.distance(fc.x, fc.y, bc.x, bc.y)
if not p.contracted:
h = geometry.point_along_a_line(fc.x, fc.y, hc.x, hc.y, fhd + hr)
b = geometry.point_along_a_line(fc.x, fc.y, bc.x, bc.y, fbd + br)
cv2.line(self.current_image, (int(b[0]), int(b[1])),
(int(fc.x), int(fc.y)), white)
cv2.line(self.current_image, (int(fc.x), int(fc.y)),
(int(h[0]), int(h[1])), white)
cv2.circle(self.current_image, (int(fc.x), int(fc.y)), 2, green)
ahd = fhd - 4
if ahd < 0:
ahd = 0
arrow_head = geometry.point_along_a_line(fc.x, fc.y, hc.x, hc.y, ahd)
arrow_line1 = geometry.point_along_a_perpendicular(fc.x, fc.y, hc.x, hc.y,
arrow_head[0], arrow_head[1], 3)
arrow_line2 = geometry.point_along_a_perpendicular(fc.x, fc.y, hc.x, hc.y,
arrow_head[0], arrow_head[1], -3)
cv2.line(self.current_image, (int(h[0]), int(h[1])),
(int(arrow_line1[0]), int(arrow_line1[1])), white)
cv2.line(self.current_image, (int(h[0]), int(h[1])),
(int(arrow_line2[0]), int(arrow_line2[1])), white)
else:
hbd = geometry.distance(hc.x, hc.y, bc.x, bc.y)
h = geometry.point_along_a_line(bc.x, bc.y, hc.x, hc.y, hbd + hr)
b = geometry.point_along_a_line(hc.x, hc.y, bc.x, bc.y, hbd + br)
cv2.line(self.current_image, (int(b[0]), int(b[1])),
(int(h[0]), int(h[1])), white)
ahd = hbd - 4
if ahd < 0:
ahd = 0
arrow_head = geometry.point_along_a_line(bc.x, bc.y, hc.x, hc.y, ahd)
arrow_line1 = geometry.point_along_a_perpendicular(bc.x, bc.y, hc.x, hc.y,
arrow_head[0], arrow_head[1], 3)
arrow_line2 = geometry.point_along_a_perpendicular(bc.x, bc.y, hc.x, hc.y,
arrow_head[0], arrow_head[1], -3)
cv2.line(self.current_image, (int(h[0]), int(h[1])),
(int(arrow_line1[0]), int(arrow_line1[1])), white)
cv2.line(self.current_image, (int(h[0]), int(h[1])),
(int(arrow_line2[0]), int(arrow_line2[1])), white)
def draw_image(self):
self.current_image = cv2.cvtColor(self.current_frame, cv2.COLOR_BGR2RGB);
self.current_image = fit_image(self.current_image, self.image_width, self.image_height)
analyzer_state = self.analyzer_states[self.analyzer_index.get()]
if not (analyzer_state is None) and self.check_show_analyzer_data.var.get():
analyzer_state.decorator.decorate_before(self.analyzer, self.current_image, self.image_scale_factor)
self.draw_animals()
if self.state == self.gs_adding_animal:
cv2.line(self.current_image, (int(self.new_animal_start.x), int(self.new_animal_start.y)),
(int(self.new_animal_end.x), int(self.new_animal_end.y)), (255, 255, 255))
if (not (analyzer_state is None)) and self.check_show_analyzer_data.var.get():
analyzer_state.decorator.decorate_after(self.analyzer, self.current_image, self.image_scale_factor)
def poll_tracking_flow(self):
if self.time_to_stop.isSet():
return
while not self.tracker_messages_queue.empty():
e = self.tracker_messages_queue.get()
self.tracker_messages.insert(Tk.END, e + '\n')
self.tracker_messages.yview(Tk.END)
e = 0
max_elements_to_get = 10
while not self.tracking_flow.empty() and max_elements_to_get > 0:
e = self.tracking_flow.get()
if self.got_first_tracking_element:
ret, self.current_frame = self.video.read()
else:
self.got_first_tracking_element = True
if not (self.analyzer is None):
self.analyzer.analyze(e)
if self.tracking.finished:
self.analyzer.on_finished()
max_elements_to_get = max_elements_to_get - 1
if e != 0:
frame_num = self.video.get(cv2.CAP_PROP_POS_FRAMES)
max = self.video.get(cv2.CAP_PROP_FRAME_COUNT) - 1
self.slider.set((self.max_video_position_slider_value * frame_num) / max)
self.current_animal_positions = e.positions
self.draw_image()
'''
if self.writer == 0:
rows, cols = self.current_image.shape[:2]
fourcc = cv2.VideoWriter_fourcc(*'XVID')
self.writer = cv2.VideoWriter('output.avi', -1 , 20.0, (cols, rows))
self.writer.write(self.current_image)
'''
self.update_image()
'''
if self.check_show_rotated.var.get():
p = e.positions[0][1]
hc = p.head
fc = p.front
dx = hc.x - fc.y
dy = hc.x - fc.y
length = math.sqrt(dx**2 + dy**2)
if length != 0:
cos = - dy / length
angle = math.acos(cos) * 180 / math.pi
if dx < 0:
angle = -angle
else:
angle = 0
rc = (self.image_width / 2, self.image_height / 2)
rotation_matrix = cv2.getRotationMatrix2D(rc, angle, 1.0);
rotated = cv2.warpAffine(self.current_image, rotation_matrix,
(self.image_width, self.image_height))
self.set_image(self.direction_image_container, rotated)
'''
'''
width = self.filtered_image_container.winfo_width()
height = self.filtered_image_container.winfo_height()
self.set_image(self.filtered_image_container,
fit_image(e.filtered_image, width, height))
'''
#w = np.ones((rows, cols), np.float)
#w.fill(255)
#w = np.multiply(w, e.weights[0])
if self.check_show_debug.var.get():
for df in e.debug_frames:
(name, frame) = df
if name in self.debug_frame_containers:
frame_container = self.debug_frame_containers[name]
else:
page = ttk.Frame(self.debug_tabs[1])
image_container = Tk.Label(page)
image_container.pack(expand = 1, fill = "both")
self.debug_tabs[1].add(page, text = name)
frame_container = (page, image_container, None)
self.debug_frame_containers[name] = frame_container
(page, image_container, old_frame) = frame_container
width = self.debug_tabs[1].winfo_width()
height = self.debug_tabs[1].winfo_height()
self.set_image(image_container, fit_image(frame, width, height))
self.debug_frame_containers[name] = (page, image_container, frame)
self.draw_one_frame = False
#self.set_image(self.filtered_image_container,
# fit_image(w, cols, rows))
#self.tracking_flow.task_done()
#print('flush')
if self.state != self.gs_paused or self.draw_one_frame:
self.root.after(10, self.poll_tracking_flow)
# controls events
def on_root_resize(self, event):
if event.widget == self.root:
self.arrange_controls(event.width, event.height)
def on_new_video(self):
self.video = cv2.VideoCapture(self.video_file_name)
self.state = self.gs_not_started
max = self.video.get(cv2.CAP_PROP_FRAME_COUNT) - 1
self.max_video_position_slider_value = max
self.slider["to"] = self.max_video_position_slider_value
#self.video.set(cv2.CAP_PROP_POS_FRAMES, 190)
# take first frame of the video
ret, self.current_frame = self.video.read()
if not ret:
print('can\'t read the video')
sys.exit()
rows, cols = self.current_frame.shape[:2]
self.tracking = tracking.Tracking(self.video_file_name, self.tracking_config, QueueLogger(self.tracker_messages_queue))
(self.image_scale_factor, self.image_dx, self.image_dy) = calculate_scale_factor(cols, rows, self.image_width, self.image_height)
self.draw_image()
self.update_image()
def run(self):
self.root.mainloop()
self.root.destroy()
self.video.release()
def get_bg_file_name(self):
bg_file_name = os.path.splitext(self.video_file_name)[0]
return bg_file_name + '-bg.tiff'
def on_video_position_changed(self, val):
if self.state != self.gs_not_started:
return
max = self.video.get(cv2.CAP_PROP_FRAME_COUNT) - 1;
self.current_frame_number = max * float(val) / self.max_video_position_slider_value
self.video.set(cv2.CAP_PROP_POS_FRAMES, self.current_frame_number)
ret, frame = self.video.read()
self.current_frame = frame
self.draw_image()
self.update_image()
def start(self):
if self.state == self.gs_running:
self.start_button["text"] = "Run"
self.run_tracking_semaphore.clear();
self.state = self.gs_paused
elif self.state == self.gs_paused:
self.start_button["text"] = "Pause"
self.run_tracking_semaphore.set();
self.next_frame_semaphore.set();
self.state = self.gs_running
self.root.after(1, self.poll_tracking_flow)
else:
bg = cv2.imread(self.get_bg_file_name())
if bg is None:
tkMessageBox.showwarning('Start tracking', 'Can''t find the backgound image file')
return;
self.start_button["text"] = "Pause"
self.run_tracking_semaphore.set();
self.tracking_thread = threading.Thread(target = self.tracking.do_tracking, args =
(bg, self.current_frame_number, self.tracking_flow, self.time_to_stop, self.next_frame_semaphore, self.run_tracking_semaphore))
# self.tracking.do_tracking(self.video_file_name, self.current_frame_number, self.tracking_flow, self.time_to_stop);
analyzer_state = self.analyzer_states[self.analyzer_index.get()]
if not (analyzer_state is None):
self.analyzer = analyzer_state.factory.create_analyzer(analyzer_state.configuration, TextBoxLogger(self.analyzer_messages))
else:
self.analyzer = None
self.tracking_thread.start()
self.poll_tracking_flow()
self.state = self.gs_running
def next(self):
self.draw_one_frame = True
self.next_frame_semaphore.set()
self.root.after(1, self.poll_tracking_flow)
def quit(self):
if self.tracking_thread != 0:
self.time_to_stop.set()
# clear the queue
while not self.tracker_messages_queue.empty():
self.tracker_messages_queue.get()
self.tracker_messages_queue.task_done()
while not self.tracking_flow.empty():
self.tracking_flow.get()
self.tracking_flow.task_done()
self.next_frame_semaphore.set()
# self.tracking_flow.task_done()
self.tracking_thread.join()
if self.writer != 0:
self.writer.release()
self.root.quit()
def on_quit(self):
if tkMessageBox.askyesno('Quit', 'Quit the tool?'):
self.quit()
def select_file(self):
fn = tkFileDialog.askopenfilename()
if fn:
self.video_file_name = fn
self.on_new_video()
def on_calculate_background(self):
if tkMessageBox.askyesno('Calculate background', 'Calculate background for the loaded video(it can take a long time)?'):
bg = self.tracking.calculate_background()
cv2.imwrite(self.get_bg_file_name(), bg)
def on_capture_background(self):
if tkMessageBox.askyesno('Capture background', 'Capture the backgound from the current frame? It will replace the background file.'):
bg = self.current_frame
cv2.imwrite(self.get_bg_file_name(), bg)
def configure_tracker(self):
tc = TrackerConfigurator(self.tracking_config, self.animal_config, self, self.root, self.current_frame)
def configure_analyzer(self):
state = self.analyzer_states[self.analyzer_index.get()]
state.factory.create_configurator(state.configuration, self, self.root, self.current_frame)
def on_configurator_closing(self):
self.draw_image()
self.update_image()
def on_show_model(self):
if self.state != self.gs_no_video_selected:
self.draw_image()
self.update_image()
def on_show_posture(self):
if self.state != self.gs_no_video_selected:
self.draw_image()
self.update_image()
def on_show_debug(self):
if self.state != self.gs_no_video_selected:
self.draw_image()
self.update_image()
def on_show_rotated(self):
if self.state != self.gs_no_video_selected:
self.draw_image()
self.update_image()
def on_show_analyzer_data(self):
if self.state != self.gs_no_video_selected:
self.draw_image()
self.update_image()
# menu events
def on_delete_all_animals(self):
if self.state != self.gs_no_video_selected:
self.tracking.delete_all_animals()
self.current_animal_positions = []
self.draw_image()
self.update_image()
def on_source_screenshot(self):
cv2.imwrite('source_frame.png', self.current_frame)
def on_drawn_frame_screenshot(self):
image = cv2.cvtColor(self.current_image, cv2.COLOR_RGB2BGR);
cv2.imwrite('drawn_frame.png', image)
def on_debug_frame_screenshot(self):
curently_selected = self.debug_tabs[1].tab(self.debug_tabs[1].select(), "text")
(page, image_container, frame) = self.debug_frame_containers[curently_selected]
cv2.imwrite('debug_frame.png', frame)
# mouse events
def on_left_mouse_button_down(self, event):
self.new_animal_start.x = event.x - self.image_dx
self.new_animal_start.y = event.y - self.image_dy
self.state = self.gs_adding_animal
def on_left_mouse_button_up(self, event):
if self.state == self.gs_adding_animal:
self.state = self.gs_not_started
self.new_animal_end.x = event.x - self.image_dx
self.new_animal_end.y = event.y - self.image_dy
model = self.animal_model.get()
if model == tracking.Animal.Configuration.model_with_drive:
self.animal_model.set(tracking.Animal.Configuration.model_normal)
self.animal_config.model = model
a = self.tracking.add_animal(self.new_animal_start.x / self.image_scale_factor, self.new_animal_start.y / self.image_scale_factor,
self.new_animal_end.x / self.image_scale_factor, self.new_animal_end.y / self.image_scale_factor,
self.animal_config)
# a.best_fit(self.current_frame)
self.current_animal_positions = self.tracking.get_animal_positions()
self.draw_image()
self.update_image()
def on_mouse_moved(self, event):
if self.state == self.gs_adding_animal:
self.new_animal_end.x = event.x - self.image_dx
self.new_animal_end.y = event.y - self.image_dy
self.draw_image()
self.update_image()
# main()
gui = Gui()
gui.run()