-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathregion_editor.py
More file actions
1446 lines (1285 loc) · 57.2 KB
/
region_editor.py
File metadata and controls
1446 lines (1285 loc) · 57.2 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
#
# DVR-Scan: Video Motion Event Detection & Extraction Tool
# --------------------------------------------------------------
# [ Site: https://www.dvr-scan.com/ ]
# [ Repo: https://github.com/Breakthrough/DVR-Scan ]
#
# Copyright (C) 2024 Brandon Castellano <http://www.bcastell.com>.
# DVR-Scan is licensed under the BSD 2-Clause License; see the included
# LICENSE file, or visit one of the above pages for details.
#
import math
import os
import os.path
import sys
import tkinter as tk
import tkinter.filedialog
import tkinter.messagebox
import tkinter.scrolledtext
import tkinter.ttk as ttk
import typing as ty
import webbrowser
from copy import deepcopy
from dataclasses import dataclass
from logging import getLogger
import cv2
import numpy as np
import PIL
import PIL.Image
import PIL.ImageTk
import dvr_scan
from dvr_scan.app.about_window import AboutWindow
from dvr_scan.app.common import register_icon
from dvr_scan.region import Point, Size, bound_point, load_regions
WINDOW_TITLE = "DVR-Scan Region Editor"
OWNED_WINDOW_TITLE = "Region Editor"
PROMPT_TITLE = "DVR-Scan"
PROMPT_MESSAGE = "You have unsaved region changes.\nDo you want to save them?"
SAVE_TITLE = "Save Region File"
LOAD_TITLE = "Load Region File"
SAVE_REGIONS = "Save Regions"
SAVE_REGIONS_PROMPT = "Save Regions..."
ABOUT_WINDOW_COPYRIGHT = (
f"DVR-Scan {dvr_scan.__version__}\n\nCopyright © Brandon Castellano.\nAll rights reserved."
)
# TODO: Need to figure out DPI scaling for *everything*. Lots of magic numbers for sizes right now.
MIN_SIZE = 16
"""Minimum height/width for a ROI created using the mouse."""
logger = getLogger("dvr_scan")
@dataclass
class Snapshot:
regions: ty.List[ty.List[Point]]
active_shape: ty.Optional[int]
# TODO: Allow controlling some of these settings in the config file.
@dataclass
class EditorSettings:
video_path: str
"""The first input video path specified by -i/--input."""
save_path: ty.Optional[str] = False
"""The path specified by the -s/--save-regions option if set."""
use_aa: bool = True
mask_source: bool = False
line_color: ty.Tuple[int, int, int] = (255, 0, 0)
line_color_alt: ty.Tuple[int, int, int] = (255, 153, 51)
line_color_inactive: ty.Tuple[int, int, int] = (172, 80, 24)
hover_color: ty.Tuple[int, int, int] = (0, 127, 255)
hover_color_alt: ty.Tuple[int, int, int] = (0, 0, 255)
interact_color: ty.Tuple[int, int, int] = (0, 255, 255)
class AutoHideScrollbar(tk.Scrollbar):
def set(self, lo, hi):
if float(lo) <= 0.0 and float(hi) >= 1.0:
self.grid_remove()
else:
self.grid()
tk.Scrollbar.set(self, lo, hi)
MIN_NUM_POINTS = 3
MAX_HISTORY_SIZE = 1024
MIN_DOWNSCALE_FACTOR = 1
MAX_DOWNSCALE_FACTOR = 10
MAX_UPDATE_RATE_NORMAL = 20
MAX_UPDATE_RATE_DRAGGING = 5
HOVER_DISPLAY_DISTANCE = 260**2
MAX_DOWNSCALE_AA_LEVEL = 4
ACCELERATOR_KEY = "Command" if sys.platform == "darwin" else "Ctrl"
KEYBIND_POINT_ADD = "+"
KEYBIND_POINT_ADD_ALT1 = "="
KEYBIND_POINT_ADD_ALT2 = "KP_Add"
KEYBIND_POINT_DELETE = "-"
KEYBIND_POINT_DELETE_ALT1 = "_"
KEYBIND_POINT_DELETE_ALT2 = "KP_Minus"
KEYBIND_REGION_ADD = f"{ACCELERATOR_KEY}+N"
KEYBIND_REGION_DELETE = f"{ACCELERATOR_KEY}+D"
KEYBIND_REGION_NEXT = "Tab"
KEYBIND_REGION_PREVIOUS = "Shift+Tab"
KEYBIND_TOGGLE_AA = f"{ACCELERATOR_KEY}+A"
KEYBIND_DOWNSCALE_INC = f"{ACCELERATOR_KEY}+(+)"
KEYBIND_DOWNSCALE_DEC = f"{ACCELERATOR_KEY}+(-)"
KEYBIND_BREAKPOINT = f"{ACCELERATOR_KEY}+B"
KEYBIND_MASK = f"{ACCELERATOR_KEY}+M"
KEYBIND_LOAD = f"{ACCELERATOR_KEY}+O"
KEYBIND_SAVE = f"{ACCELERATOR_KEY}+S"
KEYBIND_COPY_COMMAND = f"{ACCELERATOR_KEY}+C"
KEYBIND_HELP = f"{ACCELERATOR_KEY}+H"
KEYBIND_QUIT = f"{ACCELERATOR_KEY}+Q"
KEYBIND_START_SCAN = f"{ACCELERATOR_KEY}+Space"
KEYBIND_UNDO = "Ctrl+Z" if os.name == "nt" else f"{ACCELERATOR_KEY}+Z"
KEYBIND_REDO = "Ctrl+Y" if os.name == "nt" else f"{ACCELERATOR_KEY}+Shift+Z"
def control_handle_radius(scale: int):
"""Get size of point control handles based on scale factor."""
# TODO: This should be based on the video resolution in addition to scale factor.
if scale == 1:
return 12
elif scale == 2:
return 7
elif scale == 3:
return 5
elif scale <= 10:
return 4
elif scale <= 20:
return 3
elif scale <= 64:
return 2
return 1
def edge_thickness(scale: int, ext: int = 0):
"""Get thickness of polygon connecting edges based on scale factor."""
# TODO: This should be based on the video resolution in addition to scale factor.
if scale < 2:
return 4 + ext
elif scale < 5:
return 3 + ext
elif scale <= 10:
return 2 + ext
return 1 + ext if scale <= 20 else 0
def initial_point_list(frame_size: Size) -> ty.List[Point]:
# For now start with a rectangle covering 1/4 of the frame in the middle.
top_left = Point(x=frame_size.w // 4, y=frame_size.h // 4)
box_size = Size(w=frame_size.w // 2, h=frame_size.h // 2)
return [
top_left,
Point(x=top_left.x + box_size.w, y=top_left.y),
Point(x=top_left.x + box_size.w, y=top_left.y + box_size.h),
Point(x=top_left.x, y=top_left.y + box_size.h),
]
def squared_distance(a: Point, b: Point) -> int:
return (a.x - b.x) ** 2 + (a.y - b.y) ** 2
# TODO: Allow translating polygons using middle mouse button.
class RegionEditor:
def __init__(
self,
frame: np.ndarray,
initial_shapes: ty.Optional[ty.List[ty.List[Point]]],
initial_scale: ty.Optional[int],
debug_mode: bool,
video_path: str,
save_path: ty.Optional[str],
on_close: ty.Optional[ty.Callable[[], None]] = None,
):
self._settings = EditorSettings(video_path=video_path, save_path=save_path)
self._source_frame: np.ndarray = frame.copy() # Frame before downscaling
self._source_size: Size = Size(w=frame.shape[1], h=frame.shape[0])
self._frame: np.ndarray = frame.copy() # Workspace
self._frame_size: Size = Size(w=frame.shape[1], h=frame.shape[0])
self._original_frame: np.ndarray = frame.copy() # Copy to redraw on
self._video = cv2.VideoCapture(video_path)
self._video_pos = 0
self._num_frames = int(self._video.get(cv2.CAP_PROP_FRAME_COUNT))
self._regions: ty.List[ty.List[Point]] = (
initial_shapes if initial_shapes else [initial_point_list(self._frame_size)]
)
self._active_shape: int = len(self._regions) - 1
self._history: ty.List[Snapshot] = []
self._history_pos: int = 0
self._curr_mouse_pos: Point = None
self._hover_point: ty.Optional[int] = None
self._nearest_points: ty.Optional[ty.Tuple[int, int]] = None
self._redraw: bool = True
self._recalculate: bool = True
self._dragging: bool = False
self._drag_start: ty.Optional[Point] = None
self._debug_mode: bool = debug_mode
self._segment_dist: ty.List[int] = [] # Square distance of segment from point i to i+1
self._mouse_dist: ty.List[int] = [] # Square distance of mouse to point i
self._scale: int = 1 if initial_scale is None else initial_scale
self._persisted: bool = True # Indicates if we've saved outstanding changes to disk.
self._persisted_path: str = "" # Path we've saved changes to, if any.
self._launched_from_app: bool = False
self._on_close: ty.Optional[ty.Callable[[], None]] = on_close
self._root: ty.Union[tk.Tk, tk.Toplevel] = None
self._edit_menu: tk.Menu = None
self._editor_window: tk.Toplevel = None
self._editor_canvas: tk.Canvas = None
self._editor_scroll: ty.Tuple[tk.Scrollbar, tk.Scrollbar] = None
self._should_scan: bool = False
self._scale_widget: ttk.Scale = None
self._pan_enabled: bool = False
self._panning: bool = False
self._controls_window: tk.Toplevel = None
self._region_selector: ttk.Combobox = None
self._context_menu: tk.Menu = None
# Clones of the normal state variables since sometimes we can still interact with the main
# window after the context menu is posted.
self._context_curr_mouse_pos: Point = None
self._context_hover_point: ty.Optional[int] = None
self._context_nearest_points: ty.Optional[ty.Tuple[int, int]] = None
self._log_stats = False
self._redraws = 0
self._recalculates = 0
self._commit(persisted=True) # Add initial history for undo.
@property
def shapes(self) -> ty.Iterable[ty.Iterable[Point]]:
return self._regions
@property
def active_region(self) -> ty.Optional[ty.List[Point]]:
return (
self._regions[self._active_shape]
if (self._active_shape is not None and bool(self._regions))
else None
)
@property
def persisted(self) -> bool:
return self._persisted
@property
def persisted_path(self) -> str:
return self._persisted_path
def _rescale(self, draw=True, allow_resize=True):
assert self._scale > 0
logger.info(f"Downscale factor: {self._scale}")
self._original_frame = self._source_frame[:: self._scale, :: self._scale, :].copy()
self._frame = self._original_frame.copy()
self._frame_size = Size(w=self._frame.shape[1], h=self._frame.shape[0])
self._redraw = True
self._editor_canvas["scrollregion"] = (0, 0, self._frame.shape[1], self._frame.shape[0])
if allow_resize:
max_width_auto = int(self._root.winfo_screenwidth() * 0.8)
max_height_auto = int(self._root.winfo_screenheight() * 0.8)
self._editor_canvas["width"] = min(max_width_auto, self._frame.shape[1])
self._editor_canvas["height"] = min(max_height_auto, self._frame.shape[0])
else:
old_geom = self._root.geometry()
self._editor_canvas["width"] = self._frame.shape[1]
self._editor_canvas["height"] = self._frame.shape[0]
self._root.geometry(old_geom)
if draw:
self._draw()
logger.debug(
"Resize: scale = 1/%d%s, res = %d x %d",
self._scale,
" (off)" if self._scale == 1 else "",
self._frame_size.w,
self._frame_size.h,
)
def _undo(self):
if self._history_pos < (len(self._history) - 1):
self._history_pos += 1
snapshot = deepcopy(self._history[self._history_pos])
self._regions = snapshot.regions
self._active_shape = snapshot.active_shape
self._recalculate = True
self._redraw = True
self._draw()
logger.debug("Undo: [%d/%d]", self._history_pos, len(self._history) - 1)
self._update_ui_state()
def _redo(self):
if self._history_pos > 0:
self._history_pos -= 1
snapshot = deepcopy(self._history[self._history_pos])
self._regions = snapshot.regions
self._active_shape = snapshot.active_shape
self._recalculate = True
self._redraw = True
self._draw()
logger.debug("Redo: [%d/%d]", self._history_pos, len(self._history) - 1)
self._update_ui_state()
def _commit(self, persisted=False):
# Take a copy of the current state and put it in the history buffer.
snapshot = deepcopy(Snapshot(regions=self._regions, active_shape=self._active_shape))
self._history = self._history[self._history_pos :]
self._history.insert(0, snapshot)
self._history = self._history[:MAX_HISTORY_SIZE]
self._history_pos = 0
# Update state.
self._recalculate = True
self._redraw = True
self._persisted = persisted
self._update_ui_state()
def _update_ui_state(self):
if self._root is None:
return
can_undo = self._history_pos < (len(self._history) - 1)
self._edit_menu.entryconfigure("Undo", state=tk.ACTIVE if can_undo else tk.DISABLED)
can_redo = self._history_pos > 0
self._edit_menu.entryconfigure("Redo", state=tk.ACTIVE if can_redo else tk.DISABLED)
if self._regions:
self._region_selector["values"] = tuple(
f"Shape {i + 1}" for i in range(len(self._regions))
)
assert self._active_shape is not None
self._region_selector.current(self._active_shape)
self._region_selector.config(state="readonly")
else:
self._region_selector["values"] = ("",)
assert self._active_shape is not None
self._region_selector.current(self._active_shape)
self._region_selector.config(state="disabled")
self._region_selector.selection_clear()
def _copy_scan_command_to_clipboard(self):
region_info = []
for shape in self._regions:
region_info.append("-a %s" % " ".join(f"{x} {y}" for x, y in shape))
data = " ".join(region_info)
scan_command = f"dvr-scan -i {self._settings.video_path} {data}"
self._root.clipboard_append(scan_command)
logger.info(
f"Region data copied to clipboard. To scan via command-line, run:\n{scan_command}"
)
def _set_cursor(self):
if self._pan_enabled or self._panning:
self._editor_canvas.config(cursor="fleur")
elif self._hover_point is None:
self._editor_canvas.config(cursor="crosshair")
else:
self._editor_canvas.config(cursor="hand2")
def _draw(self):
self._set_cursor()
if self._recalculate:
self._recalculate_data()
if not self._redraw:
return
if self._log_stats:
self._redraws += 1
logger.debug(f"redraw {self._redraws}")
curr_aa = (
cv2.LINE_AA
if self._settings.use_aa and self._scale <= MAX_DOWNSCALE_AA_LEVEL
else cv2.LINE_4
)
frame = self._original_frame.copy()
# Mask pixels outside of the defined region if we're in mask mode.
if self._settings.mask_source:
mask = np.zeros_like(frame, dtype=np.uint8)
for shape in self._regions:
points = np.array([shape], np.int32)
if self._scale > 1:
points = points // self._scale
mask = cv2.fillPoly(mask, points, color=(255, 255, 255), lineType=curr_aa)
frame = np.bitwise_and(frame, mask).astype(np.uint8)
thickness = edge_thickness(self._scale)
thickness_active = edge_thickness(self._scale, 1)
for shape_index, shape in enumerate(self._regions):
points = np.array([shape], np.int32)
if self._scale > 1:
points = points // self._scale
#
if not self._settings.mask_source:
frame = cv2.polylines(
frame,
points,
isClosed=True,
color=self._settings.line_color
if shape_index == self._active_shape
else self._settings.line_color_inactive,
thickness=thickness,
lineType=curr_aa,
)
if self._hover_point is not None and not self._settings.mask_source:
first, mid, last = (
(self._hover_point - 1) % len(self.active_region),
self._hover_point,
(self._hover_point + 1) % len(self.active_region),
)
points = np.array(
[
[
self.active_region[first],
self.active_region[mid],
self.active_region[last],
]
],
np.int32,
)
if self._scale > 1:
points = points // self._scale
frame = cv2.polylines(
frame,
points,
isClosed=False,
color=self._settings.hover_color
if not self._dragging
else self._settings.hover_color_alt,
thickness=thickness_active,
lineType=curr_aa,
)
elif self._nearest_points is not None and not self._settings.mask_source:
points = np.array(
[
[
self.active_region[self._nearest_points[0]],
self.active_region[self._nearest_points[1]],
]
],
np.int32,
)
if self._scale > 1:
points = points // self._scale
frame = cv2.polylines(
frame,
points,
isClosed=False,
color=self._settings.hover_color,
thickness=thickness_active,
lineType=curr_aa,
)
if self.active_region is not None:
radius = control_handle_radius(self._scale)
for i, point in enumerate(self.active_region):
color = self._settings.line_color_alt
if self._hover_point is not None:
if self._hover_point == i:
color = (
self._settings.hover_color_alt
if not self._dragging
else self._settings.interact_color
)
elif self._nearest_points is not None and i in self._nearest_points:
color = (
self._settings.hover_color
if self._dragging
else self._settings.interact_color
)
start, end = (
Point(
(point.x // self._scale) - radius,
(point.y // self._scale) - radius,
),
Point(
(point.x // self._scale) + radius,
(point.y // self._scale) + radius,
),
)
cv2.rectangle(
frame,
start,
end,
color,
thickness=cv2.FILLED,
)
self._frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
self._image = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(self._frame))
self._editor_canvas.create_image(0, 0, anchor=tk.NW, image=self._image)
self._redraw = False
def _find_nearest_segment(self) -> ty.Tuple[int, int]:
nearest_seg, nearest_dist, largest_cosine = 0, 2**31, math.pi
for i in range(len(self.active_region)):
# Create a triangle where side a's length is the mouse to closest point on the line,
# side c is the length to the furthest point, and side b is the line segment length.
next = (i + 1) % len(self.active_region)
a_sq = min(self._mouse_dist[i], self._mouse_dist[next])
c_sq = max(self._mouse_dist[i], self._mouse_dist[next])
b_sq = self._segment_dist[i]
assert a_sq > 0 # Should never hit this since we check _hovering_over first.
if b_sq == 0:
# Two adjacent points are overlapping, just skip this one.
continue
a, b = math.sqrt(a_sq), math.sqrt(b_sq)
cos_C = ((a_sq + b_sq) - c_sq) / (2.0 * a * b)
# If cos_C is between [0,1] the triangle is acute. If it's not, just take the distance
# of the closest point.
dist = int(a_sq - (int(a * cos_C) ** 2)) if cos_C > 0 else a_sq
if dist < nearest_dist or (dist == nearest_dist and cos_C > largest_cosine):
nearest_seg, nearest_dist, largest_cosine = i, dist, cos_C
self._nearest_points = (
nearest_seg,
(nearest_seg + 1) % len(self.active_region),
)
def _find_hover_point(self) -> ty.Optional[int]:
min_i = 0
for i in range(1, len(self._mouse_dist)):
if self._mouse_dist[i] < self._mouse_dist[min_i]:
min_i = i
# If we've shrunk the image, we need to compensate for the size difference in the image.
# The control handles remain the same size but the image is smaller
return (
min_i
if self._mouse_dist[min_i]
<= (4 * control_handle_radius(self._scale) * self._scale) ** 2
else None
)
def _breakpoint(self):
if self._debug_mode:
breakpoint()
def _bind_keyboard(self) -> ty.Dict[int, ty.Callable]:
for key, fn in {
KEYBIND_BREAKPOINT: lambda _: self._breakpoint(),
KEYBIND_POINT_ADD: lambda _: self._add_point(),
KEYBIND_POINT_ADD_ALT1: lambda _: self._add_point(),
KEYBIND_POINT_ADD_ALT2: lambda _: self._add_point(),
KEYBIND_POINT_DELETE: lambda _: self._delete_point(),
KEYBIND_POINT_DELETE_ALT1: lambda _: self._delete_point(),
KEYBIND_POINT_DELETE_ALT2: lambda _: self._delete_point(),
}.items():
self._root.bind(key.lower(), fn)
self._root.bind("<<Undo>>", lambda _: self._undo())
self._root.bind("<<Redo>>", lambda _: self._redo())
self._root.bind("<<Copy>>", lambda _: self._copy_scan_command_to_clipboard())
self._root.bind("<Left>", lambda _: self._prev_region())
self._root.bind("<Right>", lambda _: self._next_region())
self._root.bind("<Tab>", lambda _: self._next_region())
self._root.bind("<Shift-Tab>", lambda _: self._prev_region())
self._root.bind("<Control-s>", lambda _: self._prompt_save())
self._root.bind("<Control-o>", lambda _: self._prompt_load())
self._root.bind("<Control-n>", lambda _: self._add_region())
self._root.bind("<Control-h>", lambda _: self._show_help())
self._root.bind("<Control-d>", lambda _: self._delete_region())
self._root.bind("<Control-a>", lambda _: self._toggle_antialiasing())
self._root.bind("<Control-m>", lambda _: self._toggle_mask())
# +
self._root.bind("<Control-plus>", lambda _: self._adjust_downscale(-1))
self._root.bind("<Control-equal>", lambda _: self._adjust_downscale(-1))
self._root.bind("<Control-KP_Add>", lambda _: self._adjust_downscale(-1))
# -
self._root.bind("<Control-minus>", lambda _: self._adjust_downscale(1))
self._root.bind("<Control-underscore>", lambda _: self._adjust_downscale(1))
self._root.bind("<Control-KP_Subtract>", lambda _: self._adjust_downscale(1))
self._root.bind("<Escape>", lambda _: self._cancel_active_action())
def quit():
self._close(False)
self._root.bind("<Control-q>", lambda _: quit())
self._root.bind("<Control-Return>", lambda _: self._close(True))
self._root.bind("<Control-space>", lambda _: self._close(True))
def set_pan_mode(mode: bool):
if self._dragging:
self._pan_enabled = False
else:
self._pan_enabled = mode
self._set_cursor()
self._root.bind("<KeyPress-Control_L>", lambda _: set_pan_mode(True))
self._root.bind("<KeyPress-Control_R>", lambda _: set_pan_mode(True))
self._root.bind("<KeyRelease-Control_L>", lambda _: set_pan_mode(False))
self._root.bind("<KeyRelease-Control_R>", lambda _: set_pan_mode(False))
self._root.protocol("WM_DELETE_WINDOW", lambda: self._close(False))
self._root.bind("<FocusOut>", lambda _: self._cancel_active_action())
for i in range(9):
def select_region(index):
return lambda _: self._select_region(index)
self._root.bind(f"{i + 1}", select_region(i))
# TODO: If Shift is held down, allow translating current shape
# by left-click and drag.
def _seek(self, frame_num):
self._video_pos = int(float(frame_num))
self._video.set(cv2.CAP_PROP_POS_FRAMES, self._video_pos)
ret, frame = self._video.read()
if ret:
self._source_frame = frame
self._rescale()
self._video_pos_label.config(text=f"{self._video_pos} / {self._num_frames}")
def _close(self, should_scan: bool):
self._video.release()
if self._launched_from_app:
self._root.destroy()
self._on_close()
return
self._should_scan = should_scan
if self.prompt_save_on_scan():
self._root.destroy()
def run(
self,
root: ty.Optional[tk.Tk] = None,
) -> ty.Optional[bool]:
"""Run the region editor. Returns True if the video should be scanned, False otherwise."""
logger.debug("Creating window for frame (scale = %d)", self._scale)
if root:
self._root = tk.Toplevel(master=root)
self._launched_from_app = True
else:
self._root = tk.Tk()
if not self._regions:
self._regions = [initial_point_list(self._frame_size)]
# Withdraw root window until we're done adding everything to avoid visual flicker.
self._root.withdraw()
self._root.option_add("*tearOff", False)
self._root.title(OWNED_WINDOW_TITLE if self._launched_from_app else WINDOW_TITLE)
register_icon(self._root)
self._root.resizable(True, True)
self._root.minsize(width=320, height=240)
self._editor_canvas = tk.Canvas(
self._root,
)
self._root.columnconfigure(0, weight=1)
self._root.rowconfigure(0, weight=1)
self._editor_canvas.grid(row=0, column=0, sticky="nsew")
self._editor_scroll = (
AutoHideScrollbar(self._root, command=self._editor_canvas.xview, orient=tk.HORIZONTAL),
AutoHideScrollbar(self._root, command=self._editor_canvas.yview, orient=tk.VERTICAL),
)
self._editor_canvas["xscrollcommand"] = self._editor_scroll[0].set
self._editor_canvas["yscrollcommand"] = self._editor_scroll[1].set
self._editor_scroll[0].grid(row=1, column=0, sticky="ew")
self._editor_scroll[1].grid(row=0, column=1, sticky="ns")
ttk.Separator(self._root).grid(row=2, column=0, columnspan=2, sticky="ew")
def set_scale(val: str):
new_val = round(float(val))
if self._scale != new_val:
self._scale = new_val
# Disable resize since we are probably using the mouse to control this widget.
self._rescale(allow_resize=False)
frame = tk.Frame(self._root)
frame.grid(row=3, column=0, sticky="ew", columnspan=2)
frame.columnconfigure(4, weight=1)
frame.rowconfigure(0, weight=1)
self._scale_widget = ttk.Scale(
frame,
orient=tk.HORIZONTAL,
length=200,
from_=MAX_DOWNSCALE_FACTOR,
to=MIN_DOWNSCALE_FACTOR,
command=set_scale,
value=self._scale,
)
tk.Label(frame, text="Active Region", anchor=tk.W).grid(
row=0, column=0, sticky=tk.W, padx=8.0
)
self._region_selector = ttk.Combobox(
frame,
values=list(f"Shape {i + 1}" for i in range(len(self._regions))),
width=12,
justify=tk.CENTER,
)
self._region_selector.state(["readonly"])
self._region_selector.grid(row=0, column=1, sticky="w")
self._region_selector.current(0)
self._region_selector.bind("<<ComboboxSelected>>", lambda _: self._on_shape_select())
# Looks weird when the widget takes focus, but still seems to work when we redirect focus to
# the root.
self._region_selector.bind("<FocusIn>", lambda _: self._root.focus())
ttk.Button(frame, text="Toggle Mask", command=self._toggle_mask).grid(
row=0, column=10, padx=8.0
)
self._scale_widget.grid(row=0, column=9, sticky="e", padx=8.0)
tk.Label(frame, text="Zoom", anchor=tk.E).grid(row=0, column=8, sticky=tk.E, padx=(0, 8.0))
ttk.Separator(self._root).grid(row=4, column=0, columnspan=2, sticky="ew")
video_frame = tk.Frame(self._root)
video_frame.grid(row=5, column=0, sticky="ew", columnspan=2)
video_frame.columnconfigure(1, weight=1)
self._video_pos_label = tk.Label(video_frame, text=f"0 / {self._num_frames}", anchor=tk.W)
self._video_pos_label.grid(row=0, column=0, sticky=tk.W, padx=8.0)
self._video_seek_widget = ttk.Scale(
video_frame,
orient=tk.HORIZONTAL,
length=200,
from_=0,
to=self._num_frames - 1,
command=self._seek,
value=0,
)
self._video_seek_widget.grid(row=0, column=1, sticky="ew", padx=8.0)
self._bind_mouse()
self._bind_keyboard()
self._create_menubar()
self._rescale(draw=False)
self._redraw = True
self._draw()
self._root.deiconify()
logger.info(f"Region editor active. Press {KEYBIND_HELP} to show controls.")
self._root.focus()
self._root.grab_release()
if not self._launched_from_app:
self._root.mainloop()
return self._should_scan
def _create_menubar(self):
root_menu = tk.Menu(self._root)
file_menu = tk.Menu(root_menu)
root_menu.add_cascade(menu=file_menu, label="File", underline=0)
if not self._launched_from_app:
file_menu.add_command(
label="Start Scan",
command=lambda: self._close(True),
accelerator=KEYBIND_START_SCAN,
underline=1,
)
file_menu.add_separator()
file_menu.add_command(
label="Open Regions...",
command=self._prompt_load,
accelerator=KEYBIND_LOAD,
underline=0,
)
file_menu.add_command(
label=SAVE_REGIONS if self._settings.save_path else SAVE_REGIONS_PROMPT,
command=self._prompt_save,
accelerator=KEYBIND_SAVE,
underline=0,
)
file_menu.add_separator()
file_menu.add_command(
label="Close" if self._launched_from_app else "Quit",
command=lambda: self._close(False),
accelerator=KEYBIND_QUIT,
)
edit_menu = tk.Menu(root_menu)
root_menu.add_cascade(menu=edit_menu, label="Edit", underline=0)
edit_menu.add_command(
label="Undo", command=self._undo, accelerator=KEYBIND_UNDO, underline=0
)
edit_menu.add_command(
label="Redo", command=self._redo, accelerator=KEYBIND_REDO, underline=0
)
view_menu = tk.Menu(root_menu)
root_menu.add_cascade(menu=view_menu, label="View", underline=0)
view_menu.add_command(
label="Mask Mode", command=self._toggle_mask, accelerator=KEYBIND_MASK, underline=0
)
view_menu.add_command(
label="Antialiasing",
command=self._toggle_antialiasing,
accelerator=KEYBIND_TOGGLE_AA,
underline=0,
)
view_menu.add_separator()
view_menu.add_command(
label="Zoom In",
command=lambda: self._adjust_downscale(-1),
accelerator=KEYBIND_DOWNSCALE_DEC,
underline=0,
)
view_menu.add_command(
label="Zoom Out",
command=lambda: self._adjust_downscale(1),
accelerator=KEYBIND_DOWNSCALE_INC,
underline=3,
)
help_menu = tk.Menu(root_menu)
root_menu.add_cascade(menu=help_menu, label="Help", underline=0)
help_menu.add_command(
label="Show Controls", command=self._show_help, accelerator=KEYBIND_HELP, underline=5
)
# TODO: Link to local copy of documentation included with distributions instead where
# possible. This isn't always possible with how Python manages package resources, so we
# might need to probe the directory the application was run from.
help_menu.add_command(
label="Online Manual",
command=lambda: webbrowser.open_new_tab("www.dvr-scan.com/guide"),
underline=0,
)
help_menu.add_command(
label="Join Discord Chat",
command=lambda: webbrowser.open_new_tab("https://discord.gg/69kf6f2Exb"),
underline=5,
)
help_menu.add_separator()
help_menu.add_command(
label="About DVR-Scan", command=lambda: AboutWindow().show(root=self._root), underline=0
)
self._edit_menu = edit_menu
self._root["menu"] = root_menu
self._update_ui_state()
def _show_help(self):
if self._controls_window is None:
self._controls_window = tk.Toplevel(master=self._root)
self._controls_window.withdraw()
self._controls_window.title("Controls")
self._controls_window.resizable(True, True)
self._controls_window.transient(self._root)
def dismiss():
self._controls_window.destroy()
self._controls_window = None
self._root.focus()
self._controls_window.protocol("WM_DELETE_WINDOW", dismiss)
self._controls_window.attributes("-topmost", True)
self._controls_window.bind("<Destroy>", lambda _: dismiss())
self._controls_window.bind("<FocusIn>", lambda _: self._root.focus())
def handle_escape(_: tk.Event):
self._controls_window.destroy()
self._controls_window = None
self._controls_window.bind("<Escape>", handle_escape)
regions = ttk.Labelframe(self._controls_window, text="Regions", padding=8.0)
regions.columnconfigure(0, weight=1)
regions.columnconfigure(1, weight=1)
ttk.Label(regions, text="Add Point").grid(row=0, column=0, sticky="w")
ttk.Label(regions, text="Left Click\nKeyboard: +", justify=tk.RIGHT).grid(
row=0, column=1, sticky="e"
)
ttk.Label(regions, text="Remove Point").grid(row=1, column=0, sticky="w")
ttk.Label(regions, text="Right Click\nKeyboard: -", justify=tk.RIGHT).grid(
row=1, column=1, sticky="e"
)
ttk.Label(regions, text="Move Point").grid(row=2, column=0, sticky="w")
ttk.Label(regions, text="Left Click + Drag").grid(row=2, column=1, sticky="e")
ttk.Label(regions, text="").grid(row=4, column=0, sticky="w")
ttk.Label(regions, text="Add/Remove Shape").grid(row=5, column=0, sticky="w")
ttk.Label(
regions,
text=f"Mouse: Right Click\nKeyboard: {KEYBIND_REGION_ADD}",
justify=tk.RIGHT,
).grid(row=5, column=1, sticky="e")
ttk.Label(regions, text="Active Shape").grid(row=6, column=0, sticky="w")
ttk.Label(
regions,
text="Mouse: Right Click\nKeyboard: "
f"{KEYBIND_REGION_NEXT}/{KEYBIND_REGION_PREVIOUS}",
justify=tk.RIGHT,
).grid(row=6, column=1, sticky="e")
viewport = ttk.Labelframe(self._controls_window, text="Viewport", padding=8.0)
viewport.columnconfigure(0, weight=1)
viewport.columnconfigure(1, weight=1)
ttk.Label(viewport, text="Zoom").grid(row=0, column=0, sticky="w")
ttk.Label(
viewport,
text=f"Mouse: {ACCELERATOR_KEY} + Scroll\nKeyboard: "
f"{KEYBIND_DOWNSCALE_INC}/{KEYBIND_DOWNSCALE_DEC}",
justify=tk.RIGHT,
).grid(row=0, column=1, sticky="e")
ttk.Label(viewport, text="Move/Pan").grid(row=3, column=0, sticky="w")
ttk.Label(viewport, text=f"{ACCELERATOR_KEY} + Left Click").grid(
row=3, column=1, sticky="e"
)
ttk.Label(viewport, text="").grid(row=4, column=0, sticky="w")
ttk.Label(viewport, text="Toggle Mask Mode").grid(row=5, column=0, sticky="w")
ttk.Label(viewport, text=f"Keyboard: {KEYBIND_MASK}").grid(row=5, column=1, sticky="e")
ttk.Label(viewport, text="Toggle Antialiasing").grid(row=6, column=0, sticky="w")
ttk.Label(viewport, text=f"Keyboard: {KEYBIND_TOGGLE_AA}").grid(
row=6, column=1, sticky="e"
)
general = ttk.Labelframe(self._controls_window, text="General", padding=8.0)
general.columnconfigure(0, weight=1)
general.columnconfigure(1, weight=1)
ttk.Label(general, text="Start Scan").grid(row=0, column=0, sticky="w")
ttk.Label(general, text=f"Keyboard: {KEYBIND_START_SCAN}").grid(
row=0, column=1, sticky="e"
)
ttk.Label(general, text="Quit").grid(row=1, column=0, sticky="w")
ttk.Label(general, text=f"Keyboard: {KEYBIND_QUIT}").grid(row=1, column=1, sticky="e")
ttk.Label(general, text="Show Help").grid(row=2, column=0, sticky="w")
ttk.Label(general, text=f"Keyboard: {KEYBIND_HELP}").grid(row=2, column=1, sticky="e")
ttk.Label(general, text="Copy Scan Command").grid(row=3, column=0, sticky="w")
ttk.Label(general, text=f"Keyboard: {KEYBIND_COPY_COMMAND}").grid(
row=3, column=1, sticky="e"
)
regions.grid(row=0, sticky="nsew", padx=8.0, pady=8.0)
viewport.grid(row=1, sticky="nsew", padx=8.0, pady=8.0)
general.grid(row=2, sticky="nsew", padx=8.0, pady=8.0)
self._controls_window.columnconfigure(0, weight=1)
self._controls_window.rowconfigure(0, weight=1)
self._controls_window.rowconfigure(1, weight=1)
self._controls_window.rowconfigure(2, weight=1)
self._controls_window.update()
self._controls_window.deiconify()
self._root.focus()
def _adjust_downscale(self, amount: int, allow_resize=True):
# scale is clamped to MIN_DOWNSCALE_FACTOR/MAX_DOWNSCALE_FACTOR.
scale = self._scale + amount
self._scale = min(MAX_DOWNSCALE_FACTOR, max(MIN_DOWNSCALE_FACTOR, scale))
self._scale_widget.set(self._scale)
self._rescale(allow_resize=allow_resize)
def _prompt_save(self):
"""Save region data, prompting the user if a save path wasn't specified by command line."""
if self._save():
return
save_path = tkinter.filedialog.asksaveasfilename(
title=SAVE_TITLE,
filetypes=[("Region File", "*.txt")],
defaultextension=".txt",
confirmoverwrite=True,
parent=self._root,
)
if save_path:
self._save(save_path)
def prompt_save_on_scan(self, root: ty.Optional[tk.Widget] = None):
"""Saves any changes that weren't persisted, prompting the user if a path wasn't specified.
Returns True if we should quit the program, False if we should not quit."""
# Don't prompt user if changes are already saved.
if self._persisted:
return True
# Don't prompt the user if they lanched the region editor from the CLI and already specified
# a path to save the region data to.
if self._save():
return True
should_save = tkinter.messagebox.askyesnocancel(
title=PROMPT_TITLE,
message=PROMPT_MESSAGE,
icon=tkinter.messagebox.WARNING,
parent=root if root else self._root,
)
if should_save is None: