-
Notifications
You must be signed in to change notification settings - Fork 29
/
planetary_system_stacker.py
1448 lines (1214 loc) · 63.3 KB
/
planetary_system_stacker.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
# -*- coding: utf-8; -*-
"""
Copyright (c) 2018 Rolf Hempel, rolf6419@gmx.de
This file is part of the PlanetarySystemStacker tool (PSS).
https://github.com/Rolf-Hempel/PlanetarySystemStacker
PSS 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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PSS. If not, see <http://www.gnu.org/licenses/>.
Part of this module (in class "AlignmentPointEditor" was copied from
https://stackoverflow.com/questions/35508711/how-to-enable-pan-and-zoom-in-a-qgraphicsview
"""
# The following statement is necessary so that the dependent PSS modules are found when installed
# from PyPI under site_packages.
import sys, os
sys.path.insert(0, os.path.dirname(__file__))
import getpass
import platform
from os import remove
from pathlib import Path
from sys import exit, argv
import cv2
import matplotlib
import numpy as np
import psutil
from PyQt5 import QtWidgets, QtCore, QtGui
from numpy import uint8, uint16
import scipy
import astropy
import skimage
import pip
from alignment_point_editor import AlignmentPointEditorWidget
from alignment_points import AlignmentPoints
from configuration import Configuration
from configuration_editor import ConfigurationEditor
from exceptions import NotSupportedError
from frame_selector import FrameSelectorWidget
from frame_viewer import FrameViewerWidget
from frames import Frames
from job_editor import JobEditor, FileDialog
from main_gui import Ui_MainWindow
from miscellaneous import Miscellaneous
from postproc_editor import PostprocEditorWidget
from rectangular_patch_editor import RectangularPatchEditorWidget
from shift_distribution_viewer import ShiftDistributionViewerWidget
from workflow import Workflow
from pss_console import PssConsole
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"
class DisplayImage(QtWidgets.QGraphicsView):
"""
This is an auxiliary class for debugging purposes. It opens a separate window where images
can be displayed and updated during the computational steps. Activities are triggered from the
workflow thread using signals.
"""
def __init__(self):
"""
Initialize the display window with a standard position and size. The window is resized later
as required by the images to be displayed.
"""
super().__init__()
self.title = 'PyQt5 image'
self.setWindowTitle(self.title)
self.left = 100
self.top = 100
self.width = 640
self.height = 480
self.setGeometry(self.left, self.top, self.width, self.height)
# Create the window scene and add a (so far undefined) photo object to it.
self._scene = QtWidgets.QGraphicsScene()
self._photo = QtWidgets.QGraphicsPixmapItem()
self._scene.addItem(self._photo)
self.setScene(self._scene)
self.show()
def convert_image_to_pixmap(self, image):
"""
Convert a color or monochrome image (stored as a Numpy array of type uint8 or uint16) into
a pixmap object.
:param image: Numpy array of type uint8 or uint16, size: (size_y, size_x [, 3])
:return: QPixmap object holding the image
"""
# Convert image to 8bit if necessary.
if image.dtype == uint16:
image_uint8 = (image / 256.).astype(uint8)
elif image.dtype == uint8:
image_uint8 = image
else:
raise NotSupportedError("Attempt to set a photo with type neither"
" uint8 nor uint16")
self.shape_y = image_uint8.shape[0]
self.shape_x = image_uint8.shape[1]
# The image is monochrome:
if len(image_uint8.shape) == 2:
qt_image = QtGui.QImage(image_uint8, self.shape_x, self.shape_y, self.shape_x,
QtGui.QImage.Format_Grayscale8)
# The image is RGB color.
else:
qt_image = QtGui.QImage(image_uint8, self.shape_x, self.shape_y, 3 * self.shape_x,
QtGui.QImage.Format_RGB888)
return QtGui.QPixmap(qt_image)
def update_image(self, new_image):
"""
Replace the image with a new one.
:param new_image: Image, stored as a Numpy array of type uint8 or uint16,
size: (size_y, size_x [, 3])
:return: -
"""
pixmap = self.convert_image_to_pixmap(new_image)
self._photo.setPixmap(pixmap)
# Fit the display window to the size of the image.
self.resize(pixmap.width()+10, pixmap.height()+10)
self.repaint()
class PlanetarySystemStacker(QtWidgets.QMainWindow):
"""
This is the main class of the "Planetary System Stacker" software. It implements the main GUI
for the communication with the user. It creates the workflow thread which controls all program
activities asynchronously.
"""
signal_reset_masters = QtCore.pyqtSignal()
signal_load_master_dark = QtCore.pyqtSignal(str)
signal_load_master_flat = QtCore.pyqtSignal(str)
signal_frames = QtCore.pyqtSignal(object)
signal_rank_frames = QtCore.pyqtSignal()
signal_select_frames = QtCore.pyqtSignal()
signal_align_frames = QtCore.pyqtSignal(int, int, int, int)
signal_set_roi = QtCore.pyqtSignal(int, int, int, int)
signal_set_alignment_points = QtCore.pyqtSignal()
signal_compute_frame_qualities = QtCore.pyqtSignal()
signal_stack_frames = QtCore.pyqtSignal()
signal_save_stacked_image = QtCore.pyqtSignal()
signal_postprocess_image = QtCore.pyqtSignal()
signal_save_postprocessed_image = QtCore.pyqtSignal(object)
signal_set_go_back_activity = QtCore.pyqtSignal(object)
def __init__(self, parent=None):
"""
Initialize the Planetary System Stacker environment.
:param parent: None
"""
# The (generated) QtGui class is contained in module main_gui.py.
QtWidgets.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# This line is necessary to show the menubar on Linux. On Windows it does not hurt.
self.ui.menubar.setNativeMenuBar(False)
# Make sure that the progress widgets retain their size when hidden.
size_policy = self.ui.label_current_progress.sizePolicy()
size_policy.setRetainSizeWhenHidden(True)
self.ui.label_current_progress.setSizePolicy(size_policy)
size_policy = self.ui.progressBar_current.sizePolicy()
size_policy.setRetainSizeWhenHidden(True)
self.ui.progressBar_current.setSizePolicy(size_policy)
# Create configuration object and set configuration parameters to standard values.
self.configuration = Configuration()
self.configuration.initialize_configuration()
# Set the window icon to the PSS icon.
self.setWindowIcon(QtGui.QIcon(self.configuration.window_icon))
# Look up the location and size of the main GUI. Replace the location parameters with those
# stored in the configuration file when the GUI was closed last time. This way, the GUI
# memorizes its location between MPM invocations.
x0 = self.configuration.hidden_parameters_main_window_x0
y0 = self.configuration.hidden_parameters_main_window_y0
width = self.configuration.hidden_parameters_main_window_width
height = self.configuration.hidden_parameters_main_window_height
self.setGeometry(x0, y0, width, height)
if self.configuration.hidden_parameters_main_window_maximized:
self.showMaximized()
# Initialize variables.
self.widget_saved = None
# Write the program version into the window title.
self.setWindowTitle(self.configuration.global_parameters_version)
# Connect GUI events with methods of this class.
self.ui.actionQuit.triggered.connect(self.closeEvent)
self.ui.comboBox_back.currentTextChanged.connect(self.go_back)
self.ui.pushButton_start.clicked.connect(self.play)
self.ui.pushButton_pause.clicked.connect(self.pause)
self.ui.pushButton_next_job.clicked.connect(self.go_next)
self.ui.pushButton_quit.clicked.connect(self.close)
self.ui.box_automatic.stateChanged.connect(self.automatic_changed)
self.ui.actionLoad_video_directory.triggered.connect(self.load_video_directory)
self.ui.actionSave.triggered.connect(self.save_result)
self.ui.actionSave_as.triggered.connect(self.save_result_as)
self.ui.actionEdit_configuration.triggered.connect(self.edit_configuration)
self.ui.actionLoad_config.triggered.connect(self.load_config_file)
self.ui.actionSave_config.triggered.connect(self.save_config_file)
self.ui.actionDe_activate_master_frames.triggered.connect(self.reset_masters)
self.ui.actionLoad_master_dark_frame.triggered.connect(self.load_master_dark)
self.ui.actionLoad_master_flat_frame.triggered.connect(self.load_master_flat)
self.ui.actionCreate_new_master_dark_frame.triggered.connect(self.create_master_dark)
self.ui.actionCreate_new_master_flat_frame.triggered.connect(self.create_master_flat)
self.ui.actionAbout.triggered.connect(self.about_pss)
# Create the workflow thread and start it.
self.thread = QtCore.QThread()
self.workflow = Workflow(self)
self.workflow.moveToThread(self.thread)
self.workflow.master_dark_created_signal.connect(self.master_dark_created)
self.workflow.master_flat_created_signal.connect(self.master_flat_created)
self.workflow.calibration.report_calibration_error_signal.connect(
self.report_calibration_error)
self.workflow.work_next_task_signal.connect(self.work_next_task)
self.workflow.report_error_signal.connect(self.report_error)
self.workflow.abort_job_signal.connect(self.next_job_after_error)
self.workflow.work_current_progress_signal.connect(self.set_current_progress)
self.workflow.set_main_gui_busy_signal.connect(self.gui_set_busy)
self.workflow.set_status_bar_signal.connect(self.write_status_bar)
self.workflow.create_image_window_signal.connect(self.create_image_window)
self.workflow.update_image_window_signal.connect(self.update_image_window)
self.workflow.terminate_image_window_signal.connect(self.terminate_image_window)
self.thread.start()
# Connect signals to start activities on the workflow thread (e.g. in method
# "work_next_task").
self.signal_reset_masters.connect(self.workflow.calibration.reset_masters)
self.signal_load_master_dark.connect(self.workflow.calibration.load_master_dark)
self.signal_load_master_flat.connect(self.workflow.calibration.load_master_flat)
self.signal_frames.connect(self.workflow.execute_frames)
self.signal_rank_frames.connect(self.workflow.execute_rank_frames)
self.signal_select_frames.connect(self.workflow.execute_set_index_translation_table)
self.signal_align_frames.connect(self.workflow.execute_align_frames)
self.signal_set_roi.connect(self.workflow.execute_set_roi)
self.signal_set_alignment_points.connect(self.workflow.execute_set_alignment_points)
self.signal_compute_frame_qualities.connect(self.workflow.execute_compute_frame_qualities)
self.signal_stack_frames.connect(self.workflow.execute_stack_frames)
self.signal_save_stacked_image.connect(self.workflow.execute_save_stacked_image)
self.signal_postprocess_image.connect(self.workflow.execute_postprocess_image)
self.signal_save_postprocessed_image.connect(self.workflow.execute_save_postprocessed_image)
self.signal_set_go_back_activity.connect(self.change_go_back_activity)
# Initialize status variables
self.automatic = self.ui.box_automatic.isChecked()
self.busy = False
self.pause = False
self.job_number = 0
self.job_index = 0
self.jobs = []
self.activities = ['Previous job', 'Read frames', 'Rank frames', 'Align frames',
'Select stack size', 'Set ROI', 'Set alignment points',
'Compute frame qualities', 'Stack frames', 'Save stacked image',
'Postprocessing', 'Save postprocessed image', 'Next job']
self.activity = 'Read frames'
self.error_occurred = False
# Initialize the "backwards" combobox: The user can only go back to those program steps
# which have been executed already.
self.set_previous_actions_button()
# Deactivate GUI elements which do not make sense yet.
self.activate_gui_elements(
[self.ui.box_automatic, self.ui.comboBox_back, self.ui.pushButton_start,
self.ui.pushButton_pause,
self.ui.pushButton_next_job, self.ui.actionSave, self.ui.actionSave_as,
self.ui.actionLoad_postproc_config, self.ui.actionSave_postproc_config,
self.ui.actionEdit_postproc_config], False)
self.show_current_progress_widgets(False)
self.show_batch_progress_widgets(False)
# If the configuration was not read in from a previous run (i.e. only default values have
# been set so far), open the configuration editor GUI to let the user make adjustments if
# necessary.
if not self.configuration.config_file_exists:
# Tell the user to begin with changing / confirming config parameters.
self.write_status_bar(
'Adapt configuration to your needs and / or confirm by pressing "OK".', 'red')
self.edit_configuration()
else:
# Tell the user to begin with specifying jobs to be executed.
self.write_status_bar(
"Specify video(s) or dir(s) with image files to be stacked, or single image "
"files for postprocessing (menu: File / Open).", 'red')
# Initialize objects.
self.image_window = None
@QtCore.pyqtSlot()
def create_image_window(self):
"""
On request of the workflow thread open a separate window for displaying images in debugging.
:return: -
"""
self.image_window = DisplayImage()
@QtCore.pyqtSlot(object)
def update_image_window(self, image):
"""
Replace the image in the image window with a new one sent from the workflow thread.
:param image: Numpy array of type uint8 or uint16, size: (size_y, size_x [, 3])
:return: -
"""
self.image_window.update_image(image)
@QtCore.pyqtSlot()
def terminate_image_window(self):
"""
Close the separate image window on request of the workflow thread.
:return: -
"""
del self.image_window
def automatic_changed(self):
"""
If the user checks / unchecks the "Automatic" checkbox, change the corresponding status
variable.
:return: -
"""
self.automatic = not self.automatic
def edit_configuration(self):
"""
This method is invoked by selecting the "edit stacking config" menu entry.
:return: -
"""
# Display the configuration editor widget in the central QFrame.
self.display_widget(ConfigurationEditor(self))
def change_go_back_activity(self, phases):
"""
This method is triggered in the configuration editor if at least one parameter has been
changed. In this case it may be necessary to reset the workflow to an earlier phase. This
phase is set as the current activity, and later phases are deleted from the "go back"
button list.
:param phases: List of phases after which the workflow has to be invalidated. The
earliest phase on the list is relevant.
:return: -
"""
# Include the current activity in the list to make sure that the workflow will not jump to
# a phase which is not yet prepared.
phases.append(self.activity)
# Reset the position in the workflow.
earliest_phase = self.activities[min([self.activities.index(item) for item in phases])]
# Only if parameters are changed later in the workflow, write a message to the protocol.
if self.configuration.global_parameters_protocol_level > 1 and self.activity != 'Read frames':
# If the attached logfile has been closed, re-open it.
if self.configuration.global_parameters_store_protocol_with_result and \
self.workflow.attached_log_file.closed:
try:
self.workflow.attached_log_file = open(self.workflow.attached_log_name, 'a')
except:
pass
Miscellaneous.protocol(
"+++ Parameter change: all phases after '" + earliest_phase + "' are invalidated +++",
self.workflow.attached_log_file, precede_with_timestamp=True)
# Reset the position in the workflow, and update the "go back" button list.
self.activity = earliest_phase
self.set_previous_actions_button()
def display_widget(self, widget, display=True):
"""
Display a widget in the central main GUI location, or remove it from there.
:param widget: Widget object to be displayed.
:param display: If "True", display the widget. If "False", remove the current widget from
the GUI.
:return: -
"""
if display:
if self.widget_saved:
self.ui.verticalLayout_2.removeWidget(self.widget_saved)
self.widget_saved.close()
self.widget_saved = widget
self.ui.verticalLayout_2.insertWidget(0, widget)
self.ui.verticalLayout_2.setStretch(1, 0)
else:
if self.widget_saved:
self.ui.verticalLayout_2.removeWidget(self.widget_saved)
self.widget_saved.close()
self.widget_saved = None
def load_config_file(self):
"""
Load a stacking configuration file (extension ".pss").
:return: -
"""
options = QtWidgets.QFileDialog.Options()
filename = QtWidgets.QFileDialog.getOpenFileName(self, "Load configuration file",
self.configuration.hidden_parameters_current_dir,
"*.pss", options=options)
file_name = filename[0]
# If a valid file was selected, read parameters from the file and open the configuration
# editor.
if file_name != '':
# Read configuration parameters from the selected file.
self.configuration.read_config(file_name=file_name)
# Remember the current directory for next file dialog.
self.configuration.current_dir = str(Path(file_name).parents[0])
self.display_widget(ConfigurationEditor(self))
def save_config_file(self):
"""
Save all stacking parameters in a configuration file.
:return: -
"""
# Open the file chooser.
options = QtWidgets.QFileDialog.Options()
filename = QtWidgets.QFileDialog.getSaveFileName(self, "Save configuration file",
self.configuration.hidden_parameters_current_dir,
"Config file (*.pss)",
options=options)
# Store file only if the chooser did not return with a cancel.
file_name = filename[0]
if file_name != "":
my_file = Path(file_name)
# Remember the current directory for next file dialog.
self.configuration.hidden_parameters_current_dir = str(my_file.parents[0])
# If the config file exists, delete it first.
if my_file.is_file():
remove(str(my_file))
self.configuration.write_config(file_name=str(my_file))
def load_video_directory(self):
"""
This method is invoked by selecting "Open" from the "file" menu.
:return: -
"""
# Open the job editor widget.
self.display_widget(JobEditor(self))
def reset_masters(self):
"""
This method is invoked by selecting "Reset master frames" from the "Calibration" menu. The
signal is caught on the workflow thread, where the method "execute_reset_masters" is
executed.
:return: -
"""
self.signal_reset_masters.emit()
if self.configuration.global_parameters_protocol_level > 0:
Miscellaneous.protocol("+++ De-activating master dark / flat frames +++",
self.workflow.attached_log_file)
def create_master_dark(self):
"""
Open a file dialog for entering a video file or image directory with dark frames. When the
FileDialog closes, it sends a signal (with the path name as payload) to the corresponding
slot on the workflow thread. There the actual master dark computation is performed.
:return: -
"""
options = QtWidgets.QFileDialog.Options()
message = "Select a video file / a folder with image files for computing a master dark" \
" frame"
file_dialog = FileDialog(self, message,
self.configuration.hidden_parameters_current_dir,
"Videos (*.avi *.mov *.mp4 *.ser)", options=options)
file_dialog.setNameFilters(["Still image folder / video file (*.avi *.mov *.mp4 *.ser)"])
# The list of strings (length 1) with the path name to the dark frames is sent by the
# FileDialog via the signal "signal_dialog_ready".
file_dialog.signal_dialog_ready.connect(self.workflow.execute_create_master_dark)
file_dialog.exec_()
@QtCore.pyqtSlot(bool)
def master_dark_created(self, success):
"""
Called from the workflow thread when it has created a master dark frame. This method is
used to save the image to disk.
:param success: A flag indicating if the dark frame was created successfully. Only if true,
write the resulting image to disk.
:return: -
"""
if success:
options = QtWidgets.QFileDialog.Options()
master_dark_file = QtWidgets.QFileDialog.getSaveFileName(self,
"Choose a file name for the new master dark frame",
self.configuration.hidden_parameters_current_dir,
"Images (*png *.tiff *.fits)",
options=options)
if master_dark_file[0]:
Frames.save_image(master_dark_file[0],
self.workflow.calibration.master_dark_frame,
color=self.workflow.calibration.dark_color,
avoid_overwriting=False,
header=self.configuration.global_parameters_version)
# Remember the current directory for next file dialog.
self.configuration.hidden_parameters_current_dir = \
str(Path(master_dark_file[0]).parents[0])
if self.configuration.global_parameters_protocol_level > 1:
Miscellaneous.protocol(" The master dark frame was written to: " +
str(master_dark_file[0]),
self.workflow.attached_log_file,
precede_with_timestamp=False)
# Re-activate GUI elements.
self.gui_set_busy(False)
def load_master_dark(self):
"""
This method is invoked by selecting "Load master dark" from the "Calibration" menu. It
opens a file dialog for selecting a Png, Tiff or Fits file with a master dark frame.
:return: -
"""
options = QtWidgets.QFileDialog.Options()
master_dark_file = QtWidgets.QFileDialog.getOpenFileName(self,
"Select image file containing a master dark frame",
self.configuration.hidden_parameters_current_dir,
"Images (*png *.tiff *.fits)", options=options)
if master_dark_file[0]:
self.signal_load_master_dark.emit(master_dark_file[0])
# Remember the current directory for next file dialog.
self.configuration.hidden_parameters_current_dir = str(
Path(master_dark_file[0]).parents[0])
if self.configuration.global_parameters_protocol_level > 0:
Miscellaneous.protocol("+++ Loading master dark frame +++",
self.workflow.attached_log_file)
def create_master_flat(self):
"""
Open a file dialog for entering a video file or image directory with flat frames. When the
FileDialog closes, it sends a signal (with the path name as payload) to the corresponding
slot on the workflow thread. There the actual master flat computation is performed.
:return: -
"""
options = QtWidgets.QFileDialog.Options()
message = "Select a video file / a folder with image files for computing a master flat" \
" frame"
file_dialog = FileDialog(self, message,
self.configuration.hidden_parameters_current_dir,
"Videos (*.avi *.mov *.mp4 *.ser)", options=options)
file_dialog.setNameFilters(["Still image folder / video file (*.avi *.mov *.mp4 *.ser)"])
# The list of strings (length 1) with the path name to the flat frames is sent by the
# FileDialog via the signal "signal_dialog_ready".
file_dialog.signal_dialog_ready.connect(self.workflow.execute_create_master_flat)
file_dialog.exec_()
@QtCore.pyqtSlot(bool)
def master_flat_created(self, success):
"""
Called from the workflow thread when it has created a master flat frame. This method is
used to save the image to disk.
:param success: A flag indicating if the dark frame was created successfully. Only if true,
write the resulting image to disk.
:return: -
"""
if success:
options = QtWidgets.QFileDialog.Options()
master_flat_file = QtWidgets.QFileDialog.getSaveFileName(self,
"Choose a file name for the new master flat frame",
self.configuration.hidden_parameters_current_dir,
"Images (*png *.tiff *.fits)",
options=options)
if master_flat_file[0]:
Frames.save_image(master_flat_file[0],
self.workflow.calibration.master_flat_frame,
color=self.workflow.calibration.flat_color,
avoid_overwriting=False,
header=self.configuration.global_parameters_version)
# Remember the current directory for next file dialog.
self.configuration.hidden_parameters_current_dir = str(
Path(master_flat_file[0]).parents[0])
if self.configuration.global_parameters_protocol_level > 1:
Miscellaneous.protocol(" The master flat frame was written to: " +
str(master_flat_file[0]),
self.workflow.attached_log_file,
precede_with_timestamp=False)
# Re-activate GUI elements.
self.gui_set_busy(False)
def load_master_flat(self):
"""
This method is invoked by selecting "Load master flat" from the "Calibration" menu. It
opens a file dialog for selecting a Png, Tiff or Fits file with a master flat frame.
:return: -
"""
options = QtWidgets.QFileDialog.Options()
master_flat_file = QtWidgets.QFileDialog.getOpenFileName(self,
"Select image file containing a master dark frame",
self.configuration.hidden_parameters_current_dir,
"Images (*png *.tiff *.fits)", options=options)
if master_flat_file[0]:
self.signal_load_master_flat.emit(master_flat_file[0])
# Remember the current directory for next file dialog.
self.configuration.hidden_parameters_current_dir = str(
Path(master_flat_file[0]).parents[0])
if self.configuration.global_parameters_protocol_level > 0:
Miscellaneous.protocol("+++ Loading master flat frame +++",
self.workflow.attached_log_file)
@QtCore.pyqtSlot(str)
def report_calibration_error(self, message):
if self.configuration.global_parameters_protocol_level > 0:
Miscellaneous.protocol(" " + message,
self.workflow.attached_log_file, precede_with_timestamp=False)
def go_back(self):
"""
Repeat processing steps as specified via the choice of the "comboBox_back" button. The user
can either repeat steps of the current job, or go back to the previous job.
:return: -
"""
# Get the choice of the combobox button.
task = self.ui.comboBox_back.currentText()
if self.configuration.global_parameters_protocol_level > 0:
if self.configuration.global_parameters_store_protocol_with_result and \
self.workflow.attached_log_file.closed:
try:
self.workflow.attached_log_file = open(self.workflow.attached_log_name, 'a')
except:
pass
Miscellaneous.protocol("", self.workflow.attached_log_file,
precede_with_timestamp=False)
Miscellaneous.protocol("+++ Repeating from task: " + task + " +++",
self.workflow.attached_log_file)
# If the end of the job queue was reached, reverse the last job index increment.
if self.job_index == self.job_number and self.job_index > 0:
self.job_index -= 1
# Restart from the specified task within the current job.
if task in ['Read frames', 'Rank frames', 'Select frames', 'Align frames',
'Select stack size', 'Set ROI', 'Set alignment points',
'Compute frame qualities', 'Stack frames', 'Save stacked image',
'Postprocessing', 'Save postprocessed image']:
# Make sure to remove any active interaction widget.
self.display_widget(None, display=False)
self.work_next_task(task)
# Go back to the previous job and start with the first task.
elif task == 'Previous job':
self.job_index -= 1
self.display_widget(None, display=False)
self.work_next_task("Read frames")
def play(self):
"""
This method is invoked when the "Start / Cont." button is pressed.
:return: -
"""
# Start the next task.
self.work_next_task(self.activity)
def pause(self):
"""
This method is invoked when the "Pause" button is pressed.
:return: -
"""
# If the pause flag is not yet set, append a message to the status bar.
if not self.pause:
self.append_status_bar(" Execution will be suspended after current phase.")
# Set the pause flag.
self.pause = True
def go_next(self):
"""
This method is invoked when the "Next Job" button is pressed.
:return: -
"""
self.work_next_task("Next job")
@QtCore.pyqtSlot(str)
def work_next_task(self, next_activity):
"""
This is the central place where all activities are scheduled. Depending on the
"next_activity" chosen, the appropriate activity is started on the workflow thread.
:param next_activity: Activity to be performed next.
:return: -
"""
# Make sure not to process an empty job list, or a job index out of range.
if not self.jobs or self.job_index >= self.job_number:
return
self.activity = next_activity
# Deactivate the current progress widgets. They are reactivated when the workflow thread
# sends a progress signal.
self.show_current_progress_widgets(False)
# If the "Pause" button was pressed during the last activity, stop the workflow.
if self.pause:
self.pause = False
self.busy = False
# Start workflow activities. When a workflow method terminates, it invokes this method on
# the GUI thread, with "next_activity" denoting the next step in the processing chain.
elif self.activity == "Read frames":
# For the first activity (reading all frames from the file system) there is no
# GUI interaction. Start the workflow action immediately.
self.signal_frames.emit(self.jobs[self.job_index])
self.busy = True
elif self.activity == "Rank frames":
if not self.automatic:
pass
self.signal_rank_frames.emit()
self.busy = True
elif self.activity == "Select frames":
# If the dialog to mark frames to be excluded from stacking was requested, open the
# dialog now.
if not self.automatic and self.configuration.frames_add_selection_dialog:
# Reset frames index translation, if active.
if self.workflow.frames.index_translation_active:
self.workflow.frames.reset_index_translation()
self.workflow.rank_frames.reset_index_translation()
fsw = FrameSelectorWidget(self, self.configuration, self.workflow.frames,
self.workflow.rank_frames,
self.workflow.attached_log_file,
self.signal_select_frames)
self.display_widget(fsw)
fsw.listWidget.setFocus()
else:
# The dialog to exclude frames is not to be called. Update index translation
# directly if required.
self.signal_select_frames.emit()
elif self.activity == "Align frames":
# If manual stabilization patch selection was requested in 'Surface' mode, invoke the
# patch editor.
if not self.automatic and not self.configuration.align_frames_automation and \
self.configuration.align_frames_mode == 'Surface':
border = self.configuration.align_frames_search_width
# When the editor is finished, it sends a signal (last argument) to the workflow
# thread with the four coordinate index bounds.
rpew = RectangularPatchEditorWidget(self, self.workflow.frames.frames_mono(
self.workflow.rank_frames.frame_ranks_max_index)[border:-border,
border:-border],
"With 'ctrl' and the left mouse button pressed, draw a "
"rectangular patch to be used for frame alignment. Or just "
"press 'OK / Cancel' (automatic selection).",
self.signal_align_frames)
self.display_widget(rpew)
rpew.viewer.setFocus()
else:
# If all index bounds are set to zero, the stabilization patch is computed
# automatically by the workflow thread.
self.signal_align_frames.emit(0, 0, 0, 0)
self.busy = True
elif self.activity == "Select stack size":
if not self.automatic:
# Reset the ROI, if one was defined before.
self.workflow.align_frames.reset_roi()
# When the frame viewer is finished, it sends a signal which invokes this same
# method on the main thread.
fvw = FrameViewerWidget(self, self.workflow.configuration, self.workflow.frames,
self.workflow.rank_frames, self.workflow.align_frames,
self.workflow.attached_log_file,
self.workflow.work_next_task_signal, "Set ROI")
self.display_widget(fvw)
fvw.frame_viewer.setFocus()
else:
# In automatic mode, nothing is to be done in the workflow thread. Start the next
# activity on the main thread immediately.
self.workflow.work_next_task_signal.emit("Set ROI")
self.busy = True
elif self.activity == "Set ROI":
# Reset the ROI, if one was defined before.
self.workflow.align_frames.reset_roi()
if not self.automatic:
# When the editor is finished, it sends a signal (last argument) to the workflow
# thread with the four coordinate index bounds.
rpew = RectangularPatchEditorWidget(self, self.workflow.align_frames.mean_frame,
"With 'crtl' and the left mouse button pressed, draw a rectangle to set the"
" ROI, or just press 'OK' (no ROI).", self.signal_set_roi)
self.display_widget(rpew)
rpew.viewer.setFocus()
else:
# If all index bounds are set to zero, no ROI is selected.
self.signal_set_roi.emit(0, 0, 0, 0)
self.busy = True
elif self.activity == "Set alignment points":
# In automatic mode, compute the AP grid automatically in the workflow thread. In this
# case, the AlignmentPoints object is created there as well.
if self.automatic:
self.signal_set_alignment_points.emit()
self.busy = True
else:
# If the APs are created interactively, create the AlignmentPoints object here, but
# assign it to the workflow object.
if self.configuration.global_parameters_protocol_level > 0:
Miscellaneous.protocol("+++ Start creating alignment points +++",
self.workflow.attached_log_file)
# Initialize the AlignmentPoints object.
self.workflow.my_timer.create_no_check('Initialize alignment point object')
self.workflow.alignment_points = AlignmentPoints(self.workflow.configuration,
self.workflow.frames, self.workflow.rank_frames, self.workflow.align_frames,
progress_signal=self.workflow.work_current_progress_signal)
self.workflow.my_timer.stop('Initialize alignment point object')
# Open the alignment point editor.
apew = AlignmentPointEditorWidget(self, self.workflow.configuration,
self.workflow.align_frames,
self.workflow.alignment_points,
self.signal_set_alignment_points)
self.display_widget(apew)
apew.viewer.setFocus()
elif self.activity == "Compute frame qualities":
if not self.automatic:
pass
self.signal_compute_frame_qualities.emit()
self.busy = True
elif self.activity == "Stack frames":
if not self.automatic:
pass
self.signal_stack_frames.emit()
self.busy = True
elif self.activity == "Save stacked image":
if self.automatic:
self.signal_save_stacked_image.emit()
else:
sdv = ShiftDistributionViewerWidget(self,
self.workflow.stack_frames.shift_distribution,
self.workflow.stack_frames.shift_failure_percent,
self.signal_save_stacked_image)
self.display_widget(sdv)
self.busy = True
elif self.activity == "Postprocessing":
if self.automatic:
self.signal_postprocess_image.emit()
else:
if self.configuration.global_parameters_protocol_level > 0:
Miscellaneous.protocol("+++ Start postprocessing +++",
self.workflow.attached_log_file)
# In interactive mode the postprocessed image is computed in the GUI thread. The
# resulting image is sent via the "signal_save_postprocessed_image" signal.
pew = PostprocEditorWidget(self.workflow.configuration,
self.workflow.postproc_input_image,
self.workflow.postproc_input_name,
self.write_status_bar,
self.signal_save_postprocessed_image)
self.display_widget(pew)
self.busy = True
elif self.activity == "Save postprocessed image":
if not self.automatic:
pass
# This path is executed for "automatic" mode. In that case the postprocessed image
# is available in the workflow object.
if self.workflow.postprocessed_image is not None:
self.signal_save_postprocessed_image.emit(self.workflow.postprocessed_image)
# Otherwise it has been computed in the PostprocEditor on the GUI thread, and stored
# in the postproc_data_object. If the editor was left with "cancel", the image is set
# to None. In that case the workflow thread will not save the image.
else:
self.signal_save_postprocessed_image.emit(
self.workflow.configuration.postproc_data_object.versions[
self.workflow.configuration.postproc_data_object.version_selected].image)
self.busy = True
elif self.activity == "Next job":
self.job_index += 1
if self.job_index < self.job_number:
# If the end of the queue is not reached yet, start with reading frames of next job.
self.activity = "Read frames"
# If an error condition was set during the current job, reset it.
self.error_occurred = False
if not self.automatic:
pass
self.signal_frames.emit(self.jobs[self.job_index])
else:
# If an error occurred, do not include all phases in "Go back to" combo list. This
# way the user cannot jump back to a phase of the aborted job which was not
# executed.
if self.error_occurred:
self.activity = "Read frames"
self.error_occurred = False
# End of queue reached, give control back to the user.
self.busy = False
# Activate / Deactivate GUI elements depending on the current situation.
self.update_status()
@QtCore.pyqtSlot(str)
def next_job_after_error(self, message):
"""
This method is triggered by the workflow thread via a signal when an error causes a job to
be aborted. In interactive mode a message window shows the error message and asks the user
for confirmation. Depending on the protocol level, the error message is also written to the
protocol (file).
:param message: Error message to be displayed
:return: -
"""
# Report the error.
self.report_error(message)
# Set the error flag.
self.error_occurred = True
# Abort the current job and go to the next one.
self.work_next_task("Next job")
@QtCore.pyqtSlot(str)