forked from ElvinC/gyroflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gyroflow.py
2253 lines (1657 loc) · 88.6 KB
/
gyroflow.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Main file containing UI code"""
import sys
import random
import cv2
import os
import numpy as np
from PySide2 import QtCore, QtWidgets, QtGui
from _version import __version__
from vidgear.gears.helper import get_valid_ffmpeg_path
import calibrate_video
import time
import nonlinear_stretch
import urllib.request
import json
import re
import calibrate_video
import subprocess
import bundled_images
import stabilizer
# https://en.wikipedia.org/wiki/List_of_digital_camera_brands
cam_company_list = ["GoPro", "Runcam", "Insta360", "Caddx", "Foxeer", "DJI", "RED", "Canon", "Arri",
"Blackmagic", "Casio", "Nikon", "Panasonic", "Sony", "Jvc", "Olympus", "Fujifilm",
"Phone"]
class Launcher(QtWidgets.QWidget):
"""Main launcher with options to open different utilities
"""
def __init__(self):
super().__init__()
self.setWindowTitle("Gyroflow {} Launcher".format(__version__))
self.setWindowIcon(QtGui.QIcon(':/media/icon.png'))
self.setFixedWidth(450)
# image
pixmap = QtGui.QPixmap(':/media/logo_rev0_w400.png')
self.top_logo = QtWidgets.QLabel()
self.top_logo.setPixmap(pixmap.scaled(400,450,QtCore.Qt.KeepAspectRatio))
self.top_logo.setAlignment(QtCore.Qt.AlignCenter)
self.text = QtWidgets.QLabel("<h2>Version {}</h2>".format(__version__))
self.text.setAlignment(QtCore.Qt.AlignCenter)
self.calibrator_button = QtWidgets.QPushButton("Camera Calibrator")
self.calibrator_button.setMinimumSize(300,50)
self.calibrator_button.setStyleSheet("font-size: 14px;")
self.calibrator_button.setToolTip("Use this to generate camera calibration files")
self.stabilizer_barebone_button = QtWidgets.QPushButton("Video Stabilizer")
self.stabilizer_barebone_button.setMinimumSize(300,50)
self.stabilizer_barebone_button.setStyleSheet("font-size: 14px;")
self.stabilizer_button = QtWidgets.QPushButton("Video Stabilizer (Fancy version)")
self.stabilizer_button.setMinimumSize(300,50)
self.stabilizer_button.setEnabled(False)
self.stabilizer_button.setStyleSheet("font-size: 14px;")
self.stretch_button = QtWidgets.QPushButton("Non-linear Stretch")
self.stretch_button.setMinimumSize(300,50)
self.stretch_button.setStyleSheet("font-size: 14px;")
self.version_button = QtWidgets.QPushButton("Check for updates")
self.version_button.setMinimumSize(300,50)
self.version_button.setStyleSheet("font-size: 14px;")
self.footer = QtWidgets.QLabel('''Developed by Elvin | <a href='http://gyroflow.xyz/'>gyroflow.xyz</a> | <a href='https://github.com/ElvinC/gyroflow'>Git repo</a> | <a href='http://gyroflow.xyz/donate'>Donate</p>''')
self.footer.setOpenExternalLinks(True)
self.footer.setAlignment(QtCore.Qt.AlignCenter)
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.top_logo)
self.layout.addWidget(self.text)
self.layout.addWidget(self.calibrator_button)
self.layout.addWidget(self.stabilizer_barebone_button)
self.layout.addWidget(self.stabilizer_button)
self.layout.addWidget(self.stretch_button)
self.layout.addWidget(self.version_button)
self.layout.addWidget(self.footer)
self.setLayout(self.layout)
self.calibrator_button.clicked.connect(self.open_calib_util)
self.stabilizer_button.clicked.connect(self.open_stab_util)
self.stabilizer_barebone_button.clicked.connect(self.open_stab_util_barebone)
self.stretch_button.clicked.connect(self.open_stretch_util)
self.version_button.clicked.connect(self.check_version)
# Placeholder for utility windows.
self.calibrator_utility = None
self.stabilizer_utility = None
self.stabilizer_utility_barebone = None
self.stretch_utility = None
def open_calib_util(self):
"""Open the camera calibration utility in a new window
"""
# Only open if not already open
if self.calibrator_utility:
if self.calibrator_utility.isVisible():
return
self.calibrator_utility = CalibratorUtility()
self.calibrator_utility.resize(500, 500)
self.calibrator_utility.show()
def open_stab_util(self):
"""Open video stabilization utility in new window
"""
# Only open if not already open
if self.stabilizer_utility:
if self.stabilizer_utility.isVisible():
return
self.stab_utility = StabUtility()
self.stab_utility.resize(500, 500)
self.stab_utility.show()
def open_stab_util_barebone(self):
if self.stabilizer_utility_barebone:
if self.stabilizer_utility_barebone.isVisible():
return
self.stabilizer_utility_barebone = StabUtilityBarebone()
self.stabilizer_utility_barebone.resize(500, 800)
self.stabilizer_utility_barebone.show()
def open_stretch_util(self):
"""Open non-linear stretch utility in new window
"""
# Only open if not already open
if self.stretch_utility:
if self.calibrator_utility.isVisible():
return
self.stretch_utility = StretchUtility()
self.stretch_utility.resize(500, 500)
self.stretch_utility.show()
def check_version(self):
with urllib.request.urlopen("https://api.github.com/repos/elvinc/gyroflow/releases") as url:
releases = json.loads(url.read())
newest_version = releases[0]["tag_name"]
new = re.match("(\d+).(\d+).(\d+).*", newest_version).groups()
current = re.match("(\d+).(\d+).(\d+).*", __version__).groups()
extra = ""
diff = [int(A) - int(B) for A,B in zip(new,current)]
val = diff[0] if diff[0] != 0 else diff[1] if diff[1] != 0 else diff[2] if diff[2] != 0 else 0
print(val)
if newest_version.strip() == __version__.strip():
extra = "Not much to see here:"
elif val > 0:
extra = "Oh look, there's a shiny new update. <a href='https://github.com/ElvinC/gyroflow'>Here's a link just for you.</a> "
elif val < 0:
extra = "Looks like somebody is time traveling..."
else:
extra = "Spot the difference:"
msg_window = QtWidgets.QMessageBox(self)
msg_window.setIcon(QtWidgets.QMessageBox.Information)
msg_window.setText("{}<br>Your version: <b>{}</b>, newest release: <b>{}</b>".format(extra, __version__, newest_version))
msg_window.setWindowTitle("Version check")
msg_window.show()
class VideoThread(QtCore.QThread):
changePixmap = QtCore.Signal(QtGui.QImage)
def __init__(self, parent, frame_pos_update = None):
"""Video Thread
Args:
parent ([type]):
frame_pos_update (function, optional): Function to call for frame num update. Defaults to None.
"""
super().__init__(parent)
self.playing = False
self.update_once = False
self.next_frame = False
self.frame_pos_update = frame_pos_update
self.map1s = []
self.map2s = []
# Draw vertical lines at given coords
self.vert_line_coords = []
self.cap = None
self.frame = None
# used for scaling
self.max_width = 1280
def run(self):
"""
Run the videoplayer using the thread
"""
self.cap = cv2.VideoCapture()
while True:
if self.playing or self.next_frame:
self.next_frame = False
ret, self.frame = self.cap.read()
if ret:
time.sleep(1/24)
self.update_frame()
elif self.update_once:
self.update_once = False
self.update_frame()
else:
time.sleep(1/10)
def update_frame(self):
"""Opdate the current video frame shown
"""
if self.frame is None:
return
# https://stackoverflow.com/a/55468544/6622587
rgbImage = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)
for i in range(len(self.map1s)):
# apply the maps using linear interpolation for now
rgbImage = cv2.remap(rgbImage, self.map1s[i], self.map2s[i], cv2.INTER_LINEAR)
for line_pos in self.vert_line_coords:
cv2.line(rgbImage,(int(line_pos), 0),(int(line_pos),rgbImage.shape[0]),(255,255,0),2)
if rgbImage.shape[1] > self.max_width:
new_height = int(self.max_width/rgbImage.shape[1] * rgbImage.shape[0])
rgbImage = cv2.resize(rgbImage, (self.max_width, new_height))
h, w, ch = rgbImage.shape
bytesPerLine = ch * w
convertToQtFormat = QtGui.QImage(rgbImage.data, w, h, bytesPerLine, QtGui.QImage.Format_RGB888)
self.changePixmap.emit(convertToQtFormat.copy())
this_frame_num = int(self.cap.get(cv2.CAP_PROP_POS_FRAMES))
if this_frame_num % 5 == 0 and self.frame_pos_update:
self.frame_pos_update(this_frame_num)
# based on https://robonobodojo.wordpress.com/2018/07/01/automatic-image-sizing-with-pyside/
# and https://stackoverflow.com/questions/44404349/pyqt-showing-video-stream-from-opencv/44404713
class VideoPlayer(QtWidgets.QLabel):
def __init__(self, img = "placeholder.jpg"):
super(VideoPlayer, self).__init__()
self.setFrameStyle(QtWidgets.QFrame.StyledPanel)
self.pixmap = QtGui.QPixmap(img)
#self.setPixmap(self.pixmap)
self.setSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding)
def paintEvent(self, event = None):
size = self.size()
painter = QtGui.QPainter(self)
point = QtCore.QPoint(0,0)
if not self.pixmap.isNull():
scaledPix = self.pixmap.scaled(size, QtCore.Qt.KeepAspectRatio, transformMode = QtCore.Qt.SmoothTransformation)
point.setX((size.width() - scaledPix.width())/2)
point.setY((size.height() - scaledPix.height())/2)
# print point.x(), ' ', point.y()
painter.drawPixmap(point, scaledPix)
class VideoPlayerWidget(QtWidgets.QWidget):
def __init__(self):
"""Widget containing videoplayer and controls
"""
QtWidgets.QWidget.__init__(self)
self.player = VideoPlayer("placeholder.jpg")
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.player)
#self.setStyleSheet("background-color:rgb(100, 100, 100);")
self.setLayout(self.layout)
self.control_bar = QtWidgets.QWidget()
self.control_layout = QtWidgets.QHBoxLayout()
self.control_bar.setLayout(self.control_layout)
self.play_button = QtWidgets.QPushButton("Play")
self.play_button.clicked.connect(self.toggle_play)
# seek bar with value from 0-200
self.time_slider = QtWidgets.QSlider(QtCore.Qt.Horizontal, self)
self.time_slider.setMinimum(0)
self.time_slider.setValue(0)
self.seek_ticks = 200
self.time_slider.setMaximum(self.seek_ticks)
self.time_slider.setSingleStep(1)
self.time_slider.setTickInterval(1)
#self.time_slider.valueChanged.connect(self.seek)
self.time_slider.sliderPressed.connect(self.start_seek)
self.time_slider.sliderReleased.connect(self.stop_seek)
self.is_seeking = False
self.was_playing_before = False
self.last_seek_time = time.time()
self.control_layout.addWidget(self.play_button)
self.control_layout.addWidget(self.time_slider)
self.layout.addWidget(self.control_bar)
self.frame_width = 1920 # placeholder
self.frame_height = 1080
self.num_frames = 0
# initialize thread for video player with frame update function
self.thread = VideoThread(self, self.set_seek_frame)
self.thread.changePixmap.connect(self.setImage)
self.thread.start()
@QtCore.Slot(QtGui.QImage)
def setImage(self, image):
pixmap = QtGui.QPixmap.fromImage(image)
self.player.pixmap = pixmap
self.player.setPixmap(pixmap)
def set_cv_frame(self, frame):
self.thread.frame = frame
self.thread.update_once = True
def stop(self):
self.thread.playing = False
self.play_button.setText("Play")
def play(self):
self.thread.playing = True
self.play_button.setText("Pause")
def toggle_play(self):
#self.video_viewer.thread.cap.set(cv2.CAP_PROP_POS_MSEC, 2)
self.thread.playing = not self.thread.playing
self.play_button.setText("Pause" if self.thread.playing else "Play")
def set_video_path(self, path):
self.stop()
self.thread.cap.release()
self.thread.cap = cv2.VideoCapture(path)
self.frame_width = self.thread.cap.get(cv2.CAP_PROP_FRAME_WIDTH)
self.frame_height = self.thread.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
self.num_frames = self.thread.cap.get(cv2.CAP_PROP_FRAME_COUNT)
def reset_maps(self):
self.thread.map1s = []
self.thread.map2s = []
def add_maps(self, map1, map2):
self.thread.map1s.append(map1)
self.thread.map2s.append(map2)
def reset_lines(self):
self.thread.vert_line_coords = []
def add_vert_lines(self, xcoord):
self.thread.vert_line_coords.append(xcoord)
def update_frame(self):
self.thread.update_once = True
def next_frame(self):
self.thread.next_frame = True
def start_seek(self):
self.is_seeking = True
self.was_playing_before = self.thread.playing
self.stop()
def stop_seek(self):
self.is_seeking = False
self.seek()
def seek(self):
"""Handler for seek bar update
"""
# only update when not dragging:
#if self.is_seeking:
# return
# prevent video overread using 0.2 sec cooldown
timenow = time.time()
if (timenow - self.last_seek_time) < 0.5:
return
self.last_seek_time = timenow
was_playing = self.thread.playing
if was_playing:
self.stop()
print(self.time_slider.value())
selected_frame = int(self.num_frames * self.time_slider.value() / self.seek_ticks)
print(selected_frame)
self.thread.cap.set(cv2.CAP_PROP_POS_FRAMES, selected_frame)
# restart if it was playing
if (was_playing or self.was_playing_before) and not self.is_seeking:
self.play()
else:
self.next_frame()
def set_seek_frame(self, frame_pos):
"""Set the seek bar position to match frame
Args:
frame (int): Frame number
"""
# only update when slider not in use
if self.is_seeking:
return
slider_val = int(frame_pos * self.seek_ticks / (max(self.num_frames, 1)))
# update slider without triggering valueChange
self.time_slider.blockSignals(True)
self.time_slider.setValue(slider_val)
self.time_slider.blockSignals(False)
def destroy_thread(self):
self.thread.terminate()
class Form(QtWidgets.QDialog):
def __init__(self, parent=None, title="Dialog"):
super(Form, self).__init__(parent)
self.setWindowTitle(title)
self.setWindowIcon(QtGui.QIcon(':/media/icon.png'))
def addField(description = "Write something:", id = "field1"):
self.edit = QLineEdit("Write my name here..")
self.button = QPushButton("Show Greetings")
class CalibratorUtility(QtWidgets.QMainWindow):
def __init__(self):
"""Qt window containing camera calibration utility
"""
super().__init__()
calib_input = QtWidgets.QInputDialog.getText(self, "Calibration setting","Calibration chessboard size. w, h",
QtWidgets.QLineEdit.Normal, "9,6")[0].split(",")
try:
w, h = [min(max(int(x), 1),30) for x in calib_input]
self.chessboard_size = (w,h)
except:
print("setting to default 9,6 pattern")
self.chessboard_size = (9,6)
# Initialize UI
self.setWindowTitle("Gyroflow Calibrator {}".format(__version__))
self.setWindowIcon(QtGui.QIcon(':/media/icon.png'))
self.main_widget = QtWidgets.QWidget()
self.layout = QtWidgets.QHBoxLayout()
self.main_widget.setLayout(self.layout)
# left half of screen with player/buttons
self.left_side_widget = QtWidgets.QWidget()
self.left_layout = QtWidgets.QVBoxLayout()
self.left_side_widget.setLayout(self.left_layout)
self.layout.addWidget(self.left_side_widget)
# right half of screen with export options
self.right_side_widget = QtWidgets.QWidget()
self.right_layout = QtWidgets.QVBoxLayout()
self.right_side_widget.setLayout(self.right_layout)
self.right_side_widget.setFixedWidth(250)
self.right_layout.setAlignment(QtCore.Qt.AlignTop)
self.layout.addWidget(self.right_side_widget)
# video player with controls
self.video_viewer = VideoPlayerWidget()
self.left_layout.addWidget(self.video_viewer)
self.setCentralWidget(self.main_widget)
# control buttons for stretching [Safe area slider] [expo slider] [X]View safe area [recompute maps] [render to file]
self.calib_controls = QtWidgets.QWidget()
self.calib_controls_layout = QtWidgets.QHBoxLayout()
self.calib_controls.setLayout(self.calib_controls_layout)
self.button_height = 40
self.calib_msg = ""
# button for recomputing image stretching maps
self.add_frame_button = QtWidgets.QPushButton("Add current frame")
self.add_frame_button.setMinimumHeight(self.button_height)
self.add_frame_button.clicked.connect(self.add_current_frame)
self.calib_controls_layout.addWidget(self.add_frame_button)
# button for recomputing image stretching maps
self.del_frame_button = QtWidgets.QPushButton("Remove last frame")
self.del_frame_button.setMinimumHeight(self.button_height)
self.del_frame_button.clicked.connect(self.remove_frame)
self.calib_controls_layout.addWidget(self.del_frame_button)
# button for recomputing image stretching maps
self.process_frames_btn = QtWidgets.QPushButton("Process loaded frames")
self.process_frames_btn.setMinimumHeight(self.button_height)
self.process_frames_btn.setEnabled(False)
self.process_frames_btn.clicked.connect(self.calibrate_frames)
self.calib_controls_layout.addWidget(self.process_frames_btn)
# info text box
self.info_text = QtWidgets.QLabel("No frames loaded")
self.calib_controls_layout.addWidget(self.info_text)
self.fov_scale = 1.4
# slider for adjusting FOV
self.fov_text = QtWidgets.QLabel("FOV scale ({}):".format(self.fov_scale))
self.fov_slider = QtWidgets.QSlider(QtCore.Qt.Horizontal, self)
self.fov_slider.setMinimum(8)
self.fov_slider.setValue(14)
self.fov_slider.setMaximum(30)
self.fov_slider.setMaximumWidth(300)
self.fov_slider.setSingleStep(1)
self.fov_slider.setTickInterval(1)
self.fov_slider.valueChanged.connect(self.fov_changed)
self.fov_slider.sliderReleased.connect(self.update_preview)
self.calib_controls_layout.addWidget(self.fov_text)
self.calib_controls_layout.addWidget(self.fov_slider)
# checkbox to preview lens distortion correction
self.preview_toggle_btn = QtWidgets.QCheckBox("Toggle lens correction: ")
self.preview_toggle_btn.setLayoutDirection(QtCore.Qt.RightToLeft)
self.preview_toggle_btn.stateChanged.connect(self.update_preview)
self.preview_toggle_btn.setEnabled(False)
self.calib_controls_layout.addWidget(self.preview_toggle_btn)
# add control bar to main layout
self.left_layout.addWidget(self.calib_controls)
# Right layout: Export settings
text = QtWidgets.QLabel("<h2>Preset parameters</h2>")
text.setAlignment(QtCore.Qt.AlignCenter)
self.right_layout.addWidget(text)
self.right_layout.addWidget(QtWidgets.QLabel("Camera brand (*):"))
completer = QtWidgets.QCompleter(cam_company_list)
completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
# create line edit and add auto complete
self.cam_company_input = QtWidgets.QLineEdit()
self.cam_company_input.setCompleter(completer)
self.cam_company_input.setPlaceholderText(random.choice(cam_company_list + ["Potatocam"]))
self.right_layout.addWidget(self.cam_company_input)
self.right_layout.addWidget(QtWidgets.QLabel("Camera make (*)"))
self.cam_model_input = QtWidgets.QLineEdit()
self.cam_model_input.setPlaceholderText(random.choice(["Hero5", "D5100", "Hero8", "Komodo", "Pocket Cinema", "2000D", "Alexa", "Potato"])) # Don't ask...
self.right_layout.addWidget(self.cam_model_input)
self.right_layout.addWidget(QtWidgets.QLabel("Lens name (leave blank if not relevant)"))
self.cam_lens_input = QtWidgets.QLineEdit()
self.cam_lens_input.setPlaceholderText(random.choice(["Nikkor 35mm f/1.8G", "EF-S 18-55mm", "Sigma 16mm F/1.4", "E 50mm F/1.8 OSS", "Tamron 17-28mm f/2.8 Di", "Rokinon 14mm T3.1", "PotatoGlass deluxe"]))
self.right_layout.addWidget(self.cam_lens_input)
self.right_layout.addWidget(QtWidgets.QLabel("Recording setting (*)"))
self.cam_setting_input = QtWidgets.QLineEdit()
self.cam_setting_input.setPlaceholderText("2160p 4by3 wide")
self.right_layout.addWidget(self.cam_setting_input)
self.right_layout.addWidget(QtWidgets.QLabel("Other relevant note"))
self.cam_note_input = QtWidgets.QLineEdit()
self.cam_note_input.setPlaceholderText(random.choice(["ND filter installed", "Bad light conditions", "Test calibration, don't use", "Can't believe potatoes can record video"]))
self.right_layout.addWidget(self.cam_note_input)
self.right_layout.addWidget(QtWidgets.QLabel("Name of calibrator (*)"))
self.calibrated_by_input = QtWidgets.QLineEdit()
self.calibrated_by_input.setText("Anonymous")
self.right_layout.addWidget(self.calibrated_by_input)
# button for exporting preset
self.export_button = QtWidgets.QPushButton("Export preset file")
self.export_button.setMinimumHeight(self.button_height)
self.export_button.clicked.connect(self.save_preset_file)
self.export_button.setEnabled(False)
self.right_layout.addWidget(self.export_button, alignment=QtCore.Qt.AlignBottom)
# file menu setup
menubar = self.menuBar()
filemenu = menubar.addMenu('&File')
# https://joekuan.wordpress.com/2015/09/23/list-of-qt-icons/
icon = self.style().standardIcon(QtWidgets.QStyle.SP_DirOpenIcon)
self.open_file = QtWidgets.QAction(icon, 'Open file', self)
self.open_file.setShortcut("Ctrl+O")
self.open_file.triggered.connect(self.open_file_func)
filemenu.addAction(self.open_file)
icon = self.style().standardIcon(QtWidgets.QStyle.SP_FileLinkIcon)
self.open_preset = QtWidgets.QAction(icon, 'Open calibration preset', self)
self.open_preset.triggered.connect(self.open_preset_func)
filemenu.addAction(self.open_preset)
icon = self.style().standardIcon(QtWidgets.QStyle.SP_FileDialogListView)
self.show_chessboard = QtWidgets.QAction(icon, 'Calibration target', self)
self.show_chessboard.triggered.connect(self.chessboard_func)
filemenu.addAction(self.show_chessboard)
self.chess_window = None
self.statusBar()
self.infile_path = ""
self.show()
self.main_widget.show()
# initialize instance of calibrator class
self.calibrator = calibrate_video.FisheyeCalibrator(chessboard_size=self.chessboard_size)
def open_file_func(self):
"""Open file using Qt filedialog
"""
path = QtWidgets.QFileDialog.getOpenFileName(self, "Open video file", filter="Video (*.mp4 *.avi *.mov *.MP4 *.AVI *.MOV)")
self.infile_path = path[0]
self.video_viewer.set_video_path(path[0])
self.video_viewer.next_frame()
# reset calibrator and info
self.calibrator = calibrate_video.FisheyeCalibrator(chessboard_size=self.chessboard_size)
self.update_calib_info()
def open_preset_func(self):
"""Load in calibration preset
"""
path = QtWidgets.QFileDialog.getOpenFileName(self, "Open preset file", filter="JSON preset (*.json)")
if (len(path[0]) == 0):
print("No file selected")
return
self.calibrator.load_calibration_json(path[0])
self.update_calib_info()
def chessboard_func(self):
"""Function to show the calibration chessboard in a new window
"""
print("Showing chessboard")
board_width = self.chessboard_size[0]
board_height = self.chessboard_size[1]
self.chess_window = QtWidgets.QWidget()
self.chess_window.setWindowTitle(f"Calibration target ({board_width}x{board_height})")
self.chess_window.setStyleSheet("background-color:white;")
self.chess_layout = QtWidgets.QVBoxLayout()
self.chess_window.setLayout(self.chess_layout)
# VideoPlayer class doubles as a auto resizing image viewer
# generate chessboard pattern so no external images are needed
chess_pic = np.zeros((board_height + 3,board_width + 3), np.uint8)
# Set white squares
chess_pic[::2,::2] = 255
chess_pic[1::2,1::2] = 255
# Borders to white
chess_pic[0,:] = 255
chess_pic[-1,:]= 255
chess_pic[:,0]= 255
chess_pic[:,-1]= 255
# double size and reduce borders slightly
chess_pic = cv2.resize(chess_pic,((board_width+3)*2, (board_height+3)*2), interpolation=cv2.INTER_NEAREST)
chess_pic = chess_pic[1:-1,:]
# convert to Qt image
h, w = chess_pic.shape
convertToQtFormat = QtGui.QImage(chess_pic.data, w, h, w, QtGui.QImage.Format_Grayscale8)
# VideoPlayer doubles as a autoresiznig image viewer
chess_viewer = VideoPlayer(convertToQtFormat.copy())
self.chess_layout.addWidget(chess_viewer)
self.chess_window.resize(500, 500)
self.chess_window.show()
def closeEvent(self, event):
print("Closing now")
self.video_viewer.destroy_thread()
event.accept()
def fov_changed(self):
self.fov_scale = self.fov_slider.value()/10
self.fov_text.setText("FOV scale ({}):".format(self.fov_scale))
def save_preset_file(self):
"""save camera preset file
"""
print("Exporting preset")
# Window to set export data
cam_brand = self.cam_company_input.text()
cam_model = self.cam_model_input.text()
cam_lens = self.cam_lens_input.text()
cam_setting = self.cam_setting_input.text()
cam_note = self.cam_note_input.text()
calibrated_by = self.calibrated_by_input.text()
if not (cam_brand and cam_model and cam_setting):
self.show_error("Missing information about the camera system")
return
if not calibrated_by:
self.show_error("You went through all the trouble to make a calibration profile but don't want credit? I'll just fill in 'Anonymous' for you, but feel free to write a (nick)name or a handle instead.")
self.calibrated_by_input.setText("Anonymous")
return
calib_name = f"{cam_brand}_{cam_model}_{cam_lens}_{cam_setting}"
# make sure name works
default_file_name = calib_name.replace("@", "At") # 18-55mm@18mm -> 18-55mmAt18mm, eh works I guess
default_file_name = default_file_name.replace("/", "_").replace(".", "_").replace(" ","_") # f/1.8 -> f_1_8
default_file_name = "".join([c for c in default_file_name if c.isalpha() or c.isdigit() or c in "_-"]).rstrip()
default_file_name = default_file_name.replace("__", "_").replace("__", "_")
filename = QtWidgets.QFileDialog.getSaveFileName(self, "Export calibration preset", default_file_name,
filter="JSON preset (*.json)")
print(filename[0])
if len(filename[0]) == 0:
self.show_warning("No output file given")
return
self.calibrator.save_calibration_json(filename[0], calib_name=calib_name, camera_brand=cam_brand, camera_model=cam_model,
lens_model=cam_lens, camera_setting=cam_setting, note=cam_note, calibrated_by=calibrated_by)
def show_error(self, msg):
QtWidgets.QMessageBox.critical(self, "Something's gone awfully wrong", msg)
return
#self.err_window = QtWidgets.QMessageBox(self)
#self.err_window.setIcon(QtWidgets.QMessageBox.Warning)
#self.err_window.setText(msg)
#self.err_window.setWindowTitle("Something's gone awry")
#self.err_window.exec_()
#self.err_window.close()
def show_warning(self, msg):
QtWidgets.QMessageBox.critical(self, "Something's gone awry", msg)
def add_current_frame(self):
print("Adding frame")
ret, self.calib_msg, corners = self.calibrator.add_calib_image(self.video_viewer.thread.frame)
if ret:
self.video_viewer.set_cv_frame(cv2.drawChessboardCorners(self.video_viewer.thread.frame, self.calibrator.chessboard_size,corners,True) )
self.update_calib_info()
if self.calibrator.num_images > 0:
self.process_frames_btn.setEnabled(True)
def remove_frame(self):
"""Remove last calibration frame
"""
self.calibrator.remove_calib_image()
self.update_calib_info()
def update_calib_info(self):
""" Update the status text in the utility
"""
txt = "Good frames: {}\nProcessed frames: {}\nRMS error: {}\n{}".format(self.calibrator.num_images,
self.calibrator.num_images_used,
self.calibrator.RMS_error,
self.calib_msg)
self.info_text.setText(txt)
# enable/disable buttons
if self.calibrator.num_images > 0:
self.process_frames_btn.setEnabled(True)
else:
self.process_frames_btn.setEnabled(False)
if self.calibrator.num_images_used > 0:
self.preview_toggle_btn.setEnabled(True)
self.export_button.setEnabled(True)
else:
self.preview_toggle_btn.setChecked(False)
self.preview_toggle_btn.setEnabled(False)
self.export_button.setEnabled(False)
def calibrate_frames(self):
self.calibrator.compute_calibration()
self.update_calib_info()
self.preview_toggle_btn.setEnabled(True)
self.update_preview()
def update_preview(self):
self.video_viewer.reset_maps()
if self.preview_toggle_btn.isChecked():
img_dim = (int(self.video_viewer.frame_width), int(self.video_viewer.frame_height))
map1, map2 = self.calibrator.get_maps(fov_scale=self.fov_scale, new_img_dim=img_dim)
self.video_viewer.add_maps(map1, map2)
#map1, map2 = self.calibrator.get_rotation_map()
#self.video_viewer.add_maps(map1, map2)
self.video_viewer.update_frame()
class StretchUtility(QtWidgets.QMainWindow):
def __init__(self):
"""Qt window containing utility for nonlinear stretch
"""
super().__init__()
# Initialize UI
self.setWindowTitle("Gyroflow Stretcher {}".format(__version__))
self.setWindowIcon(QtGui.QIcon(':/media/icon.png'))
self.main_widget = QtWidgets.QWidget()
self.layout = QtWidgets.QVBoxLayout()
self.main_widget.setLayout(self.layout)
# video player with controls
self.video_viewer = VideoPlayerWidget()
self.layout.addWidget(self.video_viewer)
self.setCentralWidget(self.main_widget)
# control buttons for stretching [Safe area slider] [expo slider] [X]View safe area [recompute maps] [render to file]
self.stretch_controls = QtWidgets.QWidget()
self.stretch_controls_layout = QtWidgets.QHBoxLayout()
self.stretch_controls.setLayout(self.stretch_controls_layout)
# slider for adjusting unwarped area
self.safe_area_text = QtWidgets.QLabel("Safe area (0%):")
self.safe_area_slider = QtWidgets.QSlider(QtCore.Qt.Horizontal, self)
self.safe_area_slider.setMinimum(0)
self.safe_area_slider.setValue(0)
self.safe_area_slider.setMaximum(100)
self.safe_area_slider.setSingleStep(1)
self.safe_area_slider.setTickInterval(1)
self.safe_area_slider.valueChanged.connect(self.safe_area_changed)
self.stretch_controls_layout.addWidget(self.safe_area_text)
self.stretch_controls_layout.addWidget(self.safe_area_slider)
# slider for adjusting non linear expo
self.expo_text = QtWidgets.QLabel("Stretch expo (2.0):")
self.expo_slider = QtWidgets.QSlider(QtCore.Qt.Horizontal, self)
self.expo_slider.setMinimum(10)
self.expo_slider.setValue(20)
self.expo_slider.setMaximum(40)
self.expo_slider.setSingleStep(1)
self.expo_slider.setTickInterval(1)
self.expo_slider.valueChanged.connect(self.stretch_expo_changed)
self.stretch_controls_layout.addWidget(self.expo_text)
self.stretch_controls_layout.addWidget(self.expo_slider)
# checkmark for showing untouched area
self.show_safe_check = QtWidgets.QCheckBox("Show safe area: ")
self.show_safe_check.setLayoutDirection(QtCore.Qt.RightToLeft)
self.show_safe_check.stateChanged.connect(self.safe_check_change)
self.stretch_controls_layout.addWidget(self.show_safe_check)
# output size choice
self.out_size_text = QtWidgets.QLabel("Output size: ")
self.stretch_controls_layout.addWidget(self.out_size_text)
self.out_width_control = QtWidgets.QSpinBox(self)
self.out_width_control.setMinimum(16)
self.out_width_control.setMaximum(7680) # 8K max is probably fine
self.out_width_control.setValue(1920)
self.out_width_control.valueChanged.connect(self.update_out_size)
self.stretch_controls_layout.addWidget(self.out_width_control)
# output size choice
self.out_height_control = QtWidgets.QSpinBox(self)
self.out_height_control.setMinimum(9)
self.out_height_control.setMaximum(4320)
self.out_height_control.setValue(1080)
self.out_height_control.valueChanged.connect(self.update_out_size)
self.stretch_controls_layout.addWidget(self.out_height_control)
# button for recomputing image stretching maps
self.recompute_stretch_button = QtWidgets.QPushButton("Apply settings")
self.recompute_stretch_button.clicked.connect(self.recompute_stretch)
self.stretch_controls_layout.addWidget(self.recompute_stretch_button)
# button for recomputing image stretching maps
self.export_button = QtWidgets.QPushButton("Export video")
self.export_button.clicked.connect(self.export_video)
self.stretch_controls_layout.addWidget(self.export_button)
# add control bar to main layout
self.layout.addWidget(self.stretch_controls)
# file menu setup
menubar = self.menuBar()
filemenu = menubar.addMenu('&File')
# https://joekuan.wordpress.com/2015/09/23/list-of-qt-icons/
icon = self.style().standardIcon(QtWidgets.QStyle.SP_DirOpenIcon)
self.open_file = QtWidgets.QAction(icon, 'Open file', self)
self.open_file.setShortcut("Ctrl+O")
self.open_file.triggered.connect(self.open_file_func)
filemenu.addAction(self.open_file)
self.statusBar()
self.infile_path = ""
self.show()