/
ScreenCapture.py
1553 lines (1323 loc) · 68.8 KB
/
ScreenCapture.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
import os
import unittest
import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import logging
#
# ScreenCapture
#
class ScreenCapture(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
self.parent.title = "Screen Capture"
self.parent.categories = ["Utilities"]
self.parent.dependencies = []
self.parent.contributors = ["Andras Lasso (PerkLab Queen's University)"]
self.parent.helpText = """
This module captures image sequences and videos
from dynamic contents shown in 3D and slice viewers.
"""
self.parent.helpText += self.getDefaultModuleDocumentationLink()
self.parent.acknowledgementText = """
This work was was funded by Cancer Care Ontario
and the Ontario Consortium for Adaptive Interventions in Radiation Oncology (OCAIRO)
"""
#
# ScreenCaptureWidget
#
VIEW_SLICE = 'slice'
VIEW_3D = '3d'
AXIS_YAW = 0
AXIS_PITCH = 1
class ScreenCaptureWidget(ScriptedLoadableModuleWidget):
"""Uses ScriptedLoadableModuleWidget base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def setup(self):
ScriptedLoadableModuleWidget.setup(self)
self.logic = ScreenCaptureLogic()
self.logic.logCallback = self.addLog
self.viewNodeType = None
self.animationMode = None
self.createdOutputFile = None
self.snapshotIndex = 0 # this counter is used for determining file names for single-image snapshots
self.snapshotOutputDir = None
self.snapshotFileNamePattern = None
# Instantiate and connect widgets ...
#
# Input area
#
self.inputCollapsibleButton = ctk.ctkCollapsibleButton()
self.inputCollapsibleButton.text = "Input"
self.layout.addWidget(self.inputCollapsibleButton)
inputFormLayout = qt.QFormLayout(self.inputCollapsibleButton)
# Input view selector
self.viewNodeSelector = slicer.qMRMLNodeComboBox()
self.viewNodeSelector.nodeTypes = ["vtkMRMLSliceNode", "vtkMRMLViewNode"]
self.viewNodeSelector.addEnabled = False
self.viewNodeSelector.removeEnabled = False
self.viewNodeSelector.noneEnabled = False
self.viewNodeSelector.showHidden = False
self.viewNodeSelector.showChildNodeTypes = False
self.viewNodeSelector.setMRMLScene( slicer.mrmlScene )
self.viewNodeSelector.setToolTip("This slice or 3D view will be updated during capture."
"Only this view will be captured unless 'Capture of all views' option in output section is enabled." )
inputFormLayout.addRow("Master view: ", self.viewNodeSelector)
self.captureAllViewsCheckBox = qt.QCheckBox(" ")
self.captureAllViewsCheckBox.checked = False
self.captureAllViewsCheckBox.setToolTip("If checked, all views will be captured. If unchecked then only the selected view will be captured.")
inputFormLayout.addRow("Capture all views:", self.captureAllViewsCheckBox)
# Mode
self.animationModeWidget = qt.QComboBox()
self.animationModeWidget.setToolTip("Select the property that will be adjusted")
inputFormLayout.addRow("Animation mode:", self.animationModeWidget)
# Slice start offset position
self.sliceStartOffsetSliderLabel = qt.QLabel("Start sweep offset:")
self.sliceStartOffsetSliderWidget = ctk.ctkSliderWidget()
self.sliceStartOffsetSliderWidget.singleStep = 30
self.sliceStartOffsetSliderWidget.minimum = -100
self.sliceStartOffsetSliderWidget.maximum = 100
self.sliceStartOffsetSliderWidget.value = 0
self.sliceStartOffsetSliderWidget.setToolTip("Start slice sweep offset.")
inputFormLayout.addRow(self.sliceStartOffsetSliderLabel, self.sliceStartOffsetSliderWidget)
# Slice end offset position
self.sliceEndOffsetSliderLabel = qt.QLabel("End sweep offset:")
self.sliceEndOffsetSliderWidget = ctk.ctkSliderWidget()
self.sliceEndOffsetSliderWidget.singleStep = 5
self.sliceEndOffsetSliderWidget.minimum = -100
self.sliceEndOffsetSliderWidget.maximum = 100
self.sliceEndOffsetSliderWidget.value = 0
self.sliceEndOffsetSliderWidget.setToolTip("End slice sweep offset.")
inputFormLayout.addRow(self.sliceEndOffsetSliderLabel, self.sliceEndOffsetSliderWidget)
# 3D rotation range
self.rotationSliderLabel = qt.QLabel("Rotation range:")
self.rotationSliderWidget = ctk.ctkRangeWidget()
self.rotationSliderWidget.singleStep = 5
self.rotationSliderWidget.minimum = -180
self.rotationSliderWidget.maximum = 180
self.rotationSliderWidget.minimumValue = -180
self.rotationSliderWidget.maximumValue = 180
self.rotationSliderWidget.setToolTip("View rotation range, relative to current view orientation.")
inputFormLayout.addRow(self.rotationSliderLabel, self.rotationSliderWidget)
# 3D rotation axis
self.rotationAxisLabel = qt.QLabel("Rotation axis:")
self.rotationAxisWidget = ctk.ctkRangeWidget()
self.rotationAxisWidget = qt.QComboBox()
self.rotationAxisWidget.addItem("Yaw", AXIS_YAW)
self.rotationAxisWidget.addItem("Pitch", AXIS_PITCH)
inputFormLayout.addRow(self.rotationAxisLabel, self.rotationAxisWidget)
# Sequence browser node selector
self.sequenceBrowserNodeSelectorLabel = qt.QLabel("Sequence:")
self.sequenceBrowserNodeSelectorWidget = slicer.qMRMLNodeComboBox()
self.sequenceBrowserNodeSelectorWidget.nodeTypes = ["vtkMRMLSequenceBrowserNode"]
self.sequenceBrowserNodeSelectorWidget.addEnabled = False
self.sequenceBrowserNodeSelectorWidget.removeEnabled = False
self.sequenceBrowserNodeSelectorWidget.noneEnabled = False
self.sequenceBrowserNodeSelectorWidget.showHidden = False
self.sequenceBrowserNodeSelectorWidget.setMRMLScene( slicer.mrmlScene )
self.sequenceBrowserNodeSelectorWidget.setToolTip( "Items defined by this sequence browser will be replayed." )
inputFormLayout.addRow(self.sequenceBrowserNodeSelectorLabel, self.sequenceBrowserNodeSelectorWidget)
# Sequence start index
self.sequenceStartItemIndexLabel = qt.QLabel("Start index:")
self.sequenceStartItemIndexWidget = ctk.ctkSliderWidget()
self.sequenceStartItemIndexWidget.minimum = 0
self.sequenceStartItemIndexWidget.decimals = 0
self.sequenceStartItemIndexWidget.setToolTip("First item in the sequence to capture.")
inputFormLayout.addRow(self.sequenceStartItemIndexLabel, self.sequenceStartItemIndexWidget)
# Sequence end index
self.sequenceEndItemIndexLabel = qt.QLabel("End index:")
self.sequenceEndItemIndexWidget = ctk.ctkSliderWidget()
self.sequenceEndItemIndexWidget.minimum = 0
self.sequenceEndItemIndexWidget.decimals = 0
self.sequenceEndItemIndexWidget.setToolTip("Last item in the sequence to capture.")
inputFormLayout.addRow(self.sequenceEndItemIndexLabel, self.sequenceEndItemIndexWidget)
#
# Output area
#
self.outputCollapsibleButton = ctk.ctkCollapsibleButton()
self.outputCollapsibleButton.text = "Output"
self.layout.addWidget(self.outputCollapsibleButton)
outputFormLayout = qt.QFormLayout(self.outputCollapsibleButton)
self.outputTypeWidget = qt.QComboBox()
self.outputTypeWidget.setToolTip("Select how captured images will be saved. Video mode requires setting of ffmpeg executable path in Advanced section.")
self.outputTypeWidget.addItem("image series")
self.outputTypeWidget.addItem("video")
self.outputTypeWidget.addItem("lightbox image")
outputFormLayout.addRow("Output type:", self.outputTypeWidget)
# Number of steps value
self.numberOfStepsSliderWidget = ctk.ctkSliderWidget()
self.numberOfStepsSliderWidget.singleStep = 1
self.numberOfStepsSliderWidget.pageStep = 10
self.numberOfStepsSliderWidget.minimum = 1
self.numberOfStepsSliderWidget.maximum = 600
self.numberOfStepsSliderWidget.value = 31
self.numberOfStepsSliderWidget.decimals = 0
self.numberOfStepsSliderWidget.setToolTip("Number of images extracted between start and stop positions.")
# Single step toggle button
self.singleStepButton = qt.QToolButton()
self.singleStepButton.setText("single")
self.singleStepButton.setCheckable(True)
self.singleStepButton.toolTip = "Capture a single image of current state only.\n" + \
"New filename is generated for each captured image (no files are overwritten)."
hbox = qt.QHBoxLayout()
hbox.addWidget(self.singleStepButton)
hbox.addWidget(self.numberOfStepsSliderWidget)
outputFormLayout.addRow("Number of images:", hbox)
# Output directory selector
self.outputDirSelector = ctk.ctkPathLineEdit()
self.outputDirSelector.sizeAdjustPolicy = ctk.ctkPathLineEdit.AdjustToMinimumContentsLength
self.outputDirSelector.filters = ctk.ctkPathLineEdit.Dirs
self.outputDirSelector.settingKey = 'ScreenCaptureOutputDir'
outputFormLayout.addRow("Output directory:", self.outputDirSelector)
if not self.outputDirSelector.currentPath:
defaultOutputPath = os.path.abspath(os.path.join(slicer.app.defaultScenePath,'SlicerCapture'))
self.outputDirSelector.setCurrentPath(defaultOutputPath)
self.videoFileNameWidget = qt.QLineEdit()
self.videoFileNameWidget.setToolTip("String that defines file name and type.")
self.videoFileNameWidget.text = "SlicerCapture.avi"
self.videoFileNameWidget.setEnabled(False)
self.lightboxImageFileNameWidget = qt.QLineEdit()
self.lightboxImageFileNameWidget.setToolTip("String that defines output lightbox file name and type.")
self.lightboxImageFileNameWidget.text = "SlicerCaptureLightbox.png"
self.lightboxImageFileNameWidget.setEnabled(False)
hbox = qt.QHBoxLayout()
hbox.addWidget(self.videoFileNameWidget)
hbox.addWidget(self.lightboxImageFileNameWidget)
outputFormLayout.addRow("Output file name:", hbox)
self.videoFormatWidget = qt.QComboBox()
self.videoFormatWidget.enabled = False
self.videoFormatWidget.setSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Preferred)
for videoFormatPreset in self.logic.videoFormatPresets:
self.videoFormatWidget.addItem(videoFormatPreset["name"])
outputFormLayout.addRow("Video format:", self.videoFormatWidget)
self.videoLengthSliderWidget = ctk.ctkSliderWidget()
self.videoLengthSliderWidget.singleStep = 0.1
self.videoLengthSliderWidget.minimum = 0.1
self.videoLengthSliderWidget.maximum = 30
self.videoLengthSliderWidget.value = 5
self.videoLengthSliderWidget.suffix = "s"
self.videoLengthSliderWidget.decimals = 1
self.videoLengthSliderWidget.setToolTip("Length of the exported video in seconds (without backward steps and repeating).")
self.videoLengthSliderWidget.setEnabled(False)
outputFormLayout.addRow("Video length:", self.videoLengthSliderWidget)
self.videoFrameRateSliderWidget = ctk.ctkSliderWidget()
self.videoFrameRateSliderWidget.singleStep = 0.1
self.videoFrameRateSliderWidget.minimum = 0.1
self.videoFrameRateSliderWidget.maximum = 60
self.videoFrameRateSliderWidget.value = 5.0
self.videoFrameRateSliderWidget.suffix = "fps"
self.videoFrameRateSliderWidget.decimals = 3
self.videoFrameRateSliderWidget.setToolTip("Frame rate in frames per second.")
self.videoFrameRateSliderWidget.setEnabled(False)
outputFormLayout.addRow("Video frame rate:", self.videoFrameRateSliderWidget)
#
# Advanced area
#
self.advancedCollapsibleButton = ctk.ctkCollapsibleButton()
self.advancedCollapsibleButton.text = "Advanced"
self.advancedCollapsibleButton.collapsed = True
outputFormLayout.addRow(self.advancedCollapsibleButton)
advancedFormLayout = qt.QFormLayout(self.advancedCollapsibleButton)
self.forwardBackwardCheckBox = qt.QCheckBox(" ")
self.forwardBackwardCheckBox.checked = False
self.forwardBackwardCheckBox.setToolTip("If checked, image series will be generated playing forward and then backward.")
advancedFormLayout.addRow("Forward-backward:", self.forwardBackwardCheckBox)
self.repeatSliderWidget = ctk.ctkSliderWidget()
self.repeatSliderWidget.decimals = 0
self.repeatSliderWidget.singleStep = 1
self.repeatSliderWidget.minimum = 1
self.repeatSliderWidget.maximum = 50
self.repeatSliderWidget.value = 1
self.repeatSliderWidget.setToolTip("Number of times image series are repeated. Useful for making short videos longer for playback in software"
" that does not support looped playback.")
advancedFormLayout.addRow("Repeat:", self.repeatSliderWidget)
ffmpegPath = self.logic.getFfmpegPath()
self.ffmpegPathSelector = ctk.ctkPathLineEdit()
self.ffmpegPathSelector.sizeAdjustPolicy = ctk.ctkPathLineEdit.AdjustToMinimumContentsLength
self.ffmpegPathSelector.setCurrentPath(ffmpegPath)
self.ffmpegPathSelector.nameFilters = [self.logic.getFfmpegExecutableFilename()]
self.ffmpegPathSelector.setSizePolicy(qt.QSizePolicy.MinimumExpanding, qt.QSizePolicy.Preferred)
self.ffmpegPathSelector.setToolTip("Set the path to ffmpeg executable. Download from: https://www.ffmpeg.org/")
advancedFormLayout.addRow("ffmpeg executable:", self.ffmpegPathSelector)
self.videoExportFfmpegWarning = qt.QLabel('<qt><b><font color="red">Set valid ffmpeg executable path! '+
'<a href="https://slicer.readthedocs.io/en/latest/user_guide/modules/screencapture.html#setting-up-ffmpeg">Help...</a></font></b></qt>')
self.videoExportFfmpegWarning.connect('linkActivated(QString)', self.openURL)
self.videoExportFfmpegWarning.setVisible(False)
advancedFormLayout.addRow("", self.videoExportFfmpegWarning)
self.extraVideoOptionsWidget = qt.QLineEdit()
self.extraVideoOptionsWidget.setToolTip('Additional video conversion options passed to ffmpeg. Parameters -i (input files), -y'
+'(overwrite without asking), -r (frame rate), -start_number are specified by the module and therefore'
+'should not be included in this list.')
advancedFormLayout.addRow("Video extra options:", self.extraVideoOptionsWidget)
self.fileNamePatternWidget = qt.QLineEdit()
self.fileNamePatternWidget.setToolTip(
"String that defines file name, type, and numbering scheme. Default: image%05d.png.")
self.fileNamePatternWidget.text = "image_%05d.png"
advancedFormLayout.addRow("Image file name pattern:", self.fileNamePatternWidget)
self.lightboxColumnCountSliderWidget = ctk.ctkSliderWidget()
self.lightboxColumnCountSliderWidget.decimals = 0
self.lightboxColumnCountSliderWidget.singleStep = 1
self.lightboxColumnCountSliderWidget.minimum = 1
self.lightboxColumnCountSliderWidget.maximum = 20
self.lightboxColumnCountSliderWidget.value = 6
self.lightboxColumnCountSliderWidget.setToolTip("Number of columns in lightbox image")
advancedFormLayout.addRow("Lightbox image columns:", self.lightboxColumnCountSliderWidget)
self.maxFramesWidget = qt.QSpinBox()
self.maxFramesWidget.setRange(1, 9999)
self.maxFramesWidget.setValue(600)
self.maxFramesWidget.setToolTip(
"Maximum number of images to be captured (without backward steps and repeating).")
advancedFormLayout.addRow("Maximum number of images:", self.maxFramesWidget)
self.volumeNodeComboBox = slicer.qMRMLNodeComboBox()
self.volumeNodeComboBox.nodeTypes = ["vtkMRMLVectorVolumeNode"]
self.volumeNodeComboBox.baseName = "Screenshot"
self.volumeNodeComboBox.renameEnabled = True
self.volumeNodeComboBox.noneEnabled = True
self.volumeNodeComboBox.setToolTip("Select a volume node to store the captured image in the scene instead of just writing immediately to disk. Requires output 'Number of images' to be set to 1.")
self.volumeNodeComboBox.setMRMLScene(slicer.mrmlScene)
advancedFormLayout.addRow("Output volume node:", self.volumeNodeComboBox)
self.showViewControllersCheckBox = qt.QCheckBox(" ")
self.showViewControllersCheckBox.checked = False
self.showViewControllersCheckBox.setToolTip("If checked, images will be captured with view controllers visible.")
advancedFormLayout.addRow("View controllers:", self.showViewControllersCheckBox)
self.transparentBackgroundCheckBox = qt.QCheckBox(" ")
self.transparentBackgroundCheckBox.checked = False
self.transparentBackgroundCheckBox.setToolTip("If checked, images will be captured with transparent background.")
advancedFormLayout.addRow("Transparent background:", self.transparentBackgroundCheckBox)
watermarkEnabled = slicer.util.settingsValue('ScreenCapture/WatermarkEnabled', False, converter=slicer.util.toBool)
self.watermarkEnabledCheckBox = qt.QCheckBox(" ")
self.watermarkEnabledCheckBox.checked = watermarkEnabled
self.watermarkEnabledCheckBox.setToolTip("If checked, selected watermark image will be added to all exported images.")
self.watermarkPositionWidget = qt.QComboBox()
self.watermarkPositionWidget.enabled = watermarkEnabled
self.watermarkPositionWidget.setSizePolicy(qt.QSizePolicy.MinimumExpanding, qt.QSizePolicy.Preferred)
self.watermarkPositionWidget.setToolTip("Add a watermark image to all exported images.")
for watermarkPositionPreset in self.logic.watermarkPositionPresets:
self.watermarkPositionWidget.addItem(watermarkPositionPreset["name"])
self.watermarkPositionWidget.setCurrentText(
slicer.util.settingsValue('ScreenCapture/WatermarkPosition', self.logic.watermarkPositionPresets[0]["name"]))
self.watermarkSizeSliderWidget = qt.QSpinBox()
self.watermarkSizeSliderWidget.enabled = watermarkEnabled
self.watermarkSizeSliderWidget.setSizePolicy(qt.QSizePolicy.MinimumExpanding, qt.QSizePolicy.Preferred)
self.watermarkSizeSliderWidget.singleStep = 10
self.watermarkSizeSliderWidget.minimum = 10
self.watermarkSizeSliderWidget.maximum = 1000
self.watermarkSizeSliderWidget.value = 100
self.watermarkSizeSliderWidget.suffix = "%"
self.watermarkSizeSliderWidget.setToolTip("Size scaling applied to the watermark image. 100% is original size")
try:
self.watermarkSizeSliderWidget.value = int(slicer.util.settingsValue('ScreenCapture/WatermarkSize', 100))
except:
pass
self.watermarkOpacitySliderWidget = qt.QSpinBox()
self.watermarkOpacitySliderWidget.enabled = watermarkEnabled
self.watermarkOpacitySliderWidget.setSizePolicy(qt.QSizePolicy.MinimumExpanding, qt.QSizePolicy.Preferred)
self.watermarkOpacitySliderWidget.singleStep = 10
self.watermarkOpacitySliderWidget.minimum = 0
self.watermarkOpacitySliderWidget.maximum = 100
self.watermarkOpacitySliderWidget.value = 30
self.watermarkOpacitySliderWidget.suffix = "%"
self.watermarkOpacitySliderWidget.setToolTip("Opacity of the watermark image. 100% is fully opaque.")
try:
self.watermarkOpacitySliderWidget.value = int(slicer.util.settingsValue('ScreenCapture/WatermarkOpacity', 30))
except:
pass
self.watermarkPathSelector = ctk.ctkPathLineEdit()
self.watermarkPathSelector.enabled = watermarkEnabled
self.watermarkPathSelector.settingKey = 'ScreenCaptureWatermarkImagePath'
self.watermarkPathSelector.nameFilters = ["*.png"]
self.watermarkPathSelector.sizeAdjustPolicy = ctk.ctkPathLineEdit.AdjustToMinimumContentsLength
self.watermarkPathSelector.setSizePolicy(qt.QSizePolicy.MinimumExpanding, qt.QSizePolicy.Preferred)
self.watermarkPathSelector.setToolTip("Watermark image file in png format")
hbox = qt.QHBoxLayout()
hbox.addWidget(self.watermarkEnabledCheckBox)
hbox.addWidget(qt.QLabel("Position:"))
hbox.addWidget(self.watermarkPositionWidget)
hbox.addWidget(qt.QLabel("Size:"))
hbox.addWidget(self.watermarkSizeSliderWidget)
hbox.addWidget(qt.QLabel("Opacity:"))
hbox.addWidget(self.watermarkOpacitySliderWidget)
#hbox.addStretch()
advancedFormLayout.addRow("Watermark image:", hbox)
hbox = qt.QHBoxLayout()
hbox.addWidget(self.watermarkPathSelector)
advancedFormLayout.addRow("", hbox)
# Capture button
self.captureButtonLabelCapture = "Capture"
self.captureButtonLabelCancel = "Cancel"
self.captureButton = qt.QPushButton(self.captureButtonLabelCapture)
self.captureButton.toolTip = "Capture slice sweep to image sequence."
self.showCreatedOutputFileButton = qt.QPushButton()
self.showCreatedOutputFileButton.setIcon(qt.QIcon(':Icons/Go.png'))
self.showCreatedOutputFileButton.setMaximumWidth(60)
self.showCreatedOutputFileButton.enabled = False
self.showCreatedOutputFileButton.toolTip = "Show created output file."
hbox = qt.QHBoxLayout()
hbox.addWidget(self.captureButton)
hbox.addWidget(self.showCreatedOutputFileButton)
self.layout.addLayout(hbox)
self.statusLabel = qt.QPlainTextEdit()
self.statusLabel.setTextInteractionFlags(qt.Qt.TextSelectableByMouse)
self.statusLabel.setCenterOnScroll(True)
self.layout.addWidget(self.statusLabel)
#
# Add vertical spacer
# self.layout.addStretch(1)
# connections
self.captureButton.connect('clicked(bool)', self.onCaptureButton)
self.showCreatedOutputFileButton.connect('clicked(bool)', self.onShowCreatedOutputFile)
self.viewNodeSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateViewOptions)
self.animationModeWidget.connect("currentIndexChanged(int)", self.updateViewOptions)
self.sliceStartOffsetSliderWidget.connect('valueChanged(double)', self.setSliceOffset)
self.sliceEndOffsetSliderWidget.connect('valueChanged(double)', self.setSliceOffset)
self.sequenceBrowserNodeSelectorWidget.connect("currentNodeChanged(vtkMRMLNode*)", self.updateViewOptions)
self.sequenceStartItemIndexWidget.connect('valueChanged(double)', self.setSequenceItemIndex)
self.sequenceEndItemIndexWidget.connect('valueChanged(double)', self.setSequenceItemIndex)
self.outputTypeWidget.connect('currentIndexChanged(int)', self.updateOutputType)
self.videoFormatWidget.connect("currentIndexChanged(int)", self.updateVideoFormat)
self.maxFramesWidget.connect('valueChanged(int)', self.maxFramesChanged)
self.videoLengthSliderWidget.connect('valueChanged(double)', self.setVideoLength)
self.videoFrameRateSliderWidget.connect('valueChanged(double)', self.setVideoFrameRate)
self.singleStepButton.connect('toggled(bool)', self.setForceSingleStep)
self.numberOfStepsSliderWidget.connect('valueChanged(double)', self.setNumberOfSteps)
self.watermarkEnabledCheckBox.connect('toggled(bool)', self.watermarkPositionWidget, 'setEnabled(bool)')
self.watermarkEnabledCheckBox.connect('toggled(bool)', self.watermarkSizeSliderWidget, 'setEnabled(bool)')
self.watermarkEnabledCheckBox.connect('toggled(bool)', self.watermarkPathSelector, 'setEnabled(bool)')
self.setVideoLength() # update frame rate based on video length
self.updateOutputType()
self.updateVideoFormat(0)
self.updateViewOptions()
def maxFramesChanged(self):
self.numberOfStepsSliderWidget.maximum = self.maxFramesWidget.value
def openURL(self, URL):
qt.QDesktopServices().openUrl(qt.QUrl(URL))
QDesktopServices
def onShowCreatedOutputFile(self):
if not self.createdOutputFile:
return
qt.QDesktopServices().openUrl(qt.QUrl("file:///"+self.createdOutputFile, qt.QUrl.TolerantMode))
def updateOutputType(self, selectionIndex=0):
isVideo = self.outputTypeWidget.currentText == "video"
isLightbox = self.outputTypeWidget.currentText == "lightbox image"
self.fileNamePatternWidget.enabled = not (isVideo or isLightbox)
self.videoFileNameWidget.enabled = isVideo
self.videoFormatWidget.enabled = isVideo
self.videoLengthSliderWidget.enabled = isVideo
self.videoFrameRateSliderWidget.enabled = isVideo
self.videoFileNameWidget.setVisible(not isLightbox)
self.videoFileNameWidget.enabled = isVideo
self.lightboxImageFileNameWidget.setVisible(isLightbox)
self.lightboxImageFileNameWidget.enabled = isLightbox
def updateVideoFormat(self, selectionIndex):
videoFormatPreset = self.logic.videoFormatPresets[selectionIndex]
import os
filenameExt = os.path.splitext(self.videoFileNameWidget.text)
self.videoFileNameWidget.text = filenameExt[0] + "." + videoFormatPreset["fileExtension"]
self.extraVideoOptionsWidget.text = videoFormatPreset["extraVideoOptions"]
def currentViewNodeType(self):
viewNode = self.viewNodeSelector.currentNode()
if not viewNode:
return None
elif viewNode.IsA("vtkMRMLSliceNode"):
return VIEW_SLICE
elif viewNode.IsA("vtkMRMLViewNode"):
return VIEW_3D
else:
return None
def addLog(self, text):
"""Append text to log window
"""
self.statusLabel.appendPlainText(text)
self.statusLabel.ensureCursorVisible()
slicer.app.processEvents() # force update
def cleanup(self):
pass
def updateViewOptions(self):
sequencesModuleAvailable = hasattr(slicer.modules, 'sequences')
if self.viewNodeType != self.currentViewNodeType():
self.viewNodeType = self.currentViewNodeType()
self.animationModeWidget.clear()
if self.viewNodeType == VIEW_SLICE:
self.animationModeWidget.addItem("slice sweep")
self.animationModeWidget.addItem("slice fade")
if self.viewNodeType == VIEW_3D:
self.animationModeWidget.addItem("3D rotation")
if sequencesModuleAvailable:
self.animationModeWidget.addItem("sequence")
if self.animationMode != self.animationModeWidget.currentText:
self.animationMode = self.animationModeWidget.currentText
# slice sweep
self.sliceStartOffsetSliderLabel.visible = (self.animationMode == "slice sweep")
self.sliceStartOffsetSliderWidget.visible = (self.animationMode == "slice sweep")
self.sliceEndOffsetSliderLabel.visible = (self.animationMode == "slice sweep")
self.sliceEndOffsetSliderWidget.visible = (self.animationMode == "slice sweep")
if self.animationMode == "slice sweep":
offsetResolution = self.logic.getSliceOffsetResolution(self.viewNodeSelector.currentNode())
sliceOffsetMin, sliceOffsetMax = self.logic.getSliceOffsetRange(self.viewNodeSelector.currentNode())
wasBlocked = self.sliceStartOffsetSliderWidget.blockSignals(True)
self.sliceStartOffsetSliderWidget.singleStep = offsetResolution
self.sliceStartOffsetSliderWidget.minimum = sliceOffsetMin
self.sliceStartOffsetSliderWidget.maximum = sliceOffsetMax
self.sliceStartOffsetSliderWidget.value = sliceOffsetMin
self.sliceStartOffsetSliderWidget.blockSignals(wasBlocked)
wasBlocked = self.sliceEndOffsetSliderWidget.blockSignals(True)
self.sliceEndOffsetSliderWidget.singleStep = offsetResolution
self.sliceEndOffsetSliderWidget.minimum = sliceOffsetMin
self.sliceEndOffsetSliderWidget.maximum = sliceOffsetMax
self.sliceEndOffsetSliderWidget.value = sliceOffsetMax
self.sliceEndOffsetSliderWidget.blockSignals(wasBlocked)
# 3D rotation
self.rotationSliderLabel.visible = (self.animationMode == "3D rotation")
self.rotationSliderWidget.visible = (self.animationMode == "3D rotation")
self.rotationAxisLabel.visible = (self.animationMode == "3D rotation")
self.rotationAxisWidget.visible = (self.animationMode == "3D rotation")
# Sequence
self.sequenceBrowserNodeSelectorLabel.visible = (self.animationMode == "sequence")
self.sequenceBrowserNodeSelectorWidget.visible = (self.animationMode == "sequence")
self.sequenceStartItemIndexLabel.visible = (self.animationMode == "sequence")
self.sequenceStartItemIndexWidget.visible = (self.animationMode == "sequence")
self.sequenceEndItemIndexLabel.visible = (self.animationMode == "sequence")
self.sequenceEndItemIndexWidget.visible = (self.animationMode == "sequence")
if self.animationMode == "sequence":
sequenceBrowserNode = self.sequenceBrowserNodeSelectorWidget.currentNode()
sequenceItemCount = 0
if sequenceBrowserNode and sequenceBrowserNode.GetMasterSequenceNode():
sequenceItemCount = sequenceBrowserNode.GetMasterSequenceNode().GetNumberOfDataNodes()
if sequenceItemCount>0:
wasBlocked = self.sequenceStartItemIndexWidget.blockSignals(True)
self.sequenceStartItemIndexWidget.maximum = sequenceItemCount-1
self.sequenceStartItemIndexWidget.value = 0
self.sequenceStartItemIndexWidget.blockSignals(wasBlocked)
wasBlocked = self.sequenceEndItemIndexWidget.blockSignals(True)
self.sequenceEndItemIndexWidget.maximum = sequenceItemCount-1
self.sequenceEndItemIndexWidget.value = sequenceItemCount-1
self.sequenceEndItemIndexWidget.blockSignals(wasBlocked)
self.sequenceStartItemIndexWidget.enabled = sequenceItemCount>0
self.sequenceEndItemIndexWidget.enabled = sequenceItemCount>0
numberOfSteps = int(self.numberOfStepsSliderWidget.value)
forceSingleStep = self.singleStepButton.checked
if forceSingleStep:
numberOfSteps = 1
self.numberOfStepsSliderWidget.setDisabled(forceSingleStep)
self.forwardBackwardCheckBox.enabled = (numberOfSteps > 1)
self.repeatSliderWidget.enabled = (numberOfSteps > 1)
self.volumeNodeComboBox.setEnabled(numberOfSteps == 1)
def setSliceOffset(self, offset):
sliceLogic = self.logic.getSliceLogicFromSliceNode(self.viewNodeSelector.currentNode())
sliceLogic.SetSliceOffset(offset)
def setVideoLength(self, lengthSec=None):
wasBlocked = self.videoFrameRateSliderWidget.blockSignals(True)
self.videoFrameRateSliderWidget.value = self.numberOfStepsSliderWidget.value / self.videoLengthSliderWidget.value
self.videoFrameRateSliderWidget.blockSignals(wasBlocked)
def setVideoFrameRate(self, frameRateFps):
wasBlocked = self.videoFrameRateSliderWidget.blockSignals(True)
self.videoLengthSliderWidget.value = self.numberOfStepsSliderWidget.value / self.videoFrameRateSliderWidget.value
self.videoFrameRateSliderWidget.blockSignals(wasBlocked)
def setNumberOfSteps(self, steps):
self.setVideoLength()
self.updateViewOptions()
def setForceSingleStep(self, force):
self.updateViewOptions()
def setSequenceItemIndex(self, index):
sequenceBrowserNode = self.sequenceBrowserNodeSelectorWidget.currentNode()
sequenceBrowserNode.SetSelectedItemNumber(int(index))
def enableInputOutputWidgets(self, enable):
self.inputCollapsibleButton.setEnabled(enable)
self.outputCollapsibleButton.setEnabled(enable)
def onCaptureButton(self):
# Disable capture button to prevent multiple clicks
self.captureButton.setEnabled(False)
self.enableInputOutputWidgets(False)
slicer.app.processEvents()
if self.captureButton.text == self.captureButtonLabelCancel:
self.logic.requestCancel()
return
self.logic.setFfmpegPath(self.ffmpegPathSelector.currentPath)
qt.QSettings().setValue('ScreenCapture/WatermarkEnabled', bool(self.watermarkEnabledCheckBox.checked))
qt.QSettings().setValue('ScreenCapture/WatermarkPosition', self.watermarkPositionWidget.currentText)
qt.QSettings().setValue('ScreenCapture/WatermarkOpacity', self.watermarkOpacitySliderWidget.value)
qt.QSettings().setValue('ScreenCapture/WatermarkSize', self.watermarkSizeSliderWidget.value)
if self.watermarkEnabledCheckBox.checked:
if self.watermarkPathSelector.currentPath:
self.logic.setWatermarkImagePath(self.watermarkPathSelector.currentPath)
self.watermarkPathSelector.addCurrentPathToHistory()
else:
self.logic.setWatermarkImagePath(self.resourcePath('SlicerWatermark.png'))
self.logic.setWatermarkPosition(self.watermarkPositionWidget.currentIndex)
self.logic.setWatermarkSizePercent(self.watermarkSizeSliderWidget.value)
self.logic.setWatermarkOpacityPercent(self.watermarkOpacitySliderWidget.value)
else:
self.logic.setWatermarkPosition(-1)
self.statusLabel.plainText = ''
videoOutputRequested = (self.outputTypeWidget.currentText == "video")
viewNode = self.viewNodeSelector.currentNode()
numberOfSteps = int(self.numberOfStepsSliderWidget.value)
if self.singleStepButton.checked:
numberOfSteps = 1
if numberOfSteps < 2:
# If a single image is selected
videoOutputRequested = False
outputDir = self.outputDirSelector.currentPath
self.outputDirSelector.addCurrentPathToHistory()
self.videoExportFfmpegWarning.setVisible(False)
if videoOutputRequested:
if not self.logic.isFfmpegPathValid():
# ffmpeg not found, try to automatically find it at common locations
self.logic.findFfmpeg()
if not self.logic.isFfmpegPathValid() and os.name == 'nt': # TODO: implement download for Linux/MacOS?
# ffmpeg not found, offer downloading it
if slicer.util.confirmOkCancelDisplay(
'Video encoder not detected on your system. '
'Download ffmpeg video encoder?',
windowTitle='Download confirmation'):
if not self.logic.ffmpegDownload():
slicer.util.errorDisplay("ffmpeg download failed")
if not self.logic.isFfmpegPathValid():
# still not found, user has to specify path manually
self.videoExportFfmpegWarning.setVisible(True)
self.advancedCollapsibleButton.collapsed = False
self.captureButton.setEnabled(True)
self.enableInputOutputWidgets(True)
return
self.ffmpegPathSelector.currentPath = self.logic.getFfmpegPath()
# Need to create a new random file pattern if video output is requested to make sure that new image files are not mixed up with
# existing files in the output directory
imageFileNamePattern = self.fileNamePatternWidget.text if (self.outputTypeWidget.currentText == "image series") else self.logic.getRandomFilePattern()
self.captureButton.setEnabled(True)
self.captureButton.text = self.captureButtonLabelCancel
slicer.app.setOverrideCursor(qt.Qt.WaitCursor)
captureAllViews = self.captureAllViewsCheckBox.checked
transparentBackground = self.transparentBackgroundCheckBox.checked
showViewControllers = self.showViewControllersCheckBox.checked
if captureAllViews:
self.logic.showViewControllers(showViewControllers)
elif showViewControllers:
logging.warning("View controllers are only available to be shown when capturing all views.")
try:
if numberOfSteps < 2:
if imageFileNamePattern != self.snapshotFileNamePattern or outputDir != self.snapshotOutputDir:
self.snapshotIndex = 0
if outputDir:
[filename, self.snapshotIndex] = self.logic.getNextAvailableFileName(outputDir, imageFileNamePattern, self.snapshotIndex)
else:
filename = None
view = None if captureAllViews else self.logic.viewFromNode(viewNode)
volumeNode = None if numberOfSteps>1 else self.volumeNodeComboBox.currentNode()
self.logic.captureImageFromView(view, filename, transparentBackground, volumeNode=volumeNode)
if filename:
self.logic.addLog("Write "+filename)
if volumeNode:
self.logic.addLog(f"Write to volume node '{volumeNode.GetName()}'")
elif self.animationModeWidget.currentText == "slice sweep":
self.logic.captureSliceSweep(viewNode, self.sliceStartOffsetSliderWidget.value,
self.sliceEndOffsetSliderWidget.value, numberOfSteps, outputDir, imageFileNamePattern,
captureAllViews = captureAllViews, transparentBackground = transparentBackground)
elif self.animationModeWidget.currentText == "slice fade":
self.logic.captureSliceFade(viewNode, numberOfSteps, outputDir, imageFileNamePattern,
captureAllViews = captureAllViews, transparentBackground = transparentBackground)
elif self.animationModeWidget.currentText == "3D rotation":
self.logic.capture3dViewRotation(viewNode, self.rotationSliderWidget.minimumValue,
self.rotationSliderWidget.maximumValue, numberOfSteps,
self.rotationAxisWidget.itemData(self.rotationAxisWidget.currentIndex),
outputDir, imageFileNamePattern,
captureAllViews = captureAllViews, transparentBackground = transparentBackground)
elif self.animationModeWidget.currentText == "sequence":
self.logic.captureSequence(viewNode, self.sequenceBrowserNodeSelectorWidget.currentNode(),
self.sequenceStartItemIndexWidget.value, self.sequenceEndItemIndexWidget.value,
numberOfSteps, outputDir, imageFileNamePattern,
captureAllViews = captureAllViews, transparentBackground = transparentBackground)
else:
raise ValueError('Unsupported view node type.')
import shutil
fps = self.videoFrameRateSliderWidget.value
if numberOfSteps > 1:
forwardBackward = self.forwardBackwardCheckBox.checked
numberOfRepeats = int(self.repeatSliderWidget.value)
filePathPattern = os.path.join(outputDir, imageFileNamePattern)
fileIndex = numberOfSteps
for repeatIndex in range(numberOfRepeats):
if forwardBackward:
for step in reversed(range(1, numberOfSteps-1)):
sourceFilename = filePathPattern % step
destinationFilename = filePathPattern % fileIndex
self.logic.addLog("Copy to "+destinationFilename)
shutil.copyfile(sourceFilename, destinationFilename)
fileIndex += 1
if repeatIndex < numberOfRepeats - 1:
for step in range(numberOfSteps):
sourceFilename = filePathPattern % step
destinationFilename = filePathPattern % fileIndex
self.logic.addLog("Copy to "+destinationFilename)
shutil.copyfile(sourceFilename, destinationFilename)
fileIndex += 1
if forwardBackward and (numberOfSteps > 2):
numberOfSteps += numberOfSteps - 2
numberOfSteps *= numberOfRepeats
try:
if videoOutputRequested:
self.logic.createVideo(fps, self.extraVideoOptionsWidget.text,
outputDir, imageFileNamePattern, self.videoFileNameWidget.text)
elif (self.outputTypeWidget.currentText == "lightbox image"):
self.logic.createLightboxImage(int(self.lightboxColumnCountSliderWidget.value),
outputDir, imageFileNamePattern, numberOfSteps, self.lightboxImageFileNameWidget.text)
finally:
if not self.outputTypeWidget.currentText == "image series":
self.logic.deleteTemporaryFiles(outputDir, imageFileNamePattern, numberOfSteps)
self.addLog("Done.")
self.createdOutputFile = os.path.join(outputDir, self.videoFileNameWidget.text) if videoOutputRequested else outputDir
self.showCreatedOutputFileButton.enabled = True
except Exception as e:
self.addLog(f"Error: {str(e)}")
import traceback
traceback.print_exc()
self.showCreatedOutputFileButton.enabled = False
self.createdOutputFile = None
if captureAllViews:
self.logic.showViewControllers(True)
slicer.app.restoreOverrideCursor()
self.captureButton.text = self.captureButtonLabelCapture
self.captureButton.setEnabled(True)
self.enableInputOutputWidgets(True)
#
# ScreenCaptureLogic
#
class ScreenCaptureLogic(ScriptedLoadableModuleLogic):
"""This class should implement all the actual
computation done by your module. The interface
should be such that other python code can import
this class and make use of the functionality without
requiring an instance of the Widget.
Uses ScriptedLoadableModuleLogic base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self):
self.logCallback = None
self.cancelRequested = False
self.videoFormatPresets = [
{"name": "H.264", "fileExtension": "mp4", "extraVideoOptions": "-codec libx264 -preset slower -pix_fmt yuv420p"},
{"name": "H.264 (high-quality)", "fileExtension": "mp4", "extraVideoOptions": "-codec libx264 -preset slower -crf 18 -pix_fmt yuv420p"},
{"name": "MPEG-4", "fileExtension": "mp4", "extraVideoOptions": "-codec mpeg4 -qscale 5"},
{"name": "MPEG-4 (high-quality)", "fileExtension": "mp4", "extraVideoOptions": "-codec mpeg4 -qscale 3"},
{"name": "Animated GIF", "fileExtension": "gif", "extraVideoOptions": "-filter_complex palettegen,[v]paletteuse"},
{"name": "Animated GIF (grayscale)", "fileExtension": "gif", "extraVideoOptions": "-vf format=gray"} ]
self.watermarkPositionPresets = [
{"name": "bottom-left", "position": lambda capturedImageSize, watermarkSize, spacing: [-2, -2]},
{"name": "bottom-right", "position": lambda capturedImageSize, watermarkSize, spacing: [
-capturedImageSize[0]*spacing+watermarkSize[0]+2, -2]},
{"name": "top-left", "position": lambda capturedImageSize, watermarkSize, spacing: [
-2, -capturedImageSize[1]*spacing+watermarkSize[1]+2]},
{"name": "top-right", "position": lambda capturedImageSize, watermarkSize, spacing: [
-capturedImageSize[0]*spacing+watermarkSize[0]+2, -capturedImageSize[1]*spacing+watermarkSize[1]+2]} ]
self.watermarkPosition = -1
self.watermarkSizePercent = 100
self.watermarkOpacityPercent = 100
self.watermarkImagePath = None
def requestCancel(self):
logging.info("User requested cancelling of capture")
self.cancelRequested = True
def addLog(self, text):
logging.info(text)
if self.logCallback:
self.logCallback(text)
def showViewControllers(self, show):
slicer.util.setViewControllersVisible(show)
def getRandomFilePattern(self):
import string
import random
numberOfRandomChars=5
randomString = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(numberOfRandomChars))
filePathPattern = "tmp-"+randomString+"-%05d.png"
return filePathPattern
def isFfmpegPathValid(self):
import os
ffmpegPath = self.getFfmpegPath()
return os.path.isfile(ffmpegPath)
def getDownloadedFfmpegDirectory(self):
return os.path.dirname(slicer.app.slicerUserSettingsFilePath)+'/ffmpeg'
def getFfmpegExecutableFilename(self):
if os.name == 'nt':
return 'ffmpeg.exe'
else:
return 'ffmpeg'
def findFfmpeg(self):
# Try to find the executable at specific paths
commonFfmpegPaths = [
'/usr/local/bin/ffmpeg',
'/usr/bin/ffmpeg'
]
for ffmpegPath in commonFfmpegPaths:
if os.path.isfile(ffmpegPath):
# found one
self.setFfmpegPath(ffmpegPath)
return True
# Search for the executable in directories
commonFfmpegDirs = [
self.getDownloadedFfmpegDirectory()
]
for ffmpegDir in commonFfmpegDirs:
if self.findFfmpegInDirectory(ffmpegDir):
# found it
return True
# Not found
return False
def findFfmpegInDirectory(self, ffmpegDir):
ffmpegExecutableFilename = self.getFfmpegExecutableFilename()
for dirpath, dirnames, files in os.walk(ffmpegDir):
for name in files:
if name==ffmpegExecutableFilename:
ffmpegExecutablePath = (dirpath + '/' + name).replace('\\','/')
self.setFfmpegPath(ffmpegExecutablePath)
return True
return False
def unzipFfmpeg(self, filePath, ffmpegTargetDirectory):
if not os.path.exists(filePath) or os.stat(filePath).st_size == 0:
logging.info('ffmpeg package is not found at ' + filePath)
return False
logging.info('Unzipping ffmpeg package ' + filePath)
qt.QDir().mkpath(ffmpegTargetDirectory)
slicer.app.applicationLogic().Unzip(filePath, ffmpegTargetDirectory)
success = self.findFfmpegInDirectory(ffmpegTargetDirectory)
return success
def ffmpegDownload(self):
ffmpegTargetDirectory = self.getDownloadedFfmpegDirectory()
# The number in the filePath can be incremented each time a significantly different ffmpeg version
# is to be introduced (it prevents reusing a previously downloaded package).
filePath = slicer.app.temporaryPath + '/ffmpeg-package-slicer-01.zip'
success = self.unzipFfmpeg(filePath, ffmpegTargetDirectory)
if success:
# there was a valid downloaded package already
return True
# List of mirror sites to attempt download ffmpeg pre-built binaries from
urls = []
if os.name == 'nt':
urls.append('https://github.com/Slicer/SlicerBinaryDependencies/releases/download/ffmpeg/ffmpeg-2021-05-16-win64.zip')
else:
# TODO: implement downloading for Linux/MacOS?
pass
success = False
qt.QApplication.setOverrideCursor(qt.Qt.WaitCursor)
for url in urls:
success = True
try:
logging.info('Requesting download ffmpeg from %s...' % url)
import urllib.request, urllib.error, urllib.parse
req = urllib.request.Request(url, headers={ 'User-Agent': 'Mozilla/5.0' })
data = urllib.request.urlopen(req).read()
with open(filePath, "wb") as f:
f.write(data)
success = self.unzipFfmpeg(filePath, ffmpegTargetDirectory)
except:
success = False
if success:
break
qt.QApplication.restoreOverrideCursor()
return success
def getFfmpegPath(self):
settings = qt.QSettings()
if settings.contains('General/ffmpegPath'):
return slicer.app.toSlicerHomeAbsolutePath(settings.value('General/ffmpegPath'))
return ''
def setFfmpegPath(self, ffmpegPath):
# don't save it if already saved
settings = qt.QSettings()
if settings.contains('General/ffmpegPath'):
if ffmpegPath == slicer.app.toSlicerHomeAbsolutePath(settings.value('General/ffmpegPath')):
return
settings.setValue('General/ffmpegPath', slicer.app.toSlicerHomeRelativePath(ffmpegPath))
def setWatermarkPosition(self, watermarkPosition):
self.watermarkPosition = watermarkPosition
def setWatermarkSizePercent(self, watermarkSizePercent):
self.watermarkSizePercent = watermarkSizePercent
def setWatermarkOpacityPercent(self, watermarkOpacityPercent):
self.watermarkOpacityPercent = watermarkOpacityPercent
def setWatermarkImagePath(self, watermarkImagePath):
self.watermarkImagePath = watermarkImagePath
def getSliceLogicFromSliceNode(self, sliceNode):
lm = slicer.app.layoutManager()
sliceLogic = lm.sliceWidget(sliceNode.GetLayoutName()).sliceLogic()
return sliceLogic
def getSliceOffsetRange(self, sliceNode):
sliceLogic = self.getSliceLogicFromSliceNode(sliceNode)
sliceBounds = [0, -1, 0, -1, 0, -1]
sliceLogic.GetLowestVolumeSliceBounds(sliceBounds)
sliceOffsetMin = sliceBounds[4]
sliceOffsetMax = sliceBounds[5]
# increase range if it is empty
# to allow capturing even when no volumes are shown in slice views
if sliceOffsetMin == sliceOffsetMax:
sliceOffsetMin = sliceLogic.GetSliceOffset()-100
sliceOffsetMax = sliceLogic.GetSliceOffset()+100
return sliceOffsetMin, sliceOffsetMax
def getSliceOffsetResolution(self, sliceNode):