-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflowQt.py
More file actions
3975 lines (3589 loc) · 149 KB
/
Copy pathflowQt.py
File metadata and controls
3975 lines (3589 loc) · 149 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
#!/usr/bin/env python3
# cineFlow -- degraining small-gauge film scans
#
# Copyright (C) 2026 Dr. R. Henkel
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version. See <https://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Commercial licences are available for use cases the GPL does not cover.
# Enquiries: license@pixelcircus.com
import os
import sys
import time
try:
import importlib
importlib.import_module("torch")
except Exception:
pass
try:
import PyQt5
except ImportError:
sys.exit(
"\n[flowQt] PyQt5 is not installed.\n"
" pip install PyQt5\n"
)
_PQ_PLUGINS = ""
for _sub in ("Qt5", "Qt"):
_plug = os.path.join(os.path.dirname(PyQt5.__file__), _sub, "plugins")
if os.path.isdir(_plug):
_PQ_PLUGINS = _plug
os.environ["QT_PLUGIN_PATH"] = _plug
os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = os.path.join(_plug, "platforms")
break
from PyQt5.QtCore import (QEvent, QObject, QPoint, QRect, QRectF,
Qt, QThread, QTimer, pyqtSignal, pyqtSlot)
from PyQt5.QtGui import (QColor, QCursor, QImage, QPainter,
QPalette, QPen)
from PyQt5.QtWidgets import (QApplication, QComboBox,
QDialog, QDoubleSpinBox, QFileDialog,
QGridLayout,
QGroupBox, QHBoxLayout, QLabel, QLineEdit,
QListWidget, QListWidgetItem, QMainWindow,
QMessageBox,
QPushButton, QSizePolicy, QSlider, QSpinBox,
QStatusBar, QStyle, QStyleOptionSlider,
QTabWidget, QVBoxLayout, QWidget)
import flowcore as fcore
import cv2
import numpy as np
if _PQ_PLUGINS:
os.environ["QT_PLUGIN_PATH"] = _PQ_PLUGINS
os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = os.path.join(_PQ_PLUGINS, "platforms")
else:
os.environ.pop("QT_PLUGIN_PATH", None)
os.environ.pop("QT_QPA_PLATFORM_PLUGIN_PATH", None)
from cineflow_defaults import SCENE_PARAMS, VERSION
from cineio import scene_config_path, safe_name, imwrite_unicode
import cineio
_SCRIPT = os.path.basename(__file__)
__version__ = VERSION
def _u8(x):
return np.clip(x * 255.0, 0, 255).astype(np.uint8)
def _rgb(d):
return cv2.cvtColor(_u8(d), cv2.COLOR_RGB2BGR)
RESULT_VIEW = "output"
VIRTUAL_VIEWS = {
"flow_fw_rel": "flow_fw",
"warped_flow_bw_rel": "warped_flow_bw",
}
def data_key(view):
return VIRTUAL_VIEWS.get(view, view)
MODE_DEPENDENT_VIEWS = ("trust_mean", "tex_weight", "sharp_gate")
def _unit(d):
return fcore.norm(d, 0, 1)
DISPLAY = {
RESULT_VIEW: _rgb,
"output_best": _rgb,
"output_dustA": _rgb,
"input": _rgb,
"nbr_warped": _rgb,
"nbr_warped_trust": _rgb,
"trust_geo": _unit,
"trust_photo": _unit,
"trust_mean": _unit,
"trust_mean_best": _unit,
"trust_mean_dustA": _unit,
"trust_mean_dustB": _unit,
"tex_weight": _unit,
"sharp_gate": _unit,
"flow_fw": lambda d: fcore.flow_hsv(d),
"warped_flow_bw": lambda d: fcore.flow_hsv(d),
"flow_fw_rel": lambda d: fcore.flow_hsv_rel(d),
"warped_flow_bw_rel": lambda d: fcore.flow_hsv_rel(d),
"output_dustB": _rgb,
}
FLOW_DT_SIGN = {
"flow_fw": +1,
"flow_fw_rel": +1,
"warped_flow_bw": -1,
"warped_flow_bw_rel": -1,
}
def display_fn(key, cfg):
fn = DISPLAY.get(key, _rgb)
sign = FLOW_DT_SIGN.get(key)
if sign is None:
return fn
dt = sign * int(cfg.get("_neighbor_offset", 1))
if dt == 0:
return fn
hue = fcore._FLOW_HUE_OFFSET + (90.0 if dt < 0 else 0.0)
scale = abs(dt)
if key.endswith("_rel"):
return lambda d: fcore.flow_hsv_rel(
d, maxmag=fcore.FLOW_MAXMAG_REL * scale, hue_offset=hue)
return lambda d: fcore.flow_hsv(
d, maxmag=fcore.FLOW_MAXMAG * scale, hue_offset=hue)
VIEW_LABEL = {
RESULT_VIEW: "Output",
"output_best": "Output (best)",
"output_dustA": "Output (dustA)",
"output_dustB": "Output (dustB)",
"input": "Input",
"nbr_warped": "Neighbour (warped)",
"nbr_warped_trust": "Neighbour \u00d7 trust",
"trust_geo": "Trust geo",
"trust_photo": "Trust photo",
"trust_mean": "Trust",
"trust_mean_best": "Trust (best)",
"trust_mean_dustA": "Trust (dustA)",
"trust_mean_dustB": "Trust (dustB)",
"tex_weight": "Texture weight",
"sharp_gate": "Sharp gate",
"flow_fw": "Flow fw (HSV)",
"warped_flow_bw": "Warped flow bw (HSV)",
"flow_fw_rel": "Flow fw relative (HSVz)",
"warped_flow_bw_rel": "Warped flow bw relative (HSVz)",
}
def view_label(key):
return VIEW_LABEL.get(key, key)
VIEW_GROUPS = [
("Output", [RESULT_VIEW]),
("Input", ["input"]),
("Neighbour (diag)", ["nbr_warped", "nbr_warped_trust"]),
("Trust", ["trust_mean", "trust_geo", "trust_photo"]),
("Sharpening", ["tex_weight", "sharp_gate"]),
("Flow", ["flow_fw", "flow_fw_rel",
"warped_flow_bw", "warped_flow_bw_rel"]),
]
VIEW_ORDER = [k for _grp, keys in VIEW_GROUPS for k in keys]
TIER_NAMES = {0: "Flow+Warp", 1: "Trust", 2: "Fusion", 3: "Sharpening"}
class Job:
def __init__(self, tier, idx, files, cfg, backend, view, data=None,
serial=0):
self.tier = tier
self.idx = idx
self.files = files
self.cfg = dict(cfg)
self.backend = backend
self.view = view
self.data = data
self.serial = serial
_SETTINGS = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"flowQt_settings.json")
def _platform_key():
if sys.platform.startswith("win"):
return "win"
try:
with open("/proc/version") as f:
if "microsoft" in f.read().lower():
return "wsl"
except Exception:
pass
return "linux"
_PLAT = _platform_key()
_DIR_KEY = f"input_dir_{_PLAT}"
def _sidebar_urls():
from PyQt5.QtCore import QUrl
urls = [QUrl.fromLocalFile(os.path.expanduser("~"))]
if _PLAT in ("wsl", "linux"):
if os.path.isdir("/mnt"):
urls.insert(0, QUrl.fromLocalFile("/mnt"))
else:
import string
for d in string.ascii_uppercase:
p = f"{d}:\\"
if os.path.isdir(p):
urls.append(QUrl.fromLocalFile(p))
return urls
DEFAULT_CYCLE = [
"input",
RESULT_VIEW,
"nbr_warped_trust",
"nbr_warped",
"flow_fw_rel",
"trust_geo",
"trust_photo",
"trust_mean",
"sharp_gate",
]
_bad_offset = sorted(k for k in fcore._OFFSET_DEPENDENT_KEYS if k not in DISPLAY)
_bad_cycle = sorted(k for k in DEFAULT_CYCLE
if k != RESULT_VIEW and k not in DISPLAY)
_bad_order = sorted(k for k in VIEW_ORDER if k not in DISPLAY)
_bad_label = sorted(k for k in DISPLAY if k not in VIEW_LABEL)
if _bad_offset or _bad_cycle or _bad_order or _bad_label:
raise KeyError(
"view keys and DISPLAY do not agree -- "
f"offset-abhaengig: {_bad_offset}, Zyklus: {_bad_cycle}, "
f"Reihenfolge: {_bad_order}, ohne Beschriftung: {_bad_label}")
def _load_settings():
s = {_DIR_KEY: "", "start_frame": 0, "cycle": list(DEFAULT_CYCLE),
"slots": {}}
if os.path.isfile(_SETTINGS):
try:
import json
with open(_SETTINGS) as f:
s.update(json.load(f))
except Exception as e:
fcore.log("settings", f"{_SETTINGS} not readable ({e!r}) -- using defaults")
_RENAMED = {
"center": "input",
"result": "output",
"result_best": "output_best",
"result_dustA": "output_dustA",
"result_dustB": "output_dustB",
"trust_center_dustA": "trust_input_dustA",
"trust_center_dustB": "trust_input_dustB",
}
_raw = list(s.get("cycle", []))
_moved = sorted({v for v in _raw if v in _RENAMED})
if _moved:
s["cycle"] = [_RENAMED.get(v, v) for v in _raw]
fcore.log("settings", "cycle keys migrated to the Input/Output names: "
+ ", ".join(f"{v} -> {_RENAMED[v]}" for v in _moved))
cyc = [v for v in s.get("cycle", []) if v in DISPLAY]
dropped = [v for v in s.get("cycle", []) if v not in DISPLAY]
if dropped:
fcore.log("settings", f"unknown view keys dropped from cycle: "
f"{', '.join(dropped)}")
cyc = [k for i, k in enumerate(cyc) if i == 0 or k != cyc[i - 1]]
s["cycle"] = cyc or list(DEFAULT_CYCLE)
if not isinstance(s.get("slots"), dict):
s["slots"] = {}
return s
def _atomic_write_json(path, obj):
tmp = path + ".tmp"
import json
with open(tmp, "w") as f:
json.dump(obj, f, indent=2)
f.write("\n")
os.replace(tmp, path)
def _save_settings(s):
try:
_atomic_write_json(_SETTINGS, s)
except Exception as e:
fcore.log("settings", f"could not write: {e!r}")
class SlotButton(QPushButton):
leftClicked = pyqtSignal()
rightClicked = pyqtSignal()
shiftRightClicked = pyqtSignal()
ctrlRightClicked = pyqtSignal()
def mousePressEvent(self, ev):
if ev.button() == Qt.RightButton:
mods = ev.modifiers()
if mods & Qt.ShiftModifier:
self.shiftRightClicked.emit()
elif mods & Qt.ControlModifier:
self.ctrlRightClicked.emit()
else:
self.rightClicked.emit()
elif ev.button() == Qt.LeftButton:
self.leftClicked.emit()
else:
super().mousePressEvent(ev)
class CycleEditor(QDialog):
changed = pyqtSignal(list)
def __init__(self, cycle, parent=None):
super().__init__(parent)
self.setWindowTitle("Edit views")
self.resize(600, 440)
outer = QVBoxLayout(self)
outer.addWidget(QLabel(
"<span style='color:#9aa0a6'>The order is the control: "
"Up/Down steps through this sequence.<br>"
"Views may appear more than once — e.g. 'N' between "
"several pairs, to keep flipping back to the reference.</span>"))
inner = QWidget()
outer.addWidget(inner, 1)
lay = QHBoxLayout(inner)
lv = QVBoxLayout()
lv.addWidget(QLabel("sequence (up/down to reorder):"))
self.lst = QListWidget()
for i, v in enumerate(cycle):
self.lst.addItem(self._mk_item(v, num=i + 1))
lv.addWidget(self.lst, 1)
bl = QHBoxLayout()
for txt, fn in (("up", self._up), ("down", self._down),
("remove", self._rm)):
b = QPushButton(txt); b.clicked.connect(fn); bl.addWidget(b)
lv.addLayout(bl)
lay.addLayout(lv, 1)
rv = QVBoxLayout()
rv.addWidget(QLabel("available (double-click to append):"))
self.avail = QListWidget()
for grp, keys in VIEW_GROUPS:
self.avail.addItem(self._mk_header(grp))
for v in keys:
self.avail.addItem(self._mk_item(v))
self.avail.itemDoubleClicked.connect(self._add)
rv.addWidget(self.avail, 1)
b = QPushButton("add \u2192")
b.clicked.connect(lambda: self._add(self.avail.currentItem()))
rv.addWidget(b)
lay.addLayout(rv, 1)
close = QPushButton("done")
close.clicked.connect(self.accept)
outer.addWidget(close)
def _emit(self):
self._renumber()
self.changed.emit([(self.lst.item(i).data(Qt.UserRole)
or self.lst.item(i).text())
for i in range(self.lst.count())])
@staticmethod
def _mk_header(text):
it = QListWidgetItem(text.upper())
it.setFlags(Qt.NoItemFlags)
f = it.font(); f.setBold(True); f.setPointSize(max(7, f.pointSize() - 1))
it.setFont(f)
it.setForeground(QColor("#7d838b"))
return it
@staticmethod
def _mk_item(key, num=None):
label = view_label(key)
if num is not None:
label = f"{num}. {label}" if num <= 9 else f" {label}"
it = QListWidgetItem(label)
it.setData(Qt.UserRole, key)
it.setToolTip(key)
return it
def _renumber(self):
for i in range(self.lst.count()):
it = self.lst.item(i)
key = it.data(Qt.UserRole)
label = view_label(key)
it.setText(f"{i+1}. {label}" if i < 9 else f" {label}")
def _add(self, item):
if item:
key = item.data(Qt.UserRole)
if not key:
return
self.lst.addItem(self._mk_item(key))
self._emit()
def _rm(self):
r = self.lst.currentRow()
if r >= 0 and self.lst.count() > 1:
self.lst.takeItem(r)
self._emit()
def _move(self, d):
r = self.lst.currentRow()
n = r + d
if 0 <= r < self.lst.count() and 0 <= n < self.lst.count():
it = self.lst.takeItem(r)
self.lst.insertItem(n, it)
self.lst.setCurrentRow(n)
self._emit()
def _up(self): self._move(-1)
def _down(self): self._move(+1)
class Status(QWidget):
def __init__(self):
super().__init__()
self._t0 = None
self._what = ""
self._phase = 0.0
self.last_what = None
self.last_ms = None
self.last_reason = ""
self.backend = ""
self.backend_warn = False
self._timer = QTimer(self)
self._timer.timeout.connect(self._tick)
self._relayout()
def _relayout(self):
fm = self.fontMetrics()
self._row = fm.height()
self._gap = max(2, fm.height() // 5)
self._pad = max(4, fm.height() // 3)
self._lab_w = fm.horizontalAdvance("Flow") + fm.height()
self._bar_h = max(3, fm.height() // 5)
rows = 1
need = (self._pad
+ 2 * (self._row + self._gap)
+ self._bar_h + self._gap
+ self._row
+ rows * (self._row + self._gap)
+ self._pad)
self.setMinimumHeight(need)
def changeEvent(self, ev):
if ev.type() == QEvent.FontChange:
self._relayout()
super().changeEvent(ev)
def start(self, what):
self._what = what
self._t0 = time.time()
self._timer.start(60)
self.update()
def finish(self, what, msec, reason):
self._timer.stop()
self._t0 = None
self.last_what = what
self.last_ms = msec
self.last_reason = reason
self.update()
def stop(self):
self._timer.stop()
self._t0 = None
self.update()
def set_state(self, backend=None, backend_warn=False):
if backend is not None: self.backend = backend
self.backend_warn = backend_warn
self.update()
def _tick(self):
self._phase = (self._phase + 0.06) % 1.0
self.update()
def paintEvent(self, ev):
p = QPainter(self)
p.setRenderHint(QPainter.Antialiasing)
w = self.width()
row, gap, pad = self._row, self._gap, self._pad
y = pad
if self._t0 is not None:
el = time.time() - self._t0
p.setPen(QPen(QColor(205, 210, 216)))
p.drawText(QRect(pad, y, w - 2 * pad, row), Qt.AlignLeft,
f"computing {self._what} \u2026")
p.setPen(QPen(QColor(140, 145, 152)))
p.drawText(QRect(pad, y, w - 2 * pad, row), Qt.AlignRight,
f"{el:.1f} s")
y += row + gap
bw = int(w * 0.28)
x = int((w + bw) * self._phase) - bw
p.fillRect(pad, y, w - 2 * pad, self._bar_h, QColor(44, 45, 49))
p.fillRect(max(pad, x), y,
min(bw, w - pad - max(pad, x)), self._bar_h,
QColor(78, 132, 190))
y += self._bar_h + gap
elif self.last_what is not None:
p.setPen(QPen(QColor(205, 210, 216)))
p.drawText(QRect(pad, y, w - 2 * pad, row), Qt.AlignLeft,
self.last_what)
ms = self.last_ms
txt = f"{ms/1000:.2f} s" if ms >= 1000 else f"{ms:.0f} ms"
p.setPen(QPen(QColor(216, 154, 60) if ms >= 1000
else QColor(150, 200, 150)))
p.drawText(QRect(pad, y, w - 2 * pad, row), Qt.AlignRight, txt)
y += row + gap
if self.last_reason:
p.setPen(QPen(QColor(125, 131, 139)))
p.drawText(QRect(pad, y, w - 2 * pad, row), Qt.AlignLeft,
f"\u2190 {self.last_reason}")
y += row + gap
else:
p.setPen(QPen(QColor(110, 115, 122)))
p.drawText(QRect(pad, y, w - 2 * pad, row), Qt.AlignLeft, "ready")
y += row + gap
y += gap
p.fillRect(pad, y, w - 2 * pad, 1, QColor(58, 58, 62))
y += gap + gap
rows = []
if self.backend:
rows.append(("Flow", self.backend, self.backend_warn))
lw = self._lab_w
for label, val, warn in rows:
p.setPen(QPen(QColor(125, 131, 139)))
p.drawText(QRect(pad, y, lw, row), Qt.AlignLeft, label)
p.setPen(QPen(QColor(255, 122, 69) if warn else QColor(190, 196, 203)))
p.drawText(QRect(pad + lw, y, w - pad - lw - pad, row),
Qt.AlignLeft, val)
y += row + gap
class Worker(QObject):
done = pyqtSignal(object, object, int)
started_job = pyqtSignal(str, int)
failed = pyqtSignal(str)
def __init__(self):
super().__init__()
self._latest = 0
def set_latest(self, serial):
self._latest = serial
@pyqtSlot(object)
def run(self, job):
if job.serial < self._latest:
return
try:
t0 = time.time()
_name = TIER_NAMES[job.tier]
if job.tier == fcore._TIER_FLOW and job.view == "input":
_name = "Load image"
self.started_job.emit(_name, job.tier)
if job.tier == fcore._TIER_FLOW:
data = fcore.compute_flow_trust(job.idx, job.files, job.cfg,
job.backend, active_view=job.view)
elif job.tier == fcore._TIER_TRUST:
data = fcore.compute_trust(job.data, job.cfg)
elif job.tier == fcore._TIER_FUSION:
data = fcore.compute_fusion(job.data, job.cfg)
else:
data = fcore.compute_e(job.data, job.cfg)
if job.serial < self._latest:
return
job.msec = (time.time() - t0) * 1000.0
self.done.emit(data, job, job.serial)
except Exception as e:
import traceback
traceback.print_exc()
self.failed.emit(f"{type(e).__name__}: {e}")
_FOREIGN_VIDEO = (".m4v", ".mxf", ".mts", ".webm", ".wmv", ".mpg", ".mpeg")
class Canvas(QLabel):
panned = pyqtSignal()
def __init__(self):
super().__init__()
self.setMinimumSize(480, 360)
self.setAlignment(Qt.AlignCenter)
self.setStyleSheet("background:#0a0a0b;")
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.setMouseTracking(True)
self.setAcceptDrops(True)
self._img = None
self._ref = None
self.view_key = ""
self.zoom_i = 0
self._last_zoom_i = 2
self.split_mode = 0
self.split_x = 0.5
self._pan = QPoint(0, 0)
self._drag = None
self._drag_split = False
self._drop_hint = False
self._message = None
dropped = pyqtSignal(str)
droppedConfig = pyqtSignal(str)
toggleZoom = pyqtSignal()
zoomStep = pyqtSignal(int)
zoomInfo = pyqtSignal()
ZOOM_LEVELS = [0.0, 1.0, 2.0, 4.0, 8.0]
ZOOM_NAMES = ["Fit", "1x", "2x", "4x", "8x"]
@staticmethod
def _config_from_mime(mime):
if not mime.hasUrls():
return None
for u in mime.urls():
p = u.toLocalFile()
if p and os.path.isfile(p) and p.lower().endswith(".json"):
return p
return None
@staticmethod
def _dir_from_mime(mime):
if not mime.hasUrls():
return None
for u in mime.urls():
p = u.toLocalFile()
if not p:
continue
if os.path.isdir(p):
return p
if fcore.is_video(p):
return p
if os.path.isfile(p):
ext = os.path.splitext(p)[1].lower()
if ext in _FOREIGN_VIDEO:
return None
return os.path.dirname(p)
return None
@staticmethod
def classify_drop(mime):
c = Canvas._config_from_mime(mime)
if c:
return "config", c
p = Canvas._dir_from_mime(mime)
if p:
return "scene", p
return None, None
def dragEnterEvent(self, ev):
if self.classify_drop(ev.mimeData())[0]:
ev.setDropAction(Qt.CopyAction)
ev.accept()
self.set_drop_hint(True)
else:
ev.ignore()
def dragMoveEvent(self, ev):
if self.classify_drop(ev.mimeData())[0]:
ev.setDropAction(Qt.CopyAction)
ev.accept()
else:
ev.ignore()
def dragLeaveEvent(self, ev):
self.set_drop_hint(False)
def dropEvent(self, ev):
self.set_drop_hint(False)
kind, p = self.classify_drop(ev.mimeData())
if kind == "config":
ev.acceptProposedAction()
self.droppedConfig.emit(p)
elif kind == "scene":
ev.acceptProposedAction()
self.dropped.emit(p)
else:
ev.ignore()
def set_drop_hint(self, on):
self._drop_hint = bool(on)
self.update()
def resizeEvent(self, ev):
super().resizeEvent(ev)
box = getattr(self, "_overlay_box", None)
if box is not None and not box.isHidden():
box.move(12, max(12, self.height() - box.height() - 12))
if self.is_fit():
self.zoomInfo.emit()
def set_overlay(self, box):
self._overlay_box = box
def set_images(self, img, ref=None, view_key="", clear_ref=False):
self._img = img
self._message = None
if ref is not None:
self._ref = ref
elif clear_ref:
self._ref = None
if view_key:
self.view_key = view_key
if self.is_fit():
self.zoomInfo.emit()
self.update()
def show_message(self, text):
self._img = None
self._message = text
self.update()
def is_fit(self):
return self.ZOOM_LEVELS[self.zoom_i] == 0.0
def dpr(self):
try:
return float(self.devicePixelRatioF())
except Exception:
return 1.0
def scale(self):
if self._img is None:
return 1.0
h, w = self._img.shape[:2]
z = self.ZOOM_LEVELS[self.zoom_i]
if z == 0.0:
if w <= 0 or h <= 0:
return 1.0
return min(self.width() / w, self.height() / h)
return z / self.dpr()
def effective_zoom(self):
return self.scale() * self.dpr()
def _view_origin(self):
if self._img is None or self.is_fit():
return 0.0, 0.0
h, w = self._img.shape[:2]
s = self.scale()
vis_w, vis_h = self.width() / s, self.height() / s
x = min(max(self._pan.x(), 0.0), max(0.0, w - vis_w))
y = min(max(self._pan.y(), 0.0), max(0.0, h - vis_h))
return x, y
def _fit_offset(self):
if self._img is None:
return 0.0, 0.0
h, w = self._img.shape[:2]
s = self.scale()
return (max(0.0, self.width() - w * s) / 2.0,
max(0.0, self.height() - h * s) / 2.0)
def img_from_screen(self, x, y):
if self._img is None:
return 0.0, 0.0
s = self.scale()
ox, oy = self._view_origin()
fx, fy = self._fit_offset()
return ox + (x - fx) / s, oy + (y - fy) / s
def screen_from_img(self, x, y):
if self._img is None:
return 0.0, 0.0
s = self.scale()
ox, oy = self._view_origin()
fx, fy = self._fit_offset()
return (x - ox) * s + fx, (y - oy) * s + fy
def zoom_to(self, i, anchor=None):
i = max(0, min(len(self.ZOOM_LEVELS) - 1, int(i)))
if i == self.zoom_i:
return
if anchor is not None and self._img is not None:
ax, ay = self.img_from_screen(anchor.x(), anchor.y())
self.zoom_i = i
if not self.is_fit():
s = self.scale()
self._pan = QPoint(int(round(ax - anchor.x() / s)),
int(round(ay - anchor.y() / s)))
else:
self.zoom_i = i
if not self.is_fit():
self._last_zoom_i = self.zoom_i
self.update()
def _compose(self):
if self._img is None:
return None
img = self._img
if self.split_mode and self._ref is not None:
ref = self._ref
if ref.shape[:2] != img.shape[:2]:
ref = cv2.resize(ref, (img.shape[1], img.shape[0]))
out = img.copy()
xs = int(np.clip(self.split_x, 0.02, 0.98) * img.shape[1])
if self.split_mode == 1:
out[:, :xs] = ref[:, :xs]
else:
out[:, xs:] = ref[:, xs:]
cv2.line(out, (xs, 0), (xs, img.shape[0]), (0, 220, 255), 2)
return out
return img
def paintEvent(self, ev):
p = QPainter(self)
p.fillRect(self.rect(), Qt.black)
if self._drop_hint:
pen = QPen(QColor(78, 132, 190), 3, Qt.DashLine)
p.setPen(pen)
p.drawRect(self.rect().adjusted(6, 6, -7, -7))
img = self._compose()
if img is None:
if self._message:
p.setPen(QPen(QColor(216, 154, 60)))
f = p.font(); f.setPointSize(12); p.setFont(f)
p.drawText(self.rect(), Qt.AlignCenter, self._message)
else:
p.setPen(QPen(QColor(120, 126, 134)))
f = p.font(); f.setPointSize(13); p.setFont(f)
p.drawText(self.rect().adjusted(0, -18, 0, -18), Qt.AlignCenter,
"Drag a scene folder into this area")
p.setPen(QPen(QColor(84, 89, 96)))
f.setPointSize(10); p.setFont(f)
p.drawText(self.rect().adjusted(0, 18, 0, 18), Qt.AlignCenter,
"... or use the Load buttons above")
return
h, w = img.shape[:2]
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
qim = QImage(rgb.data, w, h, 3 * w, QImage.Format_RGB888)
s = self.scale()
ox, oy = self._view_origin()
if not self.is_fit():
self._pan = QPoint(int(round(ox)), int(round(oy)))
sw = min(w - ox, self.width() / s)
sh = min(h - oy, self.height() / s)
fx, fy = self._fit_offset()
srect = QRectF(ox, oy, sw, sh)
drect = QRectF(fx, fy, sw * s, sh * s)
hard = (not self.is_fit()) and self.ZOOM_LEVELS[self.zoom_i] >= 2.0
p.setRenderHint(QPainter.SmoothPixmapTransform, not hard)
p.drawImage(drect, qim, srect)
SPLIT_GRAB = 12
def _split_screen_x(self):
if self._img is None:
return None
h, w = self._img.shape[:2]
sx, _ = self.screen_from_img(self.split_x * w, 0.0)
return int(round(sx))
def mousePressEvent(self, ev):
if ev.button() != Qt.LeftButton:
return
if self.split_mode:
sx = self._split_screen_x()
if sx is not None and abs(ev.x() - sx) <= self.SPLIT_GRAB:
self._drag_split = True
self._set_split_from_x(ev.x())
return
if not self.is_fit():
self._drag = ev.pos()
def mouseMoveEvent(self, ev):
if self._drag_split:
self._set_split_from_x(ev.x())
elif self._drag is not None:
d = ev.pos() - self._drag
s = self.scale() or 1.0
self._pan -= QPoint(int(round(d.x() / s)), int(round(d.y() / s)))
self._drag = ev.pos()
self.update()
elif self.split_mode:
sx = self._split_screen_x()
near = sx is not None and abs(ev.x() - sx) <= self.SPLIT_GRAB
self.setCursor(Qt.SplitHCursor if near else
(Qt.OpenHandCursor if not self.is_fit()
else Qt.ArrowCursor))
def mouseReleaseEvent(self, ev):
self._drag = None
self._drag_split = False
def mouseDoubleClickEvent(self, ev):
if ev.button() != Qt.LeftButton:
super().mouseDoubleClickEvent(ev)
return
self._drag = None
self._drag_split = False
self.toggleZoom.emit()
def wheelEvent(self, ev):
dy = ev.angleDelta().y()
if dy == 0:
return
self.zoomStep.emit(1 if dy > 0 else -1)
ev.accept()
def _set_split_from_x(self, x):
if self._img is None:
return
w = self._img.shape[1]
xi, _ = self.img_from_screen(x, 0.0)
self.split_x = float(np.clip(xi / max(w, 1), 0.02, 0.98))
self.update()
class TextureHistogram(QWidget):
def __init__(self):
super().__init__()
self.setMinimumHeight(90)
self._hist = None
self._pcts = {}
self._texref = None
def set_texture(self, tex):
if tex is None:
self._hist = None
self._pcts = {}
else:
t = np.asarray(tex, dtype=np.float32).ravel()
t = t[np.isfinite(t)]
if t.size == 0:
self._hist = None
self._pcts = {}
else:
hi = float(np.percentile(t, 99.5)) or 1e-6
counts, edges = np.histogram(t, bins=64, range=(0.0, hi))
self._hist = (counts.astype(np.float64), edges)
self._pcts = {p: float(np.percentile(t, p))
for p in (50, 90, 99)}
self.update()
def set_texref(self, v):
self._texref = float(v) if v is not None else None
self.update()
def percentile(self, p):
return self._pcts.get(p)
def paintEvent(self, ev):
from PyQt5.QtGui import QPainter, QColor, QPen
p = QPainter(self)
p.setRenderHint(QPainter.Antialiasing, False)
w, h = self.width(), self.height()
p.fillRect(0, 0, w, h, QColor("#232327"))
if self._hist is None:
p.setPen(QColor("#7d838b"))
p.drawText(6, h // 2, "no texture data (compute first)")
return
counts, edges = self._hist
lo, hi = float(edges[0]), float(edges[-1])
span = max(hi - lo, 1e-9)
mx = float(counts.max()) or 1.0
n = len(counts)
p.setPen(Qt.NoPen)
p.setBrush(QColor("#4a6d8c"))
for i, c in enumerate(counts):
bh = int(round((c / mx) * (h - 16)))
x0 = int(round(i * w / n))
x1 = int(round((i + 1) * w / n))
p.drawRect(x0, h - bh, max(1, x1 - x0 - 1), bh)
def xof(val):
return int(round((float(val) - lo) / span * w))
for pc, col in ((50, "#7d838b"), (90, "#c8a45c"), (99, "#8c6a4a")):
v = self._pcts.get(pc)
if v is None or not (lo <= v <= hi):
continue
x = xof(v)
p.setPen(QPen(QColor(col), 1, Qt.DashLine))
p.drawLine(x, 0, x, h)
p.setPen(QColor(col))
p.drawText(min(x + 3, w - 26), 11, f"p{pc}")
if self._texref is not None:
x = xof(self._texref)
if 0 <= x <= w:
p.setPen(QPen(QColor("#e0554a"), 2))
p.drawLine(x, 0, x, h)