Debian Codegraph @

planetary_system_stacker/postproc_editor.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 # -*- coding: utf-8; -*-
2 """
3 Copyright (c) 2018 Rolf Hempel, [email protected]
4
5 This file is part of the PlanetarySystemStacker tool (PSS).
6 https://github.com/Rolf-Hempel/PlanetarySystemStacker
7
8 PSS is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with PSS. If not, see <http://www.gnu.org/licenses/>.
20
21 """
22
23 from copy import copy, deepcopy
24 from math import sqrt
25 from pathlib import Path
26 from sys import argv, stdout, stderr
27 from time import sleep
28
29 import psutil
30 from PyQt5 import QtWidgets, QtCore
31 from PyQt5.QtWidgets import QProxyStyle, QStyle
32 from cv2 import imread, cvtColor, COLOR_BGR2RGB, GaussianBlur, bilateralFilter, BORDER_DEFAULT, \
33 COLOR_BGR2HSV, COLOR_HSV2BGR
34 from numpy import uint8, uint16, float32
35
36 from configuration import Configuration, PostprocLayer
37 from exceptions import InternalError
38 from frame_viewer import FrameViewer
39 from frames import Frames
40 from miscellaneous import Miscellaneous
41 from postproc_editor_gui import Ui_postproc_editor
42 from sharpening_layer_widget import Ui_sharpening_layer_widget
43 from version_manager_widget import Ui_version_manager_widget
44
45
46 class SharpeningLayerWidget(QtWidgets.QWidget, Ui_sharpening_layer_widget):
47 """
48 GUI widget to manipulate the parameters of a sharpening layer. An arbitrary number of sharpening
49 layers can be defined (up to a maximum set as configuration parameter).
50 """
51 signal_toggle_luminance_other_layers = QtCore.pyqtSignal()
52
53 def __init__(self, layer_index, remove_layer_callback, parent=None):
54 """
55 Initialize the widget.
56
57 :param layer_index: Index of the sharpening layer (starting with 1).
58 :param remove_layer_callback: Callback function to remove a layer from the current version.
59 :param parent: Parent object.
60 """
61
62 QtWidgets.QWidget.__init__(self, parent)
63 self.setupUi(self)
64
65 self.layer_index = layer_index
66 self.title = "Layer " + str(layer_index + 1)
67 self.remove_layer_callback = remove_layer_callback
68
69 self.horizontalSlider_radius.valueChanged.connect(self.horizontalSlider_radius_changed)
70 self.lineEdit_radius.textChanged.connect(self.lineEdit_radius_changed)
71 self.horizontalSlider_amount.valueChanged.connect(self.horizontalSlider_amount_changed)
72 self.lineEdit_amount.textChanged.connect(self.lineEdit_amount_changed)
73 self.horizontalSlider_bi_fraction.valueChanged.connect(self.horizontalSlider_bi_fraction_changed)
74 self.lineEdit_bi_fraction.textChanged.connect(self.lineEdit_bi_fraction_changed)
75 self.horizontalSlider_bi_range.valueChanged.connect(
76 self.horizontalSlider_bi_range_changed)
77 self.lineEdit_bi_range.textChanged.connect(self.lineEdit_bi_range_changed)
78 self.horizontalSlider_denoise.valueChanged.connect(
79 self.horizontalSlider_denoise_changed)
80 self.lineEdit_denoise.textChanged.connect(self.lineEdit_denoise_changed)
81 self.checkBox_luminance.stateChanged.connect(self.checkBox_luminance_toggled)
82 self.pushButton_remove.clicked.connect(self.remove_layer)
83
84 def set_values(self, layer):
85 """
86 Set the values of the GUI widget according to the current data model
87
88 :param layer: Layer instance holding the sharpening parameters
89 :return: -
90 """
91
92 self.layer = layer
93
94 self.groupBox_layer.setTitle(self.title)
95 self.horizontalSlider_radius.setValue(self.radius_to_integer(self.layer.radius))
96 self.lineEdit_radius.setText(str(self.layer.radius))
97 self.horizontalSlider_amount.setValue(self.amount_to_integer(self.layer.amount))
98 self.lineEdit_amount.setText("{0:.2f}".format(round(self.layer.amount, 2)))
99 self.horizontalSlider_bi_fraction.setValue(
100 self.bi_fraction_to_integer(self.layer.bi_fraction))
101 self.lineEdit_bi_fraction.setText("{0:.2f}".format(round(self.layer.bi_fraction, 2)))
102 self.horizontalSlider_bi_range.setValue(self.bi_range_to_integer(self.layer.bi_range))
103 self.lineEdit_bi_range.setText(str(self.layer.bi_range))
104 self.horizontalSlider_denoise.setValue(
105 self.denoise_to_integer(self.layer.denoise))
106 self.lineEdit_denoise.setText("{0:.2f}".format(round(self.layer.denoise, 2)))
107
108 # Temporarily block signals for the luminance checkbox. Otherwise the variable would be
109 # switched immediately.
110 self.checkBox_luminance.blockSignals(True)
111 self.checkBox_luminance.setChecked(self.layer.luminance_only)
112 self.checkBox_luminance.blockSignals(False)
113
114 # The following four methods implement the translation between data model values and the
115 # (integer) values of the horizontal GUI sliders. In the case of the sharpening amount this
116 # translation is non-linear in order to add resolution at small values.
117 @staticmethod
118 def radius_to_integer(radius):
119 return max(min(round(radius * 10.), 99), 1)
120
121 @staticmethod
122 def integer_to_radius(int):
123 return int / 10.
124
125 @staticmethod
126 def amount_to_integer(amount):
127 # Below the slider value 20 (amount = 1.) the behaviour is linear, above quadratic.
128 if amount > 1.:
129 a = 187. / 6400.
130 b = 0.15 - 40. * a
131 c = 400. * a - 2.
132 return (round(-b / (2. * a) + sqrt(b**2 / a**2 / 4. - (c - amount) / a)))
133 else:
134 return round((amount + 2.) / 0.15)
135
136 @staticmethod
137 def integer_to_amount(integer):
138 if integer <= 20:
139 return -2. + 0.15 * integer
140 else:
141 a = 187. / 6400.
142 b = 0.15 - 40. * a
143 c = 400. * a - 2.
144 return round(a * integer**2 + b * integer + c, 2)
145
146 @staticmethod
147 def bi_fraction_to_integer(bi_fraction):
148 return round(bi_fraction * 100)
149
150 @staticmethod
151 def integer_to_bi_fraction(integer):
152 return integer / 100.
153
154 @staticmethod
155 def bi_range_to_integer(bi_range):
156 # Below the slider value 50 (bi_range = 13.) the behaviour is linear, above quadratic.
157 if bi_range > 13.:
158 c = 0.009022222222222221
159 g = 35.59113300492611
160 h = -1233.2712514256596
161 return round(g + sqrt(h + bi_range / c))
162 else:
163 b = 0.26
164 return round(bi_range / b)
165
166 @staticmethod
167 def integer_to_bi_range(integer):
168 if integer <= 50:
169 b = 0.26
170 return round(b * integer, 1)
171 else:
172 c = 0.009022222222222221
173 e = -0.6422222222222221
174 f = 22.555555555555554
175 return round(c * integer ** 2 + e * integer + f, 1)
176
177 @staticmethod
178 def denoise_to_integer(denoise):
179 return round(denoise * 100)
180
181 @staticmethod
182 def integer_to_denoise(integer):
183 return integer / 100.
184
185 def horizontalSlider_radius_changed(self):
186 """
187 The "radius" slider has been moved. Update the corresponding lineEdit widget. Block its
188 signals temporarily to avoid cross-talk.
189 :return: -
190 """
191
192 self.layer.radius = self.integer_to_radius(self.horizontalSlider_radius.value())
193 self.lineEdit_radius.blockSignals(True)
194 self.lineEdit_radius.setText(str(self.layer.radius))
195 self.lineEdit_radius.blockSignals(False)
196
197 def lineEdit_radius_changed(self):
198 """
199 The text of the lineEdit widget has been changed. Update the horizontal slider. Include a
200 try-except block to avoid illegal user input to crash the program.
201
202 :return: -
203 """
204
205 try:
206 self.layer.radius = max(0.1, min(float(self.lineEdit_radius.text()), 9.9))
207 self.horizontalSlider_radius.blockSignals(True)
208 self.horizontalSlider_radius.setValue(self.radius_to_integer(self.layer.radius))
209 self.horizontalSlider_radius.blockSignals(False)
210 except:
211 pass
212
213 def horizontalSlider_amount_changed(self):
214 """
215 The same as above for the "amount" parameter.
216
217 :return: -
218 """
219
220 self.layer.amount = self.integer_to_amount(self.horizontalSlider_amount.value())
221 self.lineEdit_amount.blockSignals(True)
222 self.lineEdit_amount.setText("{0:.2f}".format(round(self.layer.amount, 2)))
223 self.lineEdit_amount.blockSignals(False)
224
225 def lineEdit_amount_changed(self):
226 """
227 The same as above for the "amount" parameter.
228
229 :return: -
230 """
231
232 try:
233 self.layer.amount = float(self.lineEdit_amount.text())
234 self.horizontalSlider_amount.blockSignals(True)
235 self.horizontalSlider_amount.setValue(self.amount_to_integer(self.layer.amount))
236 self.horizontalSlider_amount.blockSignals(False)
237 except:
238 pass
239
240 def horizontalSlider_bi_fraction_changed(self):
241 """
242 The same as above for the "bi_fraction" parameter.
243
244 :return: -
245 """
246
247 self.layer.bi_fraction = self.integer_to_bi_fraction(self.horizontalSlider_bi_fraction.value())
248 self.lineEdit_bi_fraction.blockSignals(True)
249 self.lineEdit_bi_fraction.setText("{0:.2f}".format(round(self.layer.bi_fraction, 2)))
250 self.lineEdit_bi_fraction.blockSignals(False)
251
252 def lineEdit_bi_fraction_changed(self):
253 """
254 The same as above for the "bi_fraction" parameter.
255
256 :return: -
257 """
258
259 try:
260 self.layer.bi_fraction = float(self.lineEdit_bi_fraction.text())
261 self.horizontalSlider_bi_fraction.blockSignals(True)
262 self.horizontalSlider_bi_fraction.setValue(self.bi_fraction_to_integer(self.layer.bi_fraction))
263 self.horizontalSlider_bi_fraction.blockSignals(False)
264 except:
265 pass
266
267 def horizontalSlider_bi_range_changed(self):
268 """
269 The same as above for the "bi_range" parameter.
270
271 :return: -
272 """
273
274 self.layer.bi_range = self.integer_to_bi_range(self.horizontalSlider_bi_range.value())
275 self.lineEdit_bi_range.blockSignals(True)
276 self.lineEdit_bi_range.setText(str(self.layer.bi_range))
277 self.lineEdit_bi_range.blockSignals(False)
278
279 def lineEdit_bi_range_changed(self):
280 """
281 The same as above for the "bi_range" parameter.
282
283 :return: -
284 """
285
286 try:
287 self.layer.bi_range = max(0, min(int(round(float(self.lineEdit_bi_range.text()))), 255))
288 self.horizontalSlider_bi_range.blockSignals(True)
289 self.horizontalSlider_bi_range.setValue(self.bi_range_to_integer(self.layer.bi_range))
290 self.horizontalSlider_bi_range.blockSignals(False)
291 except:
292 pass
293
294 def horizontalSlider_denoise_changed(self):
295 """
296 The same as above for the "denoise" parameter.
297
298 :return: -
299 """
300
301 self.layer.denoise = self.integer_to_denoise(self.horizontalSlider_denoise.value())
302 self.lineEdit_denoise.blockSignals(True)
303 self.lineEdit_denoise.setText("{0:.2f}".format(round(self.layer.denoise, 2)))
304 self.lineEdit_denoise.blockSignals(False)
305
306 def lineEdit_denoise_changed(self):
307 """
308 The same as above for the "denoise" parameter.
309
310 :return: -
311 """
312
313 try:
314 self.layer.denoise = float(self.lineEdit_denoise.text())
315 self.horizontalSlider_denoise.blockSignals(True)
316 self.horizontalSlider_denoise.setValue(self.denoise_to_integer(self.layer.denoise))
317 self.horizontalSlider_denoise.blockSignals(False)
318 except:
319 pass
320
321
322 def checkBox_luminance_toggled(self):
323 """
324 The checkbox which tells if the sharpening should affect the luminance channel only has
325 changed its state.
326
327 :return: -
328 """
329
330 self.layer.luminance_only = not self.layer.luminance_only
331
332 # Signal the other layers to change the flag as well.
333 self.signal_toggle_luminance_other_layers.emit()
334
335 @QtCore.pyqtSlot()
336 def checkBox_luminance_toggled_no_signal(self):
337 """
338 The checkbox which tells if the sharpening should affect the luminance channel only has
339 changed its state. This version of the method is invoked by another layer which has changed
340 the toggle state. In this case, not only toggle the state variable, but also toggle the
341 checkbox widget (because this was not done by the user). To avoid an avalanche, do not emit
342 a signal.
343
344 :return: -
345 """
346
347 # Block the signals of this widget to avoid a feedback loop.
348 self.checkBox_luminance.blockSignals(True)
349 self.checkBox_luminance.setChecked(not self.checkBox_luminance.isChecked())
350 self.checkBox_luminance.blockSignals(False)
351 self.layer.luminance_only = not self.layer.luminance_only
352
353 def remove_layer(self):
354 """
355 This method is executed when the user presses the "remove" button. The actual action is
356 performed by the higher-level "PostprocEditorWidget" object.
357 :return: -
358 """
359
360 self.remove_layer_callback(self.layer_index)
361
362
363 class CustomStyle(QProxyStyle):
364 """
365 This class is used to prevent the version spinbox from jumping two steps at once. The solution
366 was found on Stackoverflow
367 (https://stackoverflow.com/questions/40746350/why-qspinbox-jumps-twice-the-step-value).
368
369 """
370
371 def styleHint(self, hint, option=None, widget=None, returnData=None):
372 if hint == QStyle.SH_SpinBox_KeyPressAutoRepeatRate:
373 return 10**6
374 elif hint == QStyle.SH_SpinBox_ClickAutoRepeatRate:
375 return 10**6
376 elif hint == QStyle.SH_SpinBox_ClickAutoRepeatThreshold:
377 # You can use only this condition to avoid the auto-repeat,
378 # but better safe than sorry ;-)
379 return 10**6
380 else:
381 return super().styleHint(hint, option, widget, returnData)
382
383
384 class VersionManagerWidget(QtWidgets.QWidget, Ui_version_manager_widget):
385 """
386 This GUI widget manages the different postprocessing versions and controls which image is
387 displayed in the image viewer. It also starts and controls the blink comparator.
388 """
389
390 # The set_photo_signal tells the image viewer which image it should show.
391 set_photo_signal = QtCore.pyqtSignal(int)
392 # The blink comparator emits the variant_shown_signal to highlight / de-highlight the GUI image
393 # selector which corresponds to the image currently displayed.
394 variant_shown_signal = QtCore.pyqtSignal(bool, bool)
395 # This signal tells the PostprocEditorWidget to show the selected version in the frame viewer.
396 select_version_signal = QtCore.pyqtSignal(int)
397
398 def __init__(self, configuration, parent=None):
399 """
400
401 :param configuration: Configuration object with parameters.
402 :param parent: parent object.
403 """
404
405 QtWidgets.QWidget.__init__(self, parent)
406 self.setupUi(self)
407 self.configuration = configuration
408 self.pss_version = configuration.global_parameters_version
409 self.postproc_data_object = configuration.postproc_data_object
410 self.postproc_blinking_period = configuration.postproc_blinking_period
411
412 self.spinBox_version.valueChanged.connect(self.select_version)
413 self.spinBox_compare.valueChanged.connect(self.select_version_compared)
414 self.pushButton_new.clicked.connect(self.new_version)
415 self.pushButton_delete.clicked.connect(self.remove_version)
416 self.checkBox_blink_compare.stateChanged.connect(self.blinking_toggled)
417 self.pushButton_save.clicked.connect(self.save_version)
418 self.pushButton_save_as.clicked.connect(self.save_version_as)
419 self.variant_shown_signal.connect(self.highlight_variant)
420
421 # Set the ranges for version selection spinboxes. Initially, there are only two versions.
422 self.spinBox_version.setMaximum(configuration.postproc_data_object.number_versions)
423 self.spinBox_version.setMinimum(0)
424 self.spinBox_compare.setMaximum(configuration.postproc_data_object.number_versions)
425 self.spinBox_compare.setMinimum(0)
426 self.spinBox_version.setStyle(CustomStyle())
427 self.spinBox_compare.setStyle(CustomStyle())
428
429 # Set the spinbox to the newly created version.
430 self.spinBox_version.setValue(self.postproc_data_object.version_selected)
431
432 def select_version(self):
433 """
434 This method is called when the user changes the setting of the "version selected" spinbox.
435
436 :return: -
437 """
438 self.postproc_data_object.version_selected = self.spinBox_version.value()
439 self.select_version_signal.emit(self.postproc_data_object.version_selected)
440
441 def select_version_compared(self):
442 """
443 This method is called when the user changes the setting of the "version compared" spinbox.
444 The "selected" and "compared" versions are displayed alternately by the blink comparator.
445 :return: -
446 """
447
448 self.postproc_data_object.version_compared = self.spinBox_compare.value()
449
450 def new_version(self):
451 """
452 Create a new postprocessing version.
453 :return: -
454 """
455
456 # Create a Version object by copying the parameters from the selected version.
457 new_version = self.postproc_data_object.new_postproc_version_from_existing()
458
459 # If the new version was created from the original image (version 0), add an initial layer.
460 if self.postproc_data_object.version_selected == 1:
461 new_version.add_postproc_layer(PostprocLayer("Multilevel unsharp masking", 1., 1., 0.,
462 self.configuration.postproc_bi_range_standard, 0., False))
463
464 # Set the image viewer to the new version, and increase the range of spinboxes to include
465 # the new version.
466 self.set_photo_signal.emit(self.postproc_data_object.version_selected)
467 self.spinBox_version.setMaximum(self.postproc_data_object.number_versions)
468 self.spinBox_version.setValue(self.postproc_data_object.number_versions)
469 self.spinBox_compare.setMaximum(self.postproc_data_object.number_versions)
470
471 def remove_version(self):
472 """
473 Remove a postprocessing version.
474 :return: -
475 """
476
477 # Remove the version from the central data object, and instruct the image viewer to
478 # show the previous version.
479 self.postproc_data_object.remove_postproc_version(self.postproc_data_object.version_selected)
480 self.set_photo_signal.emit(self.postproc_data_object.version_selected)
481
482 # Adjust the spinbox bounds, and set the current version parameters to the new selection.
483 self.spinBox_version.setMaximum(self.postproc_data_object.number_versions)
484
485 # Set the spinbox to the version before the deleted one.
486 self.spinBox_version.setValue(self.postproc_data_object.version_selected)
487
488 self.spinBox_compare.setMaximum(self.postproc_data_object.number_versions)
489 self.spinBox_compare.setValue(
490 min(self.spinBox_compare.value(), self.postproc_data_object.number_versions))
491 self.select_version_signal.emit(self.postproc_data_object.version_selected)
492
493 def blinking_toggled(self):
494 """
495 Switch the blink comparator on or off.
496
497 :return: -
498 """
499
500 # Toggle the status variable.
501 self.postproc_data_object.blinking = not self.postproc_data_object.blinking
502
503 # The blink comparator is switched on.
504 if self.postproc_data_object.blinking:
505 # Create the blink comparator thread and start it.
506 self.blink_comparator = BlinkComparator(self.postproc_data_object,
507 self.postproc_blinking_period,
508 self.set_photo_signal,
509 self.variant_shown_signal)
510 self.blink_comparator.setTerminationEnabled(True)
511
512 # The blink comparator is switched off. Set the image viewer to the currently selected
513 # image and terminate the separate thread.
514 else:
515 self.set_photo_signal.emit(self.postproc_data_object.version_selected)
516 self.blink_comparator.stop()
517
518 def highlight_variant(self, selected, compare):
519 """
520 Whenever the blink comparator changes the display, the spinbox corressponding to the
521 currently displayed image changes its font color to red. The other spinbox is blanked out
522 (by setting font color to white). When the blink comparator is not active, both spinboxes
523 show their numbers in bladk font.
524
525 :param selected: True, if the image corresponding to the "selected" spinbox is displayed.
526 False, otherwise.
527 :param compare: True, if the image corresponding to the "compared" spinbox is displayed.
528 False, otherwise.
529 :return: -
530 """
531
532 if selected and compare:
533 self.spinBox_version.setStyleSheet('color: red')
534 self.spinBox_compare.setStyleSheet('color: red')
535 elif not selected and not compare:
536 self.spinBox_version.setStyleSheet('color: black')
537 self.spinBox_compare.setStyleSheet('color: black')
538 elif selected:
539 self.spinBox_version.setStyleSheet('color: red')
540 self.spinBox_compare.setStyleSheet('color: white')
541 elif compare:
542 self.spinBox_version.setStyleSheet('color: white')
543 self.spinBox_compare.setStyleSheet('color: red')
544
545 def save_version(self):
546 """
547 save the result as 16bit png, tiff or fits file at the standard location.
548
549 :return: -
550 """
551
552 # In case "correction mode" is on, process the current version image in full 16bit
553 # resolution.
554 self.postproc_data_object.finalize_postproc_version()
555 Frames.save_image(self.postproc_data_object.file_name_processed,
556 self.postproc_data_object.versions[
557 self.postproc_data_object.version_selected].image,
558 color=self.postproc_data_object.color, avoid_overwriting=False,
559 header=self.pss_version)
560
561 def save_version_as(self):
562 """
563 save the result as 16bit png, tiff or fits file at a location selected by the user.
564
565 :return: -
566 """
567
568 options = QtWidgets.QFileDialog.Options()
569 filename, extension = QtWidgets.QFileDialog.getSaveFileName(self,
570 "Save result as 16bit png, tiff or fits image",
571 self.postproc_data_object.file_name_processed,
572 "Image Files (*.png *.tiff *.fits)", options=options)
573
574 if filename and extension:
575 self.postproc_data_object.finalize_postproc_version()
576 Frames.save_image(filename,
577 self.postproc_data_object.versions[
578 self.postproc_data_object.version_selected].image,
579 color=self.postproc_data_object.color, avoid_overwriting=False,
580 header=self.pss_version)
581
582
583 class BlinkComparator(QtCore.QThread):
584 """
585 This class implements the blink comparator. It shows alternately two image versions.
586 """
587
588 def __init__(self, postproc_data_object, postproc_blinking_period, set_photo_signal,
589 variant_shown_signal, parent=None):
590 """
591 :param postproc_data_object: The central postprocessing data object.
592 :param postproc_blinking_period: Time between image switching.
593 :param set_photo_signal: Signal which tells the image viewer which image it should show.
594 :param variant_shown_signal: Signal which tells the GUI widget which spinbox should be
595 highlighted.
596 :param parent: Parent object
597 """
598
599 QtCore.QThread.__init__(self, parent)
600 self.postproc_data_object = postproc_data_object
601 self.postproc_blinking_period = postproc_blinking_period
602 self.set_photo_signal = set_photo_signal
603 self.variant_shown_signal = variant_shown_signal
604
605 # Initially, no version is shown by the blink comparator.
606 self.variant_shown_signal.emit(False, False)
607
608 # Start the comparator thread.
609 self.start()
610
611 def run(self):
612 """
613 Blink comparator main loop. As long as the "blinking" status variable is True, show the
614 two image versions alternately.
615
616 :return: -
617 """
618
619 # Begin with showing the "selected" version.
620 show_selected_version = True
621
622 # Begin main loop.
623 while self.postproc_data_object.blinking:
624 # Show the "selected" version.
625 if show_selected_version:
626 # In case the blink comparator is invoked during manual RGB shift corrections,
627 # produce a final image of the selected version before blinking.
628 self.postproc_data_object.finalize_postproc_version()
629 self.set_photo_signal.emit(self.postproc_data_object.version_selected)
630 self.variant_shown_signal.emit(True, False)
631 # Show the "compared" version.
632 else:
633 self.postproc_data_object.finalize_postproc_version(
634 version_index=self.postproc_data_object.version_compared)
635 self.set_photo_signal.emit(self.postproc_data_object.version_compared)
636 self.variant_shown_signal.emit(False, True)
637
638 # Toggle back and forth between first and second image version.
639 show_selected_version = not show_selected_version
640
641 # Sleep time inserted to limit CPU consumption by idle looping.
642 sleep(self.postproc_blinking_period)
643
644 def stop(self):
645 """
646 Terminate the blink comparator thread.
647
648 :return: -
649 """
650
651 self.variant_shown_signal.emit(False, False)
652 self.terminate()
653
654
655 class ImageProcessor(QtCore.QThread):
656 """
657 This class implements the asynchronous computation of new image versions.
658 """
659
660 # The set_photo_signal tells the image viewer which image it should show.
661 set_photo_signal = QtCore.pyqtSignal(int)
662 # The set_shift_display_signal tells the PostprocEditorWidget to update the display of RGB
663 # shift values.
664 set_shift_display_signal = QtCore.pyqtSignal()
665 # The set_status_bar_signal triggers the display of a (colored) message in the main GUI's
666 # status bar.
667 set_status_bar_signal = QtCore.pyqtSignal(str, str)
668 # While computations are going on, GUI widgets are disabled to avoid race conditions.
669 disable_widgets_signal = QtCore.pyqtSignal()
670 # When computations have finished, reactivate GUI widgets.
671 enable_widgets_signal = QtCore.pyqtSignal()
672
673 def __init__(self, configuration, parent=None):
674 """
675 Whenever the parameters of the current version change, compute a new sharpened image.
676
677 :param configuration: Data object with configuration parameters
678 """
679
680 QtCore.QThread.__init__(self, parent)
681 self.configuration = configuration
682 self.postproc_data_object = self.configuration.postproc_data_object
683 self.postproc_idle_loop_time = self.configuration.postproc_idle_loop_time
684
685 # Extract the file name from its path.
686 self.file_name = Path(self.postproc_data_object.file_name_original).name
687
688 self.start()
689
690 def run(self):
691
692 # Before executing the main loop, initialize images for all versions kept in the version
693 # manager. In particular if versions have the "Auto RGB alignment" checkbox set, this may
694 # take a while.
695
696 # Change the main GUI's status bar to show that a computation is going on, and disable GUI
697 # widgets to avoid race conditions.
698 self.set_status_bar_signal.emit("Postprocessing " + self.file_name +
699 ", busy computing initial images for all versions; "
700 "This will take a while",
701 "black")
702 self.disable_widgets_signal.emit()
703
704 # Do the computations in float32 to avoid clipping effects. If the input image is color,
705 # also create a version for "luminance only" computations.
706 self.image_original = self.postproc_data_object.image_original.astype(float32)
707 self.color = len(self.image_original.shape) == 3
708 if self.color:
709 self.image_original_hsv = cvtColor(self.image_original, COLOR_BGR2HSV)
710
711 # Initialize list of auto-rgb-aligned input images for all resolution levels.
712 self.auto_rgb_aligned_images_original = [None, None, None]
713 if self.color:
714 self.auto_rgb_aligned_images_original_hsv = [None, None, None]
715 self.auto_rgb_shifts_red = [None, None, None]
716 self.auto_rgb_shifts_blue = [None, None, None]
717
718 # Initialize images for all versions using the current layer data.
719 self.last_version_layers = []
720
721 for version in self.postproc_data_object.versions:
722 # For every version, keep a copy of the current layer parameters for later checks for
723 # changes. Also, remember if for this version RGB alignment was active.
724 self.last_version_layers.append(deepcopy(version.layers))
725 version.last_rgb_automatic = version.rgb_automatic
726
727 # If automatic RGB alignment is selected for this version, compute the shifted
728 # original image for this version's resolution if not yet available.
729 if version.rgb_automatic:
730 if self.auto_rgb_aligned_images_original[version.rgb_resolution_index] is None:
731 try:
732 self.auto_rgb_aligned_images_original[version.rgb_resolution_index], \
733 self.auto_rgb_shifts_red[version.rgb_resolution_index], \
734 self.auto_rgb_shifts_blue[
735 version.rgb_resolution_index] = Miscellaneous.auto_rgb_align(
736 self.image_original, self.configuration.postproc_max_shift,
737 interpolation_factor=[1, 2, 4][version.rgb_resolution_index],
738 blur_strength=version.rgb_gauss_width)
739 if self.color:
740 self.auto_rgb_aligned_images_original_hsv[
741 version.rgb_resolution_index] = cvtColor(
742 self.auto_rgb_aligned_images_original[version.rgb_resolution_index],
743 COLOR_BGR2HSV)
744 except:
745 self.auto_rgb_aligned_images_original[
746 version.rgb_resolution_index] = self.image_original
747 self.auto_rgb_shifts_red[version.rgb_resolution_index] = (0., 0.)
748 self.auto_rgb_shifts_blue[version.rgb_resolution_index] = (0., 0.)
749 if self.color:
750 self.auto_rgb_aligned_images_original_hsv[
751 version.rgb_resolution_index] = self.image_original_hsv
752
753 version.image = Miscellaneous.post_process(
754 self.auto_rgb_aligned_images_original[version.rgb_resolution_index],
755 version.layers)
756 # If shifts were set manually, apply them before sharpening the input image.
757 elif version.shift_red != (0., 0.) or version.shift_blue != (0., 0.):
758 # Shift the image with the resolution given by the selected interpolation factor.
759 interpolation_factor = [1, 2, 4][version.rgb_resolution_index]
760 shifted_image = Miscellaneous.shift_colors(self.image_original,
761 version.shift_red, version.shift_blue,
762 interpolate_input=interpolation_factor,
763 reduce_output=interpolation_factor)
764 version.image = Miscellaneous.post_process(shifted_image, version.layers)
765 # No RGB corrections were specified.
766 else:
767 version.image = Miscellaneous.post_process(self.image_original, version.layers)
768
769 # Initialize lists for intermediate results (to speed up image updates). The efficient
770 # reuse of intermediate results is only possible if there is enough RAM.
771 self.reset_intermediate_images()
772 self.ram_sufficient = True
773
774 # Reset the status bar to its idle state, and enable GUI widgets.
775 self.set_status_bar_signal.emit("Postprocessing " + self.file_name,
776 "black")
777 self.enable_widgets_signal.emit()
778
779 # Remember the last version (and the corresponding layer parameters) shown in the image
780 # viewer. As soon as this index changes, a new image is displayed.
781 self.last_version_selected = 0
782
783 # Initialize the data objects holding the currently active and the previous version.
784 self.version_selected = None
785 self.layers_selected = None
786
787 # Initialize Exception state.
788 exception_status = False
789
790 # Enter the main loop and wait for parameter changes in the version selected.
791 while True:
792
793 # The whole computation is enclosed in a try/except block. If something goes wrong, e.g.
794 # because during the execution of a loop pass the postproc_data_object was changed by
795 # the GUI thread, the ImageProcessor tries again in the next pass.
796 try:
797 # To avoid chasing a moving target, copy the parameters of the currently active version
798 self.version_selected = self.postproc_data_object.version_selected
799 postproc_version = deepcopy(self.postproc_data_object.versions[self.version_selected])
800 self.layers_selected = postproc_version.layers
801 self.rgb_automatic = postproc_version.rgb_automatic
802 self.rgb_resolution_index = postproc_version.rgb_resolution_index
803 self.rgb_gauss_width = postproc_version.rgb_gauss_width
804 self.shift_red = postproc_version.shift_red
805 self.shift_blue = postproc_version.shift_blue
806 self.correction_red = postproc_version.correction_red
807 self.correction_blue = postproc_version.correction_blue
808 self.correction_red_saved = postproc_version.correction_red_saved
809 self.correction_blue_saved = postproc_version.correction_blue_saved
810
811 compute_new_image = False
812 shift_image = False
813
814 # If the RGB auto-alignment checkbox was changed since the last image was computed for
815 # this version, invalidate all intermediate results for this version.
816 if self.rgb_automatic != self.postproc_data_object.versions[
817 self.version_selected].last_rgb_automatic:
818 self.postproc_data_object.versions[
819 self.version_selected].last_rgb_automatic = self.rgb_automatic
820 self.reset_intermediate_images()
821 compute_new_image = True
822
823 # If automatic RGB alignment is on, check if the shifted image for the current
824 # resolution has been computed already. Otherwise, compute it now.
825 if self.rgb_automatic:
826 if self.auto_rgb_aligned_images_original[
827 self.rgb_resolution_index] is None:
828
829 # Change the main GUI's status bar to show that a computation is going on.
830 self.set_status_bar_signal.emit("Postprocessing " + self.file_name +
831 ", busy auto-aligning image", "black")
832 self.disable_widgets_signal.emit()
833 try:
834 self.auto_rgb_aligned_images_original[self.rgb_resolution_index], \
835 self.auto_rgb_shifts_red[self.rgb_resolution_index], \
836 self.auto_rgb_shifts_blue[
837 self.rgb_resolution_index] = Miscellaneous.auto_rgb_align(
838 self.image_original, self.configuration.postproc_max_shift,
839 interpolation_factor=[1, 2, 4][self.rgb_resolution_index],
840 blur_strength=self.rgb_gauss_width)
841 if self.color:
842 self.auto_rgb_aligned_images_original_hsv[
843 self.rgb_resolution_index] = cvtColor(
844 self.auto_rgb_aligned_images_original[self.rgb_resolution_index],
845 COLOR_BGR2HSV)
846 except:
847 self.auto_rgb_aligned_images_original[
848 self.rgb_resolution_index] = self.image_original
849 self.auto_rgb_shifts_red[self.rgb_resolution_index] = (0., 0.)
850 self.auto_rgb_shifts_blue[self.rgb_resolution_index] = (0., 0.)
851 if self.color:
852 self.auto_rgb_aligned_images_original_hsv[
853 self.rgb_resolution_index] = self.image_original_hsv
854 # Reset the status bar to its idle state.
855 self.set_status_bar_signal.emit("Postprocessing " + self.file_name, "black")
856 self.enable_widgets_signal.emit()
857
858 # Since the auto-shifted image is new, the postprocessing pipeline must be
859 # applied. (This does not seem to be necessary.)
860 # compute_new_image = True
861
862 # Set the processing pipeline input to the RGB aligned original image.
863 self.input_image = self.auto_rgb_aligned_images_original[self.rgb_resolution_index]
864 if self.color:
865 self.input_image_hsv = self.auto_rgb_aligned_images_original_hsv[
866 self.rgb_resolution_index]
867
868 # Set the RGB shifts for this version to the values computed automatically.
869 self.postproc_data_object.versions[self.version_selected].shift_red = \
870 self.auto_rgb_shifts_red[self.rgb_resolution_index]
871 self.postproc_data_object.versions[self.version_selected].shift_blue = \
872 self.auto_rgb_shifts_blue[self.rgb_resolution_index]
873
874 # In correction mode the wavelets are computed only once, and then only the shift
875 # corrections are applied.
876 elif postproc_version.rgb_correction_mode:
877
878 # If the uncorrected image for this resolution index is not available, it must be
879 # computed. Try if an image for this version has been computed. If not, this version
880 # is new. In that case process the wavelets first (only applying the accumulated
881 # shifts), and do the shift corrections in the next pass.
882 if postproc_version.images_uncorrected[self.rgb_resolution_index] is None:
883
884 # Change the main GUI's status bar to show that correction mode is being
885 # initialized.
886 self.set_status_bar_signal.emit("Postprocessing " + self.file_name +
887 ", initializing manual alignment", "black")
888 self.disable_widgets_signal.emit()
889
890 if postproc_version.image is None or postproc_version.image.dtype == uint8:
891 self.input_image = Miscellaneous.shift_colors(self.image_original,
892 postproc_version.shift_red,
893 postproc_version.shift_blue)
894 if self.color:
895 if postproc_version.shift_red != (
896 0., 0.) or postproc_version.shift_blue != (0., 0.):
897 self.input_image_hsv = cvtColor(self.input_image, COLOR_BGR2HSV)
898 else:
899 self.input_image_hsv = self.image_original_hsv
900
901 self.reset_intermediate_images()
902 compute_new_image = True
903
904 # The postprocessing pipeline has been applied to this version before, set the
905 # input for this resolution index of the correction mode. The image is
906 # blown up by the resolution factor to show shifts in detail.
907 else:
908 # In the first pass, convert the input image to 8bit unsigned int (to speed
909 # up the image viewer). Store it as resolution version 0 (1 Pixel, i.e. no
910 # change in resolution).
911 if self.postproc_data_object.versions[
912 self.version_selected].images_uncorrected[0] is None:
913 self.postproc_data_object.versions[
914 self.version_selected].images_uncorrected[0] = (
915 postproc_version.image / 256.).astype(
916 uint8)
917
918 # If the resolution selected is not 1 pixel, interpolate the 1 pixel image
919 # to the required resolution and store the result for later reuse.
920 if self.rgb_resolution_index > 0:
921 self.postproc_data_object.versions[
922 self.version_selected].images_uncorrected[
923 self.rgb_resolution_index] = \
924 Miscellaneous.shift_colors(self.postproc_data_object.versions[
925 self.version_selected].images_uncorrected[0], (0., 0.), (0., 0.),
926 interpolate_input=[1, 2, 4][self.rgb_resolution_index])
927 shift_image = True
928
929 # Reset the status bar to its idle state.
930 self.set_status_bar_signal.emit("Postprocessing " + self.file_name, "black")
931 self.enable_widgets_signal.emit()
932
933 # The image without shift correction is available for the required resolution. Check
934 # if the shift correction has changed. If so, apply the correction. Otherwise, leave
935 # the image unchanged.
936 elif self.correction_red != self.correction_red_saved or self.correction_blue != \
937 self.correction_blue_saved:
938 self.postproc_data_object.versions[
939 self.version_selected].correction_red_saved = self.correction_red
940 self.postproc_data_object.versions[
941 self.version_selected].correction_blue_saved = self.correction_blue
942 shift_image = True
943
944 # Wavelet mode, RGB auto-alignment off: Set the input image for the processing pipeline
945 # to the original image, shifted by the accumulated shift vectors (not in correction
946 # mode).
947 else:
948 # The accumulated shift vectors have changed since the last computation. Apply the
949 # new shifts to the original image.
950 if postproc_version.shift_red != postproc_version.shift_red_saved or \
951 postproc_version.shift_blue != postproc_version.shift_blue_saved:
952 self.input_image = Miscellaneous.shift_colors(self.image_original,
953 postproc_version.shift_red,
954 postproc_version.shift_blue)
955 if self.color:
956 if postproc_version.shift_red != (
957 0., 0.) or postproc_version.shift_blue != (0., 0.):
958 self.input_image_hsv = cvtColor(self.input_image, COLOR_BGR2HSV)
959 else:
960 self.input_image_hsv = self.image_original_hsv
961
962 # Save the new shifted original image together with the current accumulated
963 # shift vectors.
964 self.postproc_data_object.versions[self.version_selected].input_image_saved = \
965 self.input_image
966 if self.color:
967 self.postproc_data_object.versions[
968 self.version_selected].input_image_hsv_saved = self.input_image_hsv
969 self.postproc_data_object.versions[self.version_selected].shift_red_saved = \
970 postproc_version.shift_red
971 self.postproc_data_object.versions[
972 self.version_selected].shift_blue_saved = postproc_version.shift_blue
973
974 # Since the processing pipeline input has changed, reset intermediate results
975 # and set the computation flag.
976 self.reset_intermediate_images()
977 compute_new_image = True
978
979 # The accumulated shift vectors have not changed. Reuse the saved pipeline input
980 # images.
981 else:
982 self.input_image = postproc_version.input_image_saved
983 if self.color:
984 self.input_image_hsv = postproc_version.input_image_hsv_saved
985
986 self.set_shift_display_signal.emit()
987
988 # End of preparatory phase. Flags "compute_new_image" or "shift_image" have been set.
989 # Now perform the appropriate action.
990
991 # The image has already passed the postprocessing pipeline (as contained in
992 # postproc_version.images_uncorrected). Only the correction shift must be applied.
993 if shift_image:
994 interpolation_factor = [1, 2, 4][self.rgb_resolution_index]
995 self.postproc_data_object.versions[self.version_selected].image = \
996 Miscellaneous.shift_colors(
997 self.postproc_data_object.versions[
998 self.version_selected].images_uncorrected[self.rgb_resolution_index],
999 (self.correction_red[0] * interpolation_factor,
1000 self.correction_red[1] * interpolation_factor),
1001 (self.correction_blue[0] * interpolation_factor,
1002 self.correction_blue[1] * interpolation_factor))
1003 # Show the new image in the image viewer, and remember its parameters.
1004 self.set_photo_signal.emit(self.version_selected)
1005 self.last_version_selected = self.version_selected
1006
1007 # A new image must be computed for this version. Special case self.version_selected = 0:
1008 # For the original image no layers are applied. But if the RGB automatic checkbox was
1009 # changed, the image must be set according to the new shift status. The shift was
1010 # applied in self.input_image above.
1011 elif compute_new_image and not self.version_selected:
1012 self.postproc_data_object.versions[0].image = self.input_image.astype(uint16)
1013 # Show the new image in the image viewer, and remember its parameters.
1014 self.set_photo_signal.emit(self.version_selected)
1015 self.last_version_selected = self.version_selected
1016
1017 # General case for new image computation: Either it was decided above that a new
1018 # computation is required, or the test "new_computation_required" for changes in the
1019 # correction layers is performed.
1020 elif compute_new_image or self.new_computation_required(
1021 self.version_selected != self.last_version_selected):
1022 # Change the main GUI's status bar to show that a computation is going on.
1023 self.set_status_bar_signal.emit("Postprocessing " + self.file_name +
1024 ", busy computing a new image.", "black")
1025
1026 # Perform the new computation. Try to store intermediate results. If it fails
1027 # because there is not enough RAM, switch to direct computation.
1028 if self.ram_sufficient:
1029 try:
1030 self.postproc_data_object.versions[
1031 self.version_selected].image = self.recompute_selected_version(
1032 self.layers_selected)
1033 except:
1034 self.ram_sufficient = False
1035 self.postproc_data_object.versions[
1036 self.version_selected].image = Miscellaneous.post_process(
1037 self.input_image, self.layers_selected)
1038 else:
1039 self.postproc_data_object.versions[
1040 self.version_selected].image = Miscellaneous.post_process(
1041 self.input_image, self.layers_selected)
1042
1043 # Reset the status bar to its idle state.
1044 self.set_status_bar_signal.emit("Postprocessing " + self.file_name, "black")
1045
1046 # Show the new image in the image viewer, and remember its parameters.
1047 self.set_photo_signal.emit(self.version_selected)
1048 self.last_version_selected = self.version_selected
1049
1050 # Neither the shift nor parameters have changed. If the version selection has changed,
1051 # display the image stored with the version selected.
1052 elif self.version_selected != self.last_version_selected:
1053 # Show the new image in the image viewer, and remember its parameters.
1054 self.set_photo_signal.emit(self.version_selected)
1055 self.last_version_selected = self.version_selected
1056
1057 # Idle loop before doing the next check for updates.
1058 else:
1059 sleep(self.postproc_idle_loop_time)
1060
1061 # Reset any exception condition after a successful loop pass.
1062 exception_status = False
1063
1064 except Exception as e:
1065 # Print the error message only once. The error status is reset after the next
1066 # successful loop pass.
1067 if not exception_status:
1068 print ("Exception in ImageProcessor: " + str(e) + ". Will try again.",
1069 file=stderr)
1070 exception_status = True
1071 sleep(self.postproc_idle_loop_time)
1072
1073 def reset_intermediate_images(self):
1074 """
1075 Initialize all intermediate image versions, so that they will be re-computed next time.
1076
1077 :return: -
1078 """
1079
1080 self.layer_input = [None] * (self.configuration.postproc_max_layers + 1)
1081 self.layer_gauss = [None] * (self.configuration.postproc_max_layers)
1082 self.layer_bilateral = [None] * (self.configuration.postproc_max_layers)
1083 self.layer_denoised = [None] * (self.configuration.postproc_max_layers)
1084
1085 def new_computation_required(self, version_has_changed):
1086 """
1087 Decide if a new computation is required. Invalidate only those intermediate image
1088 components which are affected by the parameter change. This results in a substantial
1089 performance improvement.
1090
1091 :param version_has_changed: True, if the version has changed, so all intermediate results
1092 must be invalidated.
1093 :return: True, if the current version parameters have changed. False, otherwise.
1094 """
1095
1096 # Initialize the flag which remembers if a change was found. Do not return on the first
1097 # detection in order to invalidate all affected intermediate results.
1098 change_detected = False
1099
1100 # If a new version is selected, reset images with intermediate results.
1101 if version_has_changed:
1102 self.reset_intermediate_images()
1103 change_detected = True
1104
1105 # Check if an additional version was created. Copy its layer info for later checks
1106 # for changes. The intermediate results are reset already because the version number must
1107 # have changed.
1108 if self.version_selected >= len(self.last_version_layers):
1109 self.last_version_layers.append(deepcopy(self.postproc_data_object.versions[
1110 self.version_selected].layers))
1111 return change_detected
1112
1113 # If the selected version is already known, check if the number of layers has changed.
1114 if len(self.last_version_layers[self.version_selected]) != len(self.layers_selected):
1115 self.last_version_layers[self.version_selected] = deepcopy(self.layers_selected)
1116 self.reset_intermediate_images()
1117 change_detected = True
1118 return change_detected
1119
1120 # For color images, check if the "luminance only" parameter has changed. In this case all
1121 # layers are invalidated completely. Remember that the "luminance only" parameter is the
1122 # same on all layers for any given version, and that for version 0 (original image) no
1123 # layers are defined (and therefore there is no parameter "luminance_only").
1124 if self.color and self.version_selected and \
1125 self.last_version_layers[self.version_selected][0].luminance_only != \
1126 self.layers_selected[0].luminance_only:
1127 self.reset_intermediate_images()
1128 change_detected = True
1129
1130 # The version is the same as before, it has the same number of layers, and the luminance
1131 # parameter has not changed. Now go through all layers and invalidate those intermediate
1132 # results individually which need to be recomputed.
1133 else:
1134 for layer_index, (last_layer, layer_selected) in enumerate(
1135 zip(self.last_version_layers[self.version_selected], self.layers_selected)):
1136 # The "amount" parameter has changed. No intermediate results need to be invalidated
1137 # because the layer's contribution to the image is computed by multiplying the
1138 # denoised component with the amount parameter.
1139 if last_layer.amount != layer_selected.amount:
1140 last_layer.amount = layer_selected.amount
1141 change_detected = True
1142
1143 # If the radius has changed, all filters at this level and the input for the next
1144 # level have to be recomputed.
1145 if last_layer.radius != layer_selected.radius:
1146 self.layer_gauss[layer_index] = self.layer_bilateral[layer_index] = \
1147 self.layer_denoised[layer_index] = self.layer_input[layer_index + 1] = None
1148 change_detected = True
1149
1150 # If the bi_fraction has changed, the input for the next layer and the denoised
1151 # component on this layer must be recomputed.
1152 if last_layer.bi_fraction != layer_selected.bi_fraction:
1153 self.layer_denoised[layer_index] = self.layer_input[layer_index + 1] = None
1154 change_detected = True
1155
1156 # If the bi_range parameter has changed, the bilateral filter is invalidated.
1157 if last_layer.bi_range != layer_selected.bi_range:
1158 self.layer_bilateral[layer_index] = None
1159 change_detected = True
1160 # If the bi_fraction parameter is not zero, the change propagates to the
1161 # denoised component and the input for the next level.
1162 if abs(layer_selected.bi_fraction) > 1.e-5:
1163 self.layer_denoised[layer_index] = self.layer_input[layer_index + 1] = None
1164
1165 # If the denoise parameter has changed, the denoised component for this layer is
1166 # invalidated.
1167 if last_layer.denoise != layer_selected.denoise:
1168 self.layer_denoised[layer_index] = None
1169 change_detected = True
1170
1171 # Remember the current parameter settings to compare with new parameters next time.
1172 self.last_version_layers[self.version_selected] = deepcopy(self.layers_selected)
1173 return change_detected
1174
1175 def recompute_selected_version(self, layers):
1176 """
1177 Do the actual computation. Starting from the original image, for each sharpening layer
1178 apply a Gaussian filter using the layer's parameters. Store the result in the central
1179 data object for the selected version.
1180
1181 :return: -
1182 """
1183
1184 # Check if the original image is selected (version 0). In this case return the (potentially
1185 # RGB-shifted) original iamge.
1186 if not layers:
1187 return self.input_image.astype(uint16)
1188
1189 for layer_index, layer in enumerate(layers):
1190 if self.layer_input[layer_index] is None:
1191 # For layers > 0, the layer_input must have been computed on the previous layer.
1192 if layer_index:
1193 raise InternalError("Layer input image is None for layer > 0")
1194 # On layer 0, the original image is taken as layer input.
1195 else:
1196 # For color input and luminance_only: extract the luminance channel.
1197 if self.color and layer.luminance_only:
1198 self.layer_input[layer_index] = self.input_image_hsv[:, :, 2]
1199 else:
1200 self.layer_input[layer_index] = self.input_image
1201
1202 # Bilateral filter is needed:
1203 if abs(layer.bi_fraction) > 1.e-5:
1204 # Filter must be recomputed.
1205 if self.layer_bilateral[layer_index] is None:
1206 self.layer_bilateral[layer_index] = bilateralFilter(self.layer_input[layer_index],
1207 0, layer.bi_range * 256., layer.radius/3., borderType=BORDER_DEFAULT)
1208
1209 # Gaussian filter is needed:
1210 if abs(layer.bi_fraction - 1.) > 1.e-5:
1211 # Filter must be recomputed.
1212 if self.layer_gauss[layer_index] is None:
1213 self.layer_gauss[layer_index] = GaussianBlur(self.layer_input[layer_index], (0, 0),
1214 layer.radius/3., borderType=BORDER_DEFAULT)
1215
1216 # Compute the input image for the next layer.
1217 if self.layer_input[layer_index + 1] is None:
1218 # Case bilateral only.
1219 if abs(layer.bi_fraction - 1.) <= 1.e-5:
1220 self.layer_input[layer_index + 1] = self.layer_bilateral[layer_index]
1221 # Case Gaussian only.
1222 elif abs(layer.bi_fraction) <= 1.e-5:
1223 self.layer_input[layer_index + 1] = self.layer_gauss[layer_index]
1224 # Mixed case.
1225 else:
1226 self.layer_input[layer_index + 1] = self.layer_bilateral[layer_index] * layer.bi_fraction + \
1227 self.layer_gauss[layer_index] * (1. - layer.bi_fraction)
1228
1229 # A new denoised layer component must be computed.
1230 if self.layer_denoised[layer_index] is None:
1231 layer_component_before_denoise = self.layer_input[layer_index] - self.layer_input[layer_index + 1]
1232 # Denoising must be applied.
1233 if layer.denoise > 1.e-5:
1234 self.layer_denoised[layer_index] = GaussianBlur(layer_component_before_denoise, (0, 0),
1235 layer.radius / 3., borderType=BORDER_DEFAULT) * layer.denoise + \
1236 layer_component_before_denoise * (1. - layer.denoise)
1237 else:
1238 self.layer_denoised[layer_index] = layer_component_before_denoise
1239
1240 # Build the sharpened image as a weighted sum of the layer components. Start with the
1241 # maximally blurred layer input (start image of first layer beyond active layers).
1242 # A weight > 1 increases details at this level, a weight < 1 lowers their visibility.
1243 new_image = copy(self.layer_input[len(layers)])
1244 for layer, image_layer_component in zip(layers, self.layer_denoised):
1245 new_image += image_layer_component * layer.amount
1246
1247 # In case of "luminance only", insert the new luminance channel into a copy of the original
1248 # image and change back to BGR.
1249 if self.color and layers[0].luminance_only:
1250 new_image_bgr = copy(self.input_image_hsv)
1251 new_image_bgr[:, :, 2] = new_image
1252 new_image = cvtColor(new_image_bgr, COLOR_HSV2BGR)
1253
1254 # Clip pixels out of range and convert the processed image to 16bit unsigned int.
1255 return new_image.clip(min=0., max=65535.).astype(uint16)
1256
1257 def stop(self):
1258 """
1259 Terminate the ImageProcessor.
1260 :return: -
1261 """
1262
1263 self.terminate()
1264
1265
1266 class PostprocEditorWidget(QtWidgets.QFrame, Ui_postproc_editor):
1267 """
1268 This widget implements a frame viewer together with control elements to control the
1269 postprocessing. Several postprocessing versions can be created and managed, each one using
1270 a variable number of sharpening layers. A blink comparator allows comparing any two versions.
1271 """
1272
1273 def __init__(self, configuration, image_original, name_original, set_status_bar_callback,
1274 signal_save_postprocessed_image):
1275 """
1276
1277 :param configuration: Configuration object with parameters.
1278 :param image_original: Original image (16bit) holding the input for postprocessing.
1279 :param name_original: Path name of the original image.
1280 :param set_status_bar_callback: Call-back function to update the main GUI's status bar.
1281 :param signal_save_postprocessed_image: Signal to be issued when the postprocessing
1282 widget closes. None if no signal is to be issued.
1283 """
1284
1285 super(PostprocEditorWidget, self).__init__()
1286 self.setupUi(self)
1287
1288 self.configuration = configuration
1289 self.postproc_data_object = self.configuration.postproc_data_object
1290 self.postproc_data_object.set_postproc_input_image(image_original, name_original,
1291 self.configuration.global_parameters_image_format)
1292 self.signal_save_postprocessed_image = signal_save_postprocessed_image
1293
1294 self.tabWidget_postproc_control.currentChanged.connect(self.tab_changed)
1295
1296 self.buttonBox.accepted.connect(self.accept)
1297 self.buttonBox.rejected.connect(self.reject)
1298 self.pushButton_add_layer.clicked.connect(self.add_layer)
1299
1300 rgb_resolutions = [' 1 Pixel ', ' 0.5 Pixels', ' 0.25 Pixels']
1301 self.max_rgb_index = self.max_auto_rgb_index()
1302 for resolution_index in range(self.max_rgb_index + 1):
1303 self.comboBox_resolution.addItem(rgb_resolutions[resolution_index])
1304
1305 self.fgw_slider_value.valueChanged['int'].connect(self.fgw_changed)
1306 self.comboBox_resolution.currentIndexChanged.connect(self.rgb_resolution_changed)
1307 self.checkBox_automatic.stateChanged.connect(self.rgb_automatic_changed)
1308 self.pushButton_red_reset.clicked.connect(self.prreset_clicked)
1309 self.pushButton_red_up.clicked.connect(self.pru_clicked)
1310 self.pushButton_red_down.clicked.connect(self.prd_clicked)
1311 self.pushButton_red_left.clicked.connect(self.prl_clicked)
1312 self.pushButton_red_right.clicked.connect(self.prr_clicked)
1313 self.pushButton_blue_reset.clicked.connect(self.pbreset_clicked)
1314 self.pushButton_blue_up.clicked.connect(self.pbu_clicked)
1315 self.pushButton_blue_down.clicked.connect(self.pbd_clicked)
1316 self.pushButton_blue_left.clicked.connect(self.pbl_clicked)
1317 self.pushButton_blue_right.clicked.connect(self.pbr_clicked)
1318
1319 # Enable RGB alignment for color input only.
1320 self.tab_rgb.setEnabled(self.postproc_data_object.color)
1321
1322 # Initialize list of sharpening layer widgets, and set the maximal number of layers.
1323 self.sharpening_layer_widgets = []
1324 self.max_layers = self.configuration.postproc_max_layers
1325
1326 self.label_message.setText("Edit postproc versions with up to "
1327 + str(self.max_layers) + " correction layers.")
1328 self.label_message.setStyleSheet('color: red')
1329
1330 # Start the frame viewer.
1331 self.frame_viewer = FrameViewer()
1332 self.frame_viewer.setObjectName("framewiever")
1333 self.gridLayout.addWidget(self.frame_viewer, 0, 0, 2, 2)
1334 self.frame_viewer.zoom_factor_signal.connect(self.display_zoom_factor)
1335
1336 # Initialize a vertical spacer used to fill the lower part of the sharpening widget scroll
1337 # area.
1338 self.spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum,
1339 QtWidgets.QSizePolicy.Expanding)
1340
1341 # Set the resolution index to an impossible value. It is used to check for changes.
1342 self.rgb_resolution_index = -1
1343
1344 # Set the vertical image size (in pixels) to an impossible value. It is used to check for
1345 # changes later. When the pixel resolution of the displayed image changes, the "fit in view"
1346 # method of the image viewer is invoked to normalize the appearance of the image.
1347 self.image_size_y = -1
1348
1349 # Create the version manager.
1350 self.selected_version = None
1351 self.version_manager_widget = VersionManagerWidget(self.configuration)
1352 self.gridLayout.addWidget(self.version_manager_widget, 1, 2, 1, 1)
1353
1354 # The "set_photo_signal" from the VersionManagerWidget is not passed to the image viewer
1355 # directly. (The image viewer does not accept signals.) Instead, it sends a signal to this
1356 # object which in turn invokes the image viewer.
1357 self.version_manager_widget.set_photo_signal.connect(self.select_image)
1358 self.version_manager_widget.select_version_signal.connect(self.select_version)
1359
1360 # Select the initial current version.
1361 self.select_version(self.postproc_data_object.version_selected)
1362
1363 # Start the image processor thread, and connect its signals.
1364 self.image_processor = ImageProcessor(self.configuration)
1365 self.image_processor.setTerminationEnabled(True)
1366 self.image_processor.set_photo_signal.connect(self.select_image)
1367 self.image_processor.set_shift_display_signal.connect(self.display_shifts)
1368 self.image_processor.set_status_bar_signal.connect(set_status_bar_callback)
1369 self.image_processor.disable_widgets_signal.connect(self.disable_widgets)
1370 self.image_processor.enable_widgets_signal.connect(self.enable_widgets)
1371
1372 if self.max_rgb_index == -1:
1373 self.checkBox_automatic.setChecked(False)
1374 self.tab_rgb.setEnabled(False)
1375
1376 for version in self.postproc_data_object.versions:
1377 if self.max_rgb_index == -1:
1378 version.rgb_automatic = False
1379 version.rgb_resolution_index = min(version.rgb_resolution_index, max(self.max_rgb_index, 0))
1380
1381 def max_auto_rgb_index(self):
1382 """
1383 Return the maximal auto RGB alignment index such that the image created is not larger than
1384 10% of the available RAM. This makes sure that the postprocessing does not run out of RAM.
1385
1386 :return: Maximal RGB alignment index (0, 1, or 2). If the image is too large to do any
1387 auto RGB alignment, -1 is returned.
1388 """
1389
1390 level = 2
1391 max_index = 2
1392 factors = [1, 2, 4]
1393
1394 # Look up the available RAM (without paging)
1395 virtual_memory = dict(psutil.virtual_memory()._asdict())
1396 available_ram = virtual_memory['available']
1397
1398 # For monochrome images, nothing is to be done.
1399 if self.postproc_data_object.color:
1400 image = self.postproc_data_object.image_original
1401
1402 # The intermediate image is in float32 (4 bytes) and has 3 color channels.
1403 size_of_image = image.shape[0] * image.shape[1] * 12.
1404
1405 # Compute the maximal interpolation factor.
1406 max_factor = int(sqrt(
1407 available_ram * self.configuration.postproc_max_ram_percentage / 100. / size_of_image))
1408
1409 # In this case auto RGB alignment does not even work for standard size.
1410 if max_factor == 0:
1411 return -1
1412
1413 # Look for the maximal interpolation index.
1414 for level in range(max_index, -1, -1):
1415 if factors[level] <= max_factor:
1416 break
1417
1418 return level
1419
1420 def disable_widgets(self):
1421 """
1422 To avoid race conditions, GUI widgets are disabled while computations are going on. The only
1423 button remaining active is "Cancel".
1424
1425 :return: -
1426 """
1427
1428 self.version_manager_widget.setEnabled(False)
1429 self.tabWidget_postproc_control.setEnabled(False)
1430 self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)
1431
1432 def enable_widgets(self):
1433 """
1434 Enable the GUI buttons when background computations have finished.
1435
1436 :return: -
1437 """
1438
1439 self.version_manager_widget.setEnabled(True)
1440 self.tabWidget_postproc_control.setEnabled(True)
1441 self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True)
1442
1443 def fgw_changed(self, value):
1444 """
1445 When the widget changes its value, update the corresponding entry for the current version.
1446 Please note that for some parameters the representations differ.
1447
1448 The methods following this one do the same for all other configuration parameters.
1449
1450 :param value: New value sent by widget
1451 :return: -
1452 """
1453
1454 gauss_width = 2 * value - 1
1455 self.postproc_data_object.versions[self.postproc_data_object.version_selected].rgb_gauss_width = gauss_width
1456 self.fgw_label_display.setText(str(gauss_width))
1457
1458 def rgb_resolution_changed(self, value):
1459 version = self.postproc_data_object.versions[self.postproc_data_object.version_selected]
1460 version.rgb_resolution_index = value
1461
1462 # Round the shift values according to the new resolution.
1463 factor = [1., 2., 4.][value]
1464 factor_incremented = [1.01, 2.01, 4.01][value]
1465 version.shift_red = (round(version.shift_red[0] * factor_incremented) / factor ,
1466 round(version.shift_red[1] * factor_incremented) / factor)
1467 version.shift_blue = (round(version.shift_blue[0] * factor_incremented) / factor,
1468 round(version.shift_blue[1] * factor_incremented) / factor)
1469 version.correction_red = (round(version.correction_red[0] * factor_incremented) / factor,
1470 round(version.correction_red[1] * factor_incremented) / factor)
1471 version.correction_blue = (round(version.correction_blue[0] * factor_incremented) / factor,
1472 round(version.correction_blue[1] * factor_incremented) / factor)
1473 self.display_shifts()
1474
1475 def tab_changed(self, index):
1476 version = self.postproc_data_object.versions[
1477 self.postproc_data_object.version_selected]
1478 if index and not version.rgb_automatic:
1479 self.rgb_correction_version_init(version)
1480 elif not index:
1481 # Force the computation of a new image in the ImageProcessor.
1482 version.shift_red_saved = None
1483 version.shift_blue_saved = None
1484 self.finish_rgb_correction_mode()
1485
1486 def rgb_automatic_changed(self, state):
1487 rgb_on = state == QtCore.Qt.Checked
1488 version = self.postproc_data_object.versions[
1489 self.postproc_data_object.version_selected]
1490 version.rgb_automatic = rgb_on
1491 if rgb_on:
1492 self.rgb_correction_version_reset(version)
1493 else:
1494 self.rgb_correction_version_init(version)
1495
1496 def rgb_correction_version_init(self, version):
1497 version.rgb_correction_mode = True
1498 version.correction_red_saved = version.correction_blue_saved = version.correction_red = \
1499 version.correction_blue = (0., 0.)
1500 version.images_uncorrected = [None] * 3
1501
1502 def rgb_correction_version_reset(self, version):
1503 version.rgb_correction_mode = False
1504 version.correction_red_saved = version.correction_blue_saved = version.correction_red =\
1505 version.correction_blue = (0., 0.)
1506 version.images_uncorrected = [None] * 3
1507
1508 def finish_rgb_correction_mode(self):
1509 for version_index, version in enumerate(self.postproc_data_object.versions):
1510 if version.correction_red != (0., 0.) or version.correction_blue != (0., 0.):
1511 version.shift_red = (version.shift_red[0] + version.correction_red[0],
1512 version.shift_red[1] + version.correction_red[1])
1513 version.shift_blue = (version.shift_blue[0] + version.correction_blue[0],
1514 version.shift_blue[1] + version.correction_blue[1])
1515 self.rgb_correction_version_reset(version)
1516 self.select_image(self.postproc_data_object.version_selected)
1517
1518 def prreset_clicked(self):
1519 version = self.postproc_data_object.versions[self.postproc_data_object.version_selected]
1520 version.correction_red = (-version.shift_red[0], -version.shift_red[1])
1521 self.display_shifts()
1522
1523 def pru_clicked(self):
1524 version = self.postproc_data_object.versions[self.postproc_data_object.version_selected]
1525 increment = [1., 0.5, 0.25][version.rgb_resolution_index]
1526 version.correction_red = (version.correction_red[0] - increment, version.correction_red[1])
1527 self.display_shifts()
1528
1529 def prd_clicked(self):
1530 version = self.postproc_data_object.versions[self.postproc_data_object.version_selected]
1531 increment = [1., 0.5, 0.25][version.rgb_resolution_index]
1532 version.correction_red = (version.correction_red[0] + increment, version.correction_red[1])
1533 self.display_shifts()
1534
1535 def prl_clicked(self):
1536 version = self.postproc_data_object.versions[self.postproc_data_object.version_selected]
1537 increment = [1., 0.5, 0.25][version.rgb_resolution_index]
1538 version.correction_red = (version.correction_red[0], version.correction_red[1] - increment)
1539 self.display_shifts()
1540
1541 def prr_clicked(self):
1542 version = self.postproc_data_object.versions[self.postproc_data_object.version_selected]
1543 increment = [1., 0.5, 0.25][version.rgb_resolution_index]
1544 version.correction_red = (version.correction_red[0], version.correction_red[1] + increment)
1545 self.display_shifts()
1546
1547 def pbreset_clicked(self):
1548 version = self.postproc_data_object.versions[self.postproc_data_object.version_selected]
1549 version.correction_blue = (-version.shift_blue[0], -version.shift_blue[1])
1550 self.display_shifts()
1551
1552 def pbu_clicked(self):
1553 version = self.postproc_data_object.versions[self.postproc_data_object.version_selected]
1554 increment = [1., 0.5, 0.25][version.rgb_resolution_index]
1555 version.correction_blue = (version.correction_blue[0] - increment, version.correction_blue[1])
1556 self.display_shifts()
1557
1558 def pbd_clicked(self):
1559 version = self.postproc_data_object.versions[self.postproc_data_object.version_selected]
1560 increment = [1., 0.5, 0.25][version.rgb_resolution_index]
1561 version.correction_blue = (
1562 version.correction_blue[0] + increment, version.correction_blue[1])
1563 self.display_shifts()
1564
1565 def pbl_clicked(self):
1566 version = self.postproc_data_object.versions[self.postproc_data_object.version_selected]
1567 increment = [1., 0.5, 0.25][version.rgb_resolution_index]
1568 version.correction_blue = (version.correction_blue[0], version.correction_blue[1] - increment)
1569 self.display_shifts()
1570
1571 def pbr_clicked(self):
1572 version = self.postproc_data_object.versions[self.postproc_data_object.version_selected]
1573 increment = [1., 0.5, 0.25][version.rgb_resolution_index]
1574 version.correction_blue = (
1575 version.correction_blue[0], version.correction_blue[1] + increment)
1576 self.display_shifts()
1577
1578 def display_shifts(self):
1579 """
1580 Set the current channel shifts in the RGB alignment GUI tab.
1581
1582 :return: -
1583 """
1584
1585 format_string = ["{0:2.0f}", "{0:4.1f}", "{0:5.2f}"][self.postproc_data_object.versions[
1586 self.postproc_data_object.version_selected].rgb_resolution_index]
1587
1588 # Red channel shifts:
1589 shift_red_base = self.postproc_data_object.versions[
1590 self.postproc_data_object.version_selected].shift_red
1591 correction_red = self.postproc_data_object.versions[
1592 self.postproc_data_object.version_selected].correction_red
1593 shift_red = (shift_red_base[0] + correction_red[0], shift_red_base[1] + correction_red[1])
1594
1595 if abs(shift_red[0]) < 0.05:
1596 self.label_red_down.setText("")
1597 self.label_red_up.setText("")
1598 elif shift_red[0] > 0:
1599 self.label_red_down.setText((format_string.format(shift_red[0])))
1600 self.label_red_up.setText("")
1601 else:
1602 self.label_red_up.setText((format_string.format(-shift_red[0])))
1603 self.label_red_down.setText("")
1604
1605 if abs(shift_red[1]) < 0.05:
1606 self.label_red_left.setText("")
1607 self.label_red_right.setText("")
1608 elif shift_red[1] > 0:
1609 self.label_red_right.setText((format_string.format(shift_red[1])))
1610 self.label_red_left.setText("")
1611 else:
1612 self.label_red_left.setText((format_string.format(-shift_red[1])))
1613 self.label_red_right.setText("")
1614
1615 # Blue channel shifts:
1616 shift_blue_base = self.postproc_data_object.versions[
1617 self.postproc_data_object.version_selected].shift_blue
1618 correction_blue = self.postproc_data_object.versions[
1619 self.postproc_data_object.version_selected].correction_blue
1620 shift_blue = (shift_blue_base[0] + correction_blue[0], shift_blue_base[1] + correction_blue[1])
1621
1622 if abs(shift_blue[0]) < 0.05:
1623 self.label_blue_down.setText("")
1624 self.label_blue_up.setText("")
1625 elif shift_blue[0] > 0:
1626 self.label_blue_down.setText((format_string.format(shift_blue[0])))
1627 self.label_blue_up.setText("")
1628 else:
1629 self.label_blue_up.setText((format_string.format(-shift_blue[0])))
1630 self.label_blue_down.setText("")
1631
1632 if abs(shift_blue[1]) < 0.05:
1633 self.label_blue_left.setText("")
1634 self.label_blue_right.setText("")
1635 elif shift_blue[1] > 0:
1636 self.label_blue_right.setText((format_string.format(shift_blue[1])))
1637 self.label_blue_left.setText("")
1638 else:
1639 self.label_blue_left.setText((format_string.format(-shift_blue[1])))
1640 self.label_blue_right.setText("")
1641
1642 def display_zoom_factor(self, zoom_factor):
1643 """
1644 Write the current viewer zoom factor under the viewer window.
1645
1646 :param zoom_factor: Current zoom factor, sent by the FrameViewer via a signal.
1647
1648 :return: -
1649 """
1650
1651 self.label_zoom.setText("Zoom: " + str(zoom_factor) + "%")
1652
1653 def select_version(self, version_index):
1654 """
1655 Select a new current version, update the scroll area with all layer widgets, and update the
1656 parameters of the RGB alignment tab.
1657
1658 :param version_index: Index of the version selected in version list of the central data
1659 object.
1660 :return: -
1661 """
1662
1663 # Check if we are leaving a version in correction mode. In this case apply the corrections.
1664 if self.selected_version is not None:
1665 if self.selected_version.rgb_correction_mode:
1666 self.finish_rgb_correction_mode()
1667
1668 self.selected_version = self.postproc_data_object.versions[version_index]
1669
1670 # Remove all existing layer widgets and the lower vertical spacer.
1671 if self.sharpening_layer_widgets:
1672 for layer_widget in self.sharpening_layer_widgets:
1673 self.verticalLayout.removeWidget(layer_widget)
1674 layer_widget.deleteLater()
1675 del layer_widget
1676 self.sharpening_layer_widgets = []
1677 self.verticalLayout.removeItem(self.spacerItem)
1678
1679 # Create new layer widgets for all active layers and put them into the scroll area.
1680 for layer_index, layer in enumerate(self.selected_version.layers):
1681 sharpening_layer_widget = SharpeningLayerWidget(layer_index, self.remove_layer)
1682 sharpening_layer_widget.set_values(layer)
1683 self.verticalLayout.addWidget(sharpening_layer_widget)
1684 self.sharpening_layer_widgets.append(sharpening_layer_widget)
1685
1686 # Connect the signal issued by a sharpening layer when the "luminance only" checkbox changes
1687 # state with all other layers, so they do the same.
1688 for layer_index, sharpening_layer_widget in enumerate(self.sharpening_layer_widgets):
1689 toggle_luminance_signal = sharpening_layer_widget.signal_toggle_luminance_other_layers
1690 for other_layer_index, other_sharpening_layer_widget in enumerate(
1691 self.sharpening_layer_widgets):
1692 if layer_index != other_layer_index:
1693 toggle_luminance_signal.connect(
1694 other_sharpening_layer_widget.checkBox_luminance_toggled_no_signal)
1695
1696 # At the end of the scroll area, add a vertical spacer.
1697 self.verticalLayout.addItem(self.spacerItem)
1698
1699 # Load the parameters of this version into the RGB alignment tab. Block signals to avoid
1700 # triggering change actions which are not required at this point.
1701 self.checkBox_automatic.blockSignals(True)
1702 self.comboBox_resolution.blockSignals(True)
1703 self.checkBox_automatic.setChecked(self.selected_version.rgb_automatic)
1704 self.comboBox_resolution.setCurrentIndex(min(self.selected_version.rgb_resolution_index,
1705 self.max_rgb_index))
1706 self.checkBox_automatic.blockSignals(False)
1707 self.comboBox_resolution.blockSignals(False)
1708 self.fgw_slider_value.setValue(int((self.selected_version.rgb_gauss_width + 1) / 2))
1709 self.fgw_label_display.setText(str(self.selected_version.rgb_gauss_width))
1710
1711 # Only if the RGB tab is selected: Enter / leave RGB correction mode.
1712 if self.tabWidget_postproc_control.currentIndex():
1713 if self.selected_version.rgb_automatic:
1714 self.rgb_correction_version_reset(self.selected_version)
1715 else:
1716 self.rgb_correction_version_init(self.selected_version)
1717
1718 # Load the current image into the image viewer.
1719 self.select_image(version_index)
1720
1721 # Display the current RGB shifts for the selected version.
1722 self.display_shifts()
1723
1724 def select_image(self, version_index):
1725 """
1726 Load the current image into the image viewer. This method is either invoked by a direct
1727 call or by a "set_photo_signal" signal.
1728
1729 :param version_index: Index of the version selected in version list of the central data
1730 object.
1731 :return: -
1732 """
1733
1734 image = self.postproc_data_object.versions[version_index].image
1735 self.frame_viewer.setPhoto(image)
1736
1737 # Check if the image size has changed by more than 10%. If so, reset the zoom factor of the
1738 # FrameViewer.
1739 # print ("Select image")
1740 if abs((image.shape[0] - self.image_size_y)/ image.shape[0]) > 0.1:
1741 # print("Fit in view")
1742 self.frame_viewer.fitInView()
1743 self.image_size_y = image.shape[0]
1744
1745 def add_layer(self):
1746 """
1747 This method is called when the "Add postprocessing layer" button is pressed. Add a layer
1748 to the currently selected postprocessing version.
1749
1750 :return:-
1751 """
1752
1753 version_selected = self.postproc_data_object.versions[
1754 self.postproc_data_object.version_selected]
1755 num_layers_current = version_selected.number_layers
1756
1757 # The "zero" layer is reserved for the original image, so for this version no additional
1758 # layer can be allocated.
1759
1760 # The first layer is initialized with a fixed parameter set (see "init" method of DataObject
1761 # class).
1762 if self.postproc_data_object.version_selected and num_layers_current < self.max_layers:
1763
1764 # This version has already at least one layer. Initialize the radius parameter of the
1765 # new layer to 1.5 times the radius of the previous one.
1766 if num_layers_current:
1767 previous_layer = version_selected.layers[num_layers_current - 1]
1768 new_layer = PostprocLayer(previous_layer.postproc_method,
1769 round(1.5 * previous_layer.radius, 1), 1.,
1770 previous_layer.bi_fraction,
1771 previous_layer.bi_range, 0.,
1772 previous_layer.luminance_only)
1773
1774 # This is the first layer for this image version. Start with standard parameters.
1775 else:
1776 new_layer = PostprocLayer("Multilevel unsharp masking", 1., 1., 0., 20, 0., False)
1777 version_selected.add_postproc_layer(new_layer)
1778
1779 # Update all layer widgets.
1780 self.select_version(self.postproc_data_object.version_selected)
1781
1782 def remove_layer(self, layer_index):
1783 """
1784 Remove a layer from the selected version. The "remove_layer" method of class "Layer" makes
1785 sure that the first layer is not removed.
1786
1787 :param layer_index: Index of the layer to be removed.
1788 :return: -
1789 """
1790
1791 version_selected = self.postproc_data_object.versions[
1792 self.postproc_data_object.version_selected]
1793 version_selected.remove_postproc_layer(layer_index)
1794
1795 # Update all layer widgets.
1796 self.select_version(self.postproc_data_object.version_selected)
1797
1798 def accept(self):
1799 """
1800 When the user presses the "OK" button, save the currently selected version to the standard
1801 path and exit.
1802
1803 :return: -
1804 """
1805
1806 # In case "correction mode" is on, process the current version image in full 16bit
1807 # resolution.
1808 self.disable_widgets()
1809 self.finish_rgb_correction_mode()
1810 self.postproc_data_object.finalize_postproc_version()
1811
1812 # Terminate the image processor thread.
1813 self.image_processor.stop()
1814 self.configuration.write_config()
1815 if self.signal_save_postprocessed_image:
1816 self.signal_save_postprocessed_image.emit(self.postproc_data_object.versions[
1817 self.postproc_data_object.version_selected].image)
1818 # The else branch is only for the test program below which does not provide a signal for
1819 # saving the result. In this case use the save method of the version manager.
1820 else:
1821 self.version_manager_widget.save_version()
1822 self.enable_widgets()
1823 self.close()
1824
1825 def reject(self):
1826 """
1827 When the user presses the "Cancel" button, terminate the image processor thread and
1828 exit without saving anything.
1829
1830 :return: -
1831 """
1832
1833 self.image_processor.stop()
1834 if self.signal_save_postprocessed_image:
1835 self.signal_save_postprocessed_image.emit(None)
1836 self.close()
1837
1838
1839 class EmulateStatusBar(object):
1840 """
1841 This class is only used for unit testing with the main program below. It emulates the status
1842 bar of the main GUI by printing the message to standard output.
1843 """
1844
1845 def __init__(self):
1846 super(EmulateStatusBar, self).__init__()
1847 pass
1848
1849 @staticmethod
1850 def print_status_bar_info(message, color):
1851 """
1852 Emulate the "write_status_bar" method of the main GUI.
1853
1854 :param message: Message to be displayed (str).
1855 :param color: String with the color of the message (e.g. "red").
1856 :return:
1857 """
1858
1859 colors = {}
1860 colors['red'] = "\033[1;31m"
1861 colors['blue'] = "\033[1;34m"
1862 colors['cyan'] = "\033[1;36m"
1863 colors['green'] = "\033[0;32m"
1864 colors['reset'] = "\033[0;0m"
1865 colors['bold'] = "\033[;1m"
1866
1867 # Add a try-except clause to avoid a program crash if an un-supported color is specified.
1868 # In this case, just use a standard print.
1869 try:
1870 stdout.write(colors[color])
1871 print(message)
1872 stdout.write(colors['reset'])
1873 except:
1874 print(message)
1875
1876
1877 if __name__ == '__main__':
1878 # input_file_name = "D:\SW-Development\Python\PlanetarySystemStacker\Examples\Moon_2018-03-24\Moon_Tile-024_043939_pss.tiff"
•1879 # input_file_name = "D:\SW-Development\Python\PlanetarySystemStacker\Examples\Jupiter_Richard\\" \
1880 # "2020-07-29-2145_3-L-Jupiter_ALTAIRGP224C_pss_p70_b48.png"
1881 # input_file_name = "D:\SW-Development\Python\PlanetarySystemStacker\Examples\Jupiter\\2019-05-26-0115_4-L-Jupiter_ZWO ASI290MM Mini_pipp_pss.png"
1882 # input_file_name = "D:\SW-Development\Python\PlanetarySystemStacker\Examples\Moon_2011-04-10\South.stacked.tiff"
•1883 input_file_name = "dummy-not-used"
1884
1885 input_image = imread(input_file_name, -1)
1886 # Change colors to standard RGB
1887 if len(input_image.shape) == 3:
1888 input_image = cvtColor(input_image, COLOR_BGR2RGB)
1889
1890 configuration = Configuration()
1891 configuration.initialize_configuration()
1892 dummy_status_bar = EmulateStatusBar()
1893 app = QtWidgets.QApplication(argv)
1894 window = PostprocEditorWidget(configuration, input_image, input_file_name,
1895 dummy_status_bar.print_status_bar_info, None)
1896 window.show()
1897 app.exec_()