Debian Codegraph @

planetary_system_stacker/workflow.py

raw symbols SCIP
1 # -*- coding: utf-8; -*-
2 """
3 Copyright (c) 2019 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 import gc
24 import platform
25 import sys
26 from os import listdir, rename, remove
27 from os.path import splitext, join, dirname
28
29 import psutil
30 from PyQt5 import QtCore
31 from numpy import uint16, uint8
32
33 from align_frames import AlignFrames
34 from alignment_points import AlignmentPoints
35 from configuration import PostprocDataObject
36 from exceptions import NotSupportedError, InternalError, ArgumentError, Error
37 from frames import Frames, Calibration
38 from miscellaneous import Miscellaneous
39 from rank_frames import RankFrames
40 from stack_frames import StackFrames
41 from timer import timer
42
43 # The following lists define the allowed file extensions for still images.
44 image_extensions = ['.tif', '.tiff', '.fit', '.fits', '.jpg', '.png']
45
46 class Workflow(QtCore.QObject):
47 master_dark_created_signal = QtCore.pyqtSignal(bool)
48 master_flat_created_signal = QtCore.pyqtSignal(bool)
49 work_next_task_signal = QtCore.pyqtSignal(str)
50 report_error_signal = QtCore.pyqtSignal(str)
51 abort_job_signal = QtCore.pyqtSignal(str)
52 work_current_progress_signal = QtCore.pyqtSignal(str, int)
53 set_main_gui_busy_signal = QtCore.pyqtSignal(bool)
54 set_status_bar_signal = QtCore.pyqtSignal(str, str)
55 create_image_window_signal = QtCore.pyqtSignal()
56 update_image_window_signal = QtCore.pyqtSignal(object)
57 terminate_image_window_signal = QtCore.pyqtSignal()
58
59 def __init__(self, main_gui):
60 super(Workflow, self).__init__()
61 self.main_gui = main_gui
62 self.configuration = main_gui.configuration
63
64 self.my_timer = None
65
66 self.frames = None
67 self.rank_frames = None
68 self.align_frames = None
69 self.alignment_points = None
70 self.stack_frames = None
71 self.stacked_image_name = None
72 self.postprocessed_image_name = None
73 self.postprocessed_image = None
74 self.postproc_input_image = None
75 self.postproc_input_name = None
76 self.activity = None
77 self.attached_log_name = None
78 self.attached_log_name_new = None
79 self.attached_log_file = None
80 self.stdout_saved = None
81 self.output_redirected = False
82 self.protocol_file = None
83
84 # Switch alignment point debugging on / off.
85 self.debug_AP = False
86
87 # Print info on the platform used.
88 platform_name = platform.system()
89 processor_name = platform.processor()
90
91 python_dir = dirname(sys.executable)
92 if self.configuration.global_parameters_protocol_level > 1:
93 Miscellaneous.protocol(
94 "Operating system used: " + platform_name + ", Processor used: " + processor_name +
95 "\n Python interpreter location: " +
96 python_dir, self.attached_log_file, precede_with_timestamp=True)
97
98 # Check if the configuration was imported from an older version. If so, print a message.
99 # Please note that the "version imported from" parameter is set only if a configuration
100 # has been read.
101 if self.configuration.global_parameters_protocol_level > 1 and \
102 self.configuration.configuration_read and \
103 self.configuration.global_parameters_version_imported_from != \
104 self.configuration.global_parameters_version:
105 Miscellaneous.protocol(" Configuration imported from older version: " +
106 self.configuration.global_parameters_version_imported_from,
107 self.attached_log_file, precede_with_timestamp=False)
108
109 # Create the calibration object, used for potential flat / dark corrections.
110 self.calibration = Calibration(self.configuration)
111
112 @QtCore.pyqtSlot(list)
113 def execute_create_master_dark(self, dark_names):
114 # Create a new master dark.
115 if self.configuration.global_parameters_protocol_level > 0:
116 Miscellaneous.protocol("+++ Creating a new master dark frame +++",
117 self.attached_log_file, precede_with_timestamp=True)
118 if self.configuration.global_parameters_protocol_level > 1:
119 Miscellaneous.protocol(" Input frames: " + dark_names[0],
120 self.attached_log_file, precede_with_timestamp=False)
121
122 try:
123 self.set_main_gui_busy_signal.emit(True)
124 self.calibration.create_master_dark(dark_names[0])
125 if self.calibration.warn_message is not None and \
126 self.configuration.global_parameters_protocol_level > 0:
127 Miscellaneous.protocol("Warning in creating a new master dark frame: " +
128 self.calibration.warn_message,
129 self.attached_log_file, precede_with_timestamp=True)
130 self.master_dark_created_signal.emit(True)
131 except Exception as e:
132 if self.configuration.global_parameters_protocol_level > 0:
133 self.report_error_signal.emit("Error in creating master dark frame: " + str(e))
134 self.master_dark_created_signal.emit(False)
135
136 @QtCore.pyqtSlot(list)
137 def execute_create_master_flat(self, flat_names):
138
139 # Create a new master flat.
140 if self.configuration.global_parameters_protocol_level > 0:
141 Miscellaneous.protocol("+++ Creating a new master flat frame +++",
142 self.attached_log_file, precede_with_timestamp=True)
143 if self.configuration.global_parameters_protocol_level > 1:
144 Miscellaneous.protocol(" Input frames: " + flat_names[0],
145 self.attached_log_file, precede_with_timestamp=False)
146
147 try:
148 self.set_main_gui_busy_signal.emit(True)
149 self.calibration.create_master_flat(flat_names[0])
150 if self.calibration.warn_message is not None and \
151 self.configuration.global_parameters_protocol_level > 0:
152 Miscellaneous.protocol("Warning in creating a new master flat frame: " +
153 self.calibration.warn_message,
154 self.attached_log_file, precede_with_timestamp=True)
155 self.master_flat_created_signal.emit(True)
156 except Error as e:
157 if self.configuration.global_parameters_protocol_level > 0:
158 self.report_error_signal.emit("Error in creating master flat frame: " +
159 str(e) + ", flat frame calibration de-activated")
160 self.master_flat_created_signal.emit(False)
161
162 @QtCore.pyqtSlot()
163 def execute_reset_masters(self):
164
165 # De-activate master frames.
166 if self.configuration.global_parameters_protocol_level > 0:
167 Miscellaneous.protocol("+++ De-activating master frames +++", self.attached_log_file,
168 precede_with_timestamp=True)
169 self.calibration.reset_masters()
170
171 @QtCore.pyqtSlot(object)
172 def execute_frames(self, job):
173 self.job = job
174
175 # Reset the potential new log file name (required if parameters are to be encoded in file
176 # name).
177 self.attached_log_name_new = None
178
179 # Remove objects from previous job to clean up RAM.
180 for obj in [self.frames, self.rank_frames, self.align_frames, self.alignment_points,
181 self.stack_frames]:
182 if obj is not None:
183 del obj
184 self.frames = None
185 self.rank_frames = None
186 self.align_frames = None
187 self.alignment_points = None
188 self.stack_frames = None
189
190 # Force the garbage collector to release unreferenced objects.
191 gc.collect()
192
193 # Update the status bar in the main GUI.
194 self.input_name = self.job.file_name
195 self.set_status_bar_processing_phase("reading frames")
196
197 # A job can either "stack" images or "postprocess" a single image. In the latter case,
198 # input is a single image file.
199 #
200 # Images for stacking can either be extracted from a video file or a batch of single
201 # photographs. In the first case, input_type is set to 'video', in the second case to
202 # 'image'.
203
204 if self.job.type == 'postproc':
205 self.activity = 'postproc'
206 self.postproc_input_name = self.job.name
207
208 # Reset the postprocessed image to None. This way, in saving the postprocessing result,
209 # it can be checked if an image was computed in the workflow thread.
210 self.postprocessed_image = None
211 self.postprocessed_image_name = PostprocDataObject.set_file_name_processed(
212 self.job.name, self.configuration.postproc_suffix,
213 self.configuration.global_parameters_image_format)
214 self.attached_log_name = splitext(self.job.name)[0] + '_postproc-log.txt'
215
216 # For video file input, the Frames constructor expects the video file name for "names".
217 elif self.job.type == 'video':
218 self.activity = 'stacking'
219 names = self.job.name
220 self.attached_log_name = splitext(self.job.name)[0] + '_stacking-log.txt'
221
222 # For single image input, the Frames constructor expects a list of image file names for
223 # "names".
224 else: # input_type = 'image'
225 self.activity = 'stacking'
226 # Include only names with image extensions.
227 names = [join(self.job.name, name) for name in listdir(self.job.name) if
228 splitext(name)[-1].lower() in image_extensions]
229 self.attached_log_name = self.job.name + '_stacking-log.txt'
230
231 # Redirect stdout to a file if requested.
232 if self.configuration.global_parameters_write_protocol_to_file != self.output_redirected:
233 # Output currently redirected. Reset to stdout.
234 if self.output_redirected:
235 sys.stdout = self.stdout_saved
236 self.output_redirected = False
237 # Currently set to stdout, redirect to file now.
238 else:
239 try:
240 self.stdout_saved = sys.stdout
241 sys.stdout = open(self.configuration.protocol_filename, 'a+')
242 self.output_redirected = True
243 except IOError:
244 pass
245
246 # Create logfile if requested to store the log with the stacked file.
247 if self.attached_log_file:
248 self.attached_log_file.close()
249 if self.configuration.global_parameters_store_protocol_with_result:
250 self.attached_log_file = open(self.attached_log_name, "w+")
251 else:
252 self.attached_log_file = None
253
254 # Write a header to stdout and optionally to the logfile.
255 if self.configuration.global_parameters_protocol_level > 0:
256 decorator_line = (len(self.job.name) + 28) * "*"
257 Miscellaneous.protocol(decorator_line, self.attached_log_file,
258 precede_with_timestamp=False)
259 Miscellaneous.protocol("Start processing " + self.job.name, self.attached_log_file)
260 Miscellaneous.protocol(" Software version used: " +
261 self.configuration.global_parameters_version,
262 self.attached_log_file, precede_with_timestamp=False)
263 Miscellaneous.protocol(decorator_line, self.attached_log_file,
264 precede_with_timestamp=False)
265
266 # Initalize the timer object used to measure execution times of program sections.
267 self.my_timer = timer()
268 self.my_timer.create('Execution over all')
269
270 if self.activity == 'stacking':
271
272 # Write parameters to the protocol.
273 if self.configuration.global_parameters_protocol_level > 1:
274 Miscellaneous.print_stacking_parameters(self.configuration, self.attached_log_file)
275
276 try:
277 if self.configuration.global_parameters_maximum_memory_active:
278 available_ram = float(self.configuration.global_parameters_maximum_memory_amount)
279 else:
280 # Look up the available RAM (without paging)
281 virtual_memory = dict(psutil.virtual_memory()._asdict())
282 available_ram = virtual_memory['available'] / 1e9
283
284 self.frames = Frames(self.configuration, names, type=self.job.type,
285 bayer_option_selected=self.job.bayer_option_selected,
286 calibration=self.calibration,
287 progress_signal=self.work_current_progress_signal)
288
289 # If buffering is not automatic, set the buffering_level as requested by the user.
290 if self.configuration.global_parameters_buffering_level != -1:
291 # Decide on the objects to be buffered, depending on configuration parameter.
292 buffering_level_set = self.configuration.global_parameters_buffering_level
293 # Compute the approximate RAM usage of this job at the selected buffering level.
294 needed_ram = self.frames.compute_required_buffer_size(buffering_level_set)
295 else:
296 needed_ram = None
297
298 # If buffering was set to "auto", compute the highest possible value. If the
299 # buffering level requested explicitly was too high, test if lowering the
300 # buffering level would help.
301 if self.configuration.global_parameters_buffering_level == -1 or needed_ram > available_ram:
302 buffering_level_set = None
303 for level in range(4, -1, -1):
304 alternative_ram = self.frames.compute_required_buffer_size(level)
305 if alternative_ram < available_ram:
306 buffering_level_set = level
307 needed_ram = alternative_ram
308 break
309
310 # Check if the job can be processed with the requested buffering level.
311 message = None
312 if buffering_level_set is None:
313 message = "Error: Too little RAM for this job, continuing with the next one"
314
315 # If an appropriate level other then the one set by the user was found, write it
316 # as a recommendation to the protocol. The job is aborted anyway.
317 elif self.configuration.global_parameters_buffering_level != -1:
318 message = "Error: Too little RAM for chosen buffering level, recommended " \
319 "level: " + str(
320 buffering_level_set) + ", continuing with next job"
321
322 # Buffering is set to "auto" and an appropriate buffering level was found. Set
323 # the buffering in the frames object.
324 else:
325 self.frames.set_buffering(buffering_level_set)
326
327 # The job does not fit in RAM, continue with the next job.
328 if message:
329 self.abort_job_signal.emit(message)
330 return
331
332 # The user has set the buffering level explicitly, and the job fits in memory. Set
333 # the buffering in the frames object.
334 else:
335 self.frames.set_buffering(buffering_level_set)
336
337 if self.configuration.global_parameters_protocol_level > 1:
338 Miscellaneous.protocol("+++ Buffering level is " +
339 str(buffering_level_set) +
340 " +++", self.attached_log_file)
341 Miscellaneous.protocol(
342 " RAM required (Gbytes): " + str(round(needed_ram, 2)) +
343 ", available: " + str(round(available_ram, 2)), self.attached_log_file,
344 precede_with_timestamp=False)
345
346 if self.configuration.global_parameters_protocol_level > 0:
347 Miscellaneous.protocol("+++ Start reading frames +++", self.attached_log_file)
348
349 if self.frames.warn_message is not None and \
350 self.configuration.global_parameters_protocol_level > 0:
351 Miscellaneous.protocol(
352 "Warning in opening SER file: " + self.frames.warn_message,
353 self.attached_log_file, precede_with_timestamp=True)
354 if self.configuration.global_parameters_protocol_level > 1:
355 Miscellaneous.protocol(
356 " Number of frames: " + str(self.frames.number) +
357 ", image shape: " + str(self.frames.shape), self.attached_log_file,
358 precede_with_timestamp=False)
359 if self.job.bayer_option_selected == 'Auto detect color':
360 Miscellaneous.protocol(
361 " Debayer pattern detected automatically: '" +
362 self.frames.bayer_pattern + "'",
363 self.attached_log_file, precede_with_timestamp=False)
364 self.job.bayer_pattern = self.frames.bayer_pattern
365 else:
366 Miscellaneous.protocol(
367 " Debayer pattern selected manually: '" +
368 self.job.bayer_option_selected + "'",
369 self.attached_log_file, precede_with_timestamp=False)
370 if self.frames.dt0 == 'uint16':
371 dynamic_range = '16 bit'
372 elif self.frames.dt0 == 'uint8':
373 dynamic_range = '8 bit'
374 else:
375 dynamic_range = 'undefined'
376 Miscellaneous.protocol(
377 " Dynamic range of input frames: " + dynamic_range + ".",
378 self.attached_log_file, precede_with_timestamp=False)
379 if self.frames.shift_pixels:
380 Miscellaneous.protocol(
381 " Pixel values are multiplied by 2**" + str(
382 self.frames.shift_pixels) + " to use the full dynamic range of 16 "
383 "bits.",
384 self.attached_log_file, precede_with_timestamp=False)
385 if self.frames.calibration_matches:
386 if self.calibration.master_dark_frame_adapted is not None and \
387 self.calibration.inverse_master_flat_frame is not None:
388 Miscellaneous.protocol(
389 " Dark / flat frame calibration is active",
390 self.attached_log_file, precede_with_timestamp=False)
391 elif self.calibration.master_dark_frame_adapted is not None:
392 Miscellaneous.protocol(" Dark frame calibration is active",
393 self.attached_log_file,
394 precede_with_timestamp=False)
395 elif self.calibration.inverse_master_flat_frame is not None:
396 Miscellaneous.protocol(" Flat frame calibration is active",
397 self.attached_log_file,
398 precede_with_timestamp=False)
399 else:
400 Miscellaneous.protocol(
401 " No matching master dark / flat frames found, "
402 "calibration de-activated",
403 self.attached_log_file, precede_with_timestamp=False)
404 except Error as e:
405 self.abort_job_signal.emit("Error: " + e.message + ", continuing with next job")
406 return
407 except Exception as e:
408 self.abort_job_signal.emit(
409 "Error in opening/reading frames: " + str(e) + ", continuing with next job")
410 return
411
412
413
414 # The RAM seems to be sufficient, continue with ranking frames.
415 self.work_next_task_signal.emit("Rank frames")
416
417 # Job type is 'postproc'.
418 else:
419 try:
420 self.postproc_input_image = Frames.read_image(self.postproc_input_name)
421 except Error as e:
422 self.abort_job_signal.emit("Error: " + e.message + ", continuing with next job")
423 return
424 except Exception as e:
425 self.abort_job_signal.emit(
426 "Error in reading image file: " + str(e) + ", continuing with next job")
427 return
428
429 # Convert 8 bit to 16 bit.
430 if self.postproc_input_image.dtype == uint8:
431 self.postproc_input_image = self.postproc_input_image.astype(uint16) * 256
432 self.work_next_task_signal.emit("Postprocessing")
433
434 @QtCore.pyqtSlot()
435 def execute_rank_frames(self):
436
437 # Reset the frame index translation.
438 self.frames.reset_index_translation()
439
440 self.set_status_bar_processing_phase("ranking frames")
441 # Rank the frames by their overall local contrast.
442 if self.configuration.global_parameters_protocol_level > 0:
443 Miscellaneous.protocol("+++ Start ranking frames +++", self.attached_log_file)
444 self.my_timer.create_no_check('Ranking frames')
445
446 try:
447 self.rank_frames = RankFrames(self.frames, self.configuration,
448 self.work_current_progress_signal)
449 self.rank_frames.frame_score()
450 self.my_timer.stop('Ranking frames')
451 except Error as e:
452 self.abort_job_signal.emit("Error: " + e.message + ", continuing with next job")
453 self.my_timer.stop('Ranking frames')
454 return
455 except Exception as e:
456 self.abort_job_signal.emit(
457 "Error: " + str(e) + ", continuing with next job")
458 self.my_timer.stop('Ranking frames')
459 return
460
461 if self.configuration.global_parameters_protocol_level > 1:
462 Miscellaneous.protocol(
463 " Index of best frame: " + str(self.rank_frames.frame_ranks_max_index + 1),
464 self.attached_log_file, precede_with_timestamp=False)
465
466 self.work_next_task_signal.emit("Select frames")
467
468 @QtCore.pyqtSlot()
469 def execute_set_index_translation_table(self):
470 # If in the frame selection dialog the status of at least one frame was changed, update
471 # the index translation table.
472 if not all(self.frames.index_included):
473 self.frames.set_index_translation()
474 self.rank_frames.set_index_translation(self.frames.index_translation)
475 else:
476 self.frames.reset_index_translation()
477 self.rank_frames.reset_index_translation()
478
479 self.work_next_task_signal.emit("Align frames")
480
481 @QtCore.pyqtSlot(int, int, int, int)
482 def execute_align_frames(self, y_low_opt, y_high_opt, x_low_opt, x_high_opt):
483
484 self.set_status_bar_processing_phase("aligning frames")
485 # Initialize the frame alignment object.
486 if self.configuration.global_parameters_protocol_level > 0:
487 Miscellaneous.protocol("+++ Initializing frame alignment +++", self.attached_log_file)
488 self.align_frames = AlignFrames(self.frames, self.rank_frames, self.configuration,
489 progress_signal=self.work_current_progress_signal)
490
491 if self.configuration.align_frames_mode == "Surface":
492
493 auto_execution = False
494 if y_low_opt == 0 and y_high_opt == 0 and x_low_opt == 0 and x_high_opt == 0:
495 auto_execution = True
496 elif (y_high_opt - y_low_opt) / self.frames.shape[
497 0] > self.configuration.align_frames_max_stabilization_patch_fraction or (
498 x_high_opt - x_low_opt) / self.frames.shape[
499 1] > self.configuration.align_frames_max_stabilization_patch_fraction and \
500 self.configuration.global_parameters_protocol_level > 0:
501 Miscellaneous.protocol(" Stabilization patch selected manually is "
502 "too large, switch to automatic mode",
503 self.attached_log_file, precede_with_timestamp=False)
504 auto_execution = True
505 elif (y_high_opt - y_low_opt) / self.frames.shape[
506 0] < self.configuration.align_frames_min_stabilization_patch_fraction or (
507 x_high_opt - x_low_opt) / self.frames.shape[
508 1] < self.configuration.align_frames_min_stabilization_patch_fraction and \
509 self.configuration.global_parameters_protocol_level > 0:
510 Miscellaneous.protocol(" Stabilization patch selected manually is "
511 "too small, switch to automatic mode",
512 self.attached_log_file, precede_with_timestamp=False)
513 auto_execution = True
514
515 # Compute the local rectangular patch in the image where the L gradient is highest
516 # in both x and y direction. The scale factor specifies how much smaller the patch
517 # is compared to the whole image frame. In batch mode, variable "auto_execution" is
518 # set to "True", and the automatic patch computation is the only option.
519 if auto_execution or self.configuration.align_frames_automation:
520
521 self.my_timer.create_no_check('Select optimal alignment patch')
522 try:
523 (y_low_opt, y_high_opt, x_low_opt,
524 x_high_opt) = self.align_frames.compute_alignment_rect(
525 self.configuration.align_frames_rectangle_scale_factor)
526 except (ArgumentError) as e:
527 self.abort_job_signal.emit("Error: " + e.message + ", continuing with next job")
528 self.my_timer.stop('Select optimal alignment patch')
529 return
530 self.my_timer.stop('Select optimal alignment patch')
531 if self.configuration.global_parameters_protocol_level > 1:
532 Miscellaneous.protocol(
533 " Alignment rectangle, computed automatically: " + str(
534 y_low_opt) + "<y<" + str(y_high_opt) + ", " + str(
535 x_low_opt) + "<x<" + str(x_high_opt), self.attached_log_file,
536 precede_with_timestamp=False)
537
538 # As an alternative, set the coordinates of the rectangular patch explicitly.
539 else:
540 # The image displayed in the stabilization patch editor was shrunk on all four
541 # sides by a number of pixels given by the alignment search width parameter.
542 # Therefore, the resulting coordinates of the stabilization patch have to be
543 # corrected by this offset now.
544 y_low_opt += self.configuration.align_frames_search_width
545 y_high_opt += self.configuration.align_frames_search_width
546 x_low_opt += self.configuration.align_frames_search_width
547 x_high_opt += self.configuration.align_frames_search_width
548
549 self.align_frames.set_alignment_rect(y_low_opt, y_high_opt, x_low_opt, x_high_opt)
550 if self.configuration.global_parameters_protocol_level > 1:
551 Miscellaneous.protocol(
552 " Alignment rectangle, set by the user: " + str(
553 y_low_opt) + "<y<" + str(y_high_opt) + ", " + str(
554 x_low_opt) + "<x<" + str(x_high_opt), self.attached_log_file,
555 precede_with_timestamp=False)
556
557 # Align all frames globally relative to the frame with the highest score.
558 if self.configuration.global_parameters_protocol_level > 0:
559 Miscellaneous.protocol("+++ Start aligning all frames +++", self.attached_log_file)
560
561 self.my_timer.create_no_check('Global frame alignment')
562
563 # Align all frames in "Surface" mode.
564 if self.configuration.align_frames_mode == "Surface":
565 # Try the frame alignment using the alignment patch with the highest quality first. If
566 # for at least one frame no valid shift can be found, try the next alignment patch. If
567 # valid shifts cannot be computed with any patch, abort processing of this job and go to
568 # the next one.
569 number_patches = len(self.align_frames.alignment_rect_qualities)
570 for patch_index in range(number_patches):
571 self.align_frames.select_alignment_rect(patch_index)
572 try:
573 self.align_frames.align_frames()
574 # Everything is fine, no need to try another stabilization patch.
575 break
576 except (NotSupportedError, ArgumentError) as e:
577 self.abort_job_signal.emit("Error: " + e.message + ", continuing with next job")
578 self.my_timer.stop('Global frame alignment')
579 return
580 # For some frames no valid shift could be computed. This would create problems later
581 # in the workflow. Therefore, try again with another stabilization patch.
582 except InternalError as e:
583 if self.configuration.global_parameters_protocol_level > 0:
584 Miscellaneous.protocol("Warning: No valid shift computed at " + e.message +
585 ", will try another stabilization patch",
586 self.attached_log_file)
587 # If there is no more patch available, skip this job.
588 if patch_index == number_patches - 1:
589 if self.configuration.align_frames_search_width < self.configuration.align_frames_max_search_width:
590 self.abort_job_signal.emit(
591 "Error: Frame stabilization failed at " + e.message +
592 ", continuing with next job. "
593 "Try a higher value for parameter 'stabilization search width'.")
594 else:
595 self.abort_job_signal.emit(
596 "Error: Frame stabilization failed at " + e.message +
597 ", continuing with next job. "
598 "Try stabilizing the frames with another program, e.g. PIPP.")
599 self.my_timer.stop('Global frame alignment')
600 return
601 # Continue with the next best stabilization patch.
602 else:
603 y_low_opt, y_high_opt, x_low_opt, x_high_opt = \
604 self.align_frames.alignment_rect_bounds[patch_index + 1]
605 if self.configuration.global_parameters_protocol_level > 0:
606 Miscellaneous.protocol(
607 " Next alignment rectangle tried: " + str(
608 y_low_opt) + "<y<" + str(y_high_opt) + ", " + str(
609 x_low_opt) + "<x<" + str(x_high_opt), self.attached_log_file,
610 precede_with_timestamp=False)
611
612 # Catch all other exceptions. In this case abort the job and try the next one.
613 except Exception as e:
614 self.abort_job_signal.emit("Error: " + str(e) + ", continuing with next job")
615 self.my_timer.stop('Global frame alignment')
616 return
617
618 # Align all frames in "Planet" mode.
619 else:
620 try:
621 self.align_frames.align_frames()
622 except Error as e:
623 self.abort_job_signal.emit("Error: " + e.message + ", continuing with next job")
624 self.my_timer.stop('Global frame alignment')
625 return
626 except Exception as e:
627 self.abort_job_signal.emit(
628 "Error in aligning frames: " + str(e) + ", continuing with next job")
629 self.my_timer.stop('Global frame alignment')
630 return
631
632 self.my_timer.stop('Global frame alignment')
633
634 if self.configuration.global_parameters_protocol_level > 1:
635 Miscellaneous.protocol(" Pixel range common to all frames: " + str(
636 self.align_frames.intersection_shape[0][0]) + "<y<" + str(
637 self.align_frames.intersection_shape[0][1]) + ", " + str(
638 self.align_frames.intersection_shape[1][0]) + "<x<" + str(
639 self.align_frames.intersection_shape[1][1]), self.attached_log_file,
640 precede_with_timestamp=False)
641
642 # Compute and print the maximum shift between two consecutive frames:
643 max_shift_y = max([abs(
644 self.align_frames.frame_shifts[idx][0] - self.align_frames.frame_shifts[idx - 1][0])
645 for idx in range(1, self.frames.number)])
646 max_shift_x = max([abs(
647 self.align_frames.frame_shifts[idx][1] - self.align_frames.frame_shifts[idx - 1][1])
648 for idx in range(1, self.frames.number)])
649 Miscellaneous.protocol(
650 " Maximal pixel shift between consecutive frames, vertical: " + str(
651 max_shift_y) + ", horizontal: " + str(max_shift_x), self.attached_log_file,
652 precede_with_timestamp=False)
653
654 # Compute the average frame.
655 if self.configuration.global_parameters_protocol_level > 0:
656 Miscellaneous.protocol("+++ Start computing the reference frame +++",
657 self.attached_log_file)
658 self.my_timer.create_no_check('Compute reference frame')
659 self.align_frames.average_frame()
660 self.my_timer.stop('Compute reference frame')
661 if self.configuration.global_parameters_protocol_level > 1:
662 if self.configuration.align_frames_fast_changing_object:
663 Miscellaneous.protocol(
664 " The reference frame was computed using the best " + str(
665 self.align_frames.average_frame_number) + " frames within a window of " +
666 str(self.align_frames.average_frame_number *
667 self.configuration.align_frames_best_frames_window_extension) +
668 " frames.\n Quality loss of reference frame due to time restriction: " +
669 str(self.align_frames.quality_loss_percent) +
670 "%\n Position of reference frame in video time line: " +
671 str(self.align_frames.cog_mean_frame) + "%",
672 self.attached_log_file, precede_with_timestamp=False)
673 else:
674 Miscellaneous.protocol(
675 " The reference frame was computed using the best " + str(
676 self.align_frames.average_frame_number) + " frames.",
677 self.attached_log_file, precede_with_timestamp=False)
678
679 self.work_next_task_signal.emit("Select stack size")
680
681 @QtCore.pyqtSlot(int, int, int, int)
682 def execute_set_roi(self, y_min, y_max, x_min, x_max):
683
684 self.set_status_bar_processing_phase("setting the ROI")
685 if self.configuration.global_parameters_protocol_level > 0 and (y_min != 0 or y_max != 0):
686 Miscellaneous.protocol("+++ Start setting a ROI and computing a new reference frame +++",
687 self.attached_log_file)
688 self.my_timer.create_no_check('Setting ROI and new reference')
689 self.align_frames.set_roi(y_min, y_max, x_min, x_max)
690 self.my_timer.stop('Setting ROI and new reference')
691
692 if self.configuration.global_parameters_protocol_level > 1 and (y_min != 0 or y_max != 0):
693 Miscellaneous.protocol(
694 " ROI, set by the user: " + str(y_min) + "<y<" + str(y_max) + ", " + str(
695 x_min) + "<x<" + str(x_max), self.attached_log_file,
696 precede_with_timestamp=False)
697
698 self.work_next_task_signal.emit("Set alignment points")
699
700 @QtCore.pyqtSlot()
701 def execute_set_alignment_points(self):
702
703 # If not executing in "automatic" mode, the APs are created on the main_gui thread.
704 if self.main_gui.automatic:
705 self.set_status_bar_processing_phase("creating alignment points")
706 # Initialize the AlignmentPoints object.
707 self.my_timer.create_no_check('Initialize alignment point object')
708 self.alignment_points = AlignmentPoints(self.configuration, self.frames,
709 self.rank_frames, self.align_frames,
710 progress_signal=self.work_current_progress_signal)
711 self.my_timer.stop('Initialize alignment point object')
712
713 # Create alignment points, and create an image with wll alignment point boxes and
714 # patches.
715 if self.configuration.global_parameters_protocol_level > 0:
716 Miscellaneous.protocol("+++ Start creating alignment points +++",
717 self.attached_log_file)
718 self.my_timer.create_no_check('Create alignment points')
719
720 # If a ROI is selected, alignment points are created in the ROI window only.
721 self.alignment_points.create_ap_grid()
722
723 self.my_timer.stop('Create alignment points')
724
725 self.work_next_task_signal.emit("Compute frame qualities")
726
727 @QtCore.pyqtSlot()
728 def execute_compute_frame_qualities(self):
729
730 if self.configuration.global_parameters_protocol_level > 1:
731 Miscellaneous.protocol(" Number of alignment points selected: " + str(len(
732 self.alignment_points.alignment_points)) + ", aps dropped because too dim: " + str(
733 self.alignment_points.alignment_points_dropped_dim) + ", aps dropped because too "
734 "little structure: " + str(
735 self.alignment_points.alignment_points_dropped_structure), self.attached_log_file,
736 precede_with_timestamp=False)
737
738 self.set_status_bar_processing_phase("ranking all frames at all alignment points")
739 # For each alignment point rank frames by their quality.
740 self.my_timer.create_no_check('Rank frames at alignment points')
741 if self.configuration.global_parameters_protocol_level > 0:
742 Miscellaneous.protocol("+++ Start ranking all frames at all alignment points +++",
743 self.attached_log_file)
744 self.alignment_points.compute_frame_qualities()
745 self.my_timer.stop('Rank frames at alignment points')
746
747 self.work_next_task_signal.emit("Stack frames")
748
749 @QtCore.pyqtSlot()
750 def execute_stack_frames(self):
751
752 self.set_status_bar_processing_phase("stacking frames")
753 # Allocate StackFrames object.
754 self.stack_frames = StackFrames(self.configuration, self.frames, self.rank_frames,
755 self.align_frames, self.alignment_points, self.my_timer,
756 progress_signal=self.work_current_progress_signal,
757 debug=self.debug_AP,
758 create_image_window_signal=self.create_image_window_signal,
759 update_image_window_signal=self.update_image_window_signal,
760 terminate_image_window_signal=self.terminate_image_window_signal)
761
762 # Stack all frames.
763 if self.configuration.global_parameters_protocol_level > 0:
764 Miscellaneous.protocol(
765 "+++ Start stacking " + str(self.alignment_points.stack_size) + " frames +++",
766 self.attached_log_file)
767 try:
768 self.stack_frames.stack_frames()
769 except Error as e:
770 self.abort_job_signal.emit("Error: " + e.message + ", continuing with next job")
771 return
772 except Exception as e:
773 self.abort_job_signal.emit(
774 "Error in stacking frames: " + str(e) + ", continuing with next job")
775 return
776
777 if self.configuration.global_parameters_protocol_level > 1 and len(
778 self.alignment_points.alignment_points) > 0:
779 Miscellaneous.protocol("\n Distribution of shifts at alignment points:",
780 self.attached_log_file, precede_with_timestamp=False)
781 Miscellaneous.protocol(self.stack_frames.print_shift_table() + "\n",
782 self.attached_log_file, precede_with_timestamp=False)
783
784 self.set_status_bar_processing_phase("merging AP patches")
785 # Merge the stacked alignment point buffers into a single image.
786 if self.configuration.global_parameters_protocol_level > 0:
787 Miscellaneous.protocol("+++ Start merging all alignment patches and the background +++",
788 self.attached_log_file)
789
790 try:
791 self.stack_frames.merge_alignment_point_buffers()
792 except Error as e:
793 self.abort_job_signal.emit("Error: " + e.message + ", continuing with next job")
794 return
795 except Exception as e:
796 self.abort_job_signal.emit(
797 "Error in merging AP patches: " + str(e) + ", continuing with next job")
798 return
799
800 if self.stack_frames.border_y_low or self.stack_frames.border_y_high or self.stack_frames.border_x_low or self.stack_frames.border_x_high:
801 if self.configuration.global_parameters_protocol_level > 1:
802 Miscellaneous.protocol(
803 " Stacked image borders cropped to avoid artifacts; top: " + str(
804 self.stack_frames.border_y_low) + ", bottom: " + str(
805 self.stack_frames.border_y_high) + ", left: " + str(
806 self.stack_frames.border_x_low) + ", right: " + str(
807 self.stack_frames.border_x_high) + "\n",
808 self.attached_log_file, precede_with_timestamp=False)
809
810 # If the drizzle factor is 1.5, reduce the pixel resolution of the stacked image buffer
811 # to half the size used in stacking.
812 if self.configuration.drizzle_factor_is_1_5:
813 self.stack_frames.half_stacked_image_buffer_resolution()
814
815 self.work_next_task_signal.emit("Save stacked image")
816
817 @QtCore.pyqtSlot()
818 def execute_save_stacked_image(self):
819
820 self.set_status_bar_processing_phase("saving result")
821
822 # Create suffix containing parameter info.
823 parameter_suffix = self.compose_suffix()
824 if self.job.type == 'video':
825 self.stacked_image_name = splitext(self.job.name)[0] + \
826 self.configuration.stack_frames_suffix + \
827 parameter_suffix + '.' + \
828 self.configuration.global_parameters_image_format
829 else: # self.job.type == 'image'
830 self.stacked_image_name = self.job.name + self.configuration.stack_frames_suffix + \
831 parameter_suffix + '.' + \
832 self.configuration.global_parameters_image_format
833
834 # Save the image as 16bit int (color or mono).
835 if self.configuration.global_parameters_protocol_level > 0:
836 Miscellaneous.protocol("+++ Start saving the stacked image +++", self.attached_log_file)
837 self.my_timer.create_no_check('Saving the stacked image')
838 Frames.save_image(self.stacked_image_name, self.stack_frames.stacked_image,
839 color=self.frames.color, avoid_overwriting=False,
840 header=self.configuration.global_parameters_version)
841 self.my_timer.stop('Saving the stacked image')
842 if self.configuration.global_parameters_protocol_level > 1:
843 Miscellaneous.protocol(
844 " The stacked image was written to: " + self.stacked_image_name,
845 self.attached_log_file, precede_with_timestamp=False)
846
847 # If parameter info is to be included in output file names, compose the new name for
848 # the attached log file. The existing file will be renamed after closing.
849 if self.attached_log_file:
850 self.attached_log_name_new = self.attached_log_name[:self.attached_log_name.index(
851 '_stacking-log')] + '_stacking-log' + parameter_suffix + '.txt'
852
853 # If postprocessing is included after stacking, set the stacked image as input.
854 if self.configuration.global_parameters_include_postprocessing:
855 self.postproc_input_image = self.stack_frames.stacked_image
856 self.postproc_input_name = self.stacked_image_name
857 self.postprocessed_image_name = PostprocDataObject.set_file_name_processed(
858 self.stacked_image_name, self.configuration.postproc_suffix,
859 self.configuration.global_parameters_image_format)
860 self.work_next_task_signal.emit("Postprocessing")
861 else:
862 self.work_next_task_signal.emit("Next job")
863
864 # Print timing info for this job.
865 self.my_timer.stop('Execution over all')
866 if self.configuration.global_parameters_protocol_level > 0:
867 self.my_timer.protocol(self.attached_log_file)
868 if self.attached_log_file:
869 self.attached_log_file.close()
870 if self.attached_log_name_new and self.attached_log_name_new != self.attached_log_name:
871 # If a logfile with the new name exists, remove it.
872 try:
873 remove(self.attached_log_name_new)
874 except:
875 pass
876 rename(self.attached_log_name, self.attached_log_name_new)
877 self.attached_log_name = self.attached_log_name_new
878
879 def compose_suffix(self):
880 """
881 If process parameters are to be included in the stacked output file name, compose the
882 suffix from the parameters computed during the workflow.
883
884 :return: Additional suffix string
885 """
886 string = ''
887 if self.configuration.global_parameters_parameters_in_filename:
888 if self.configuration.global_parameters_stack_number_frames:
889 string += '_f' + str(self.alignment_points.stack_size)
890 if self.configuration.global_parameters_stack_percent_frames:
891 string += '_p' + str(int(round(100*self.alignment_points.stack_size/self.frames.number)))
892 if self.configuration.global_parameters_ap_box_size:
893 string += '_b' + str(self.configuration.alignment_points_half_box_width*2)
894 if self.configuration.global_parameters_ap_number:
895 string += '_ap' + str(len(self.alignment_points.alignment_points))
896
897 return string
898
899
900 @QtCore.pyqtSlot()
901 def execute_postprocess_image(self):
902
903 if self.configuration.global_parameters_protocol_level > 0:
904 Miscellaneous.protocol("+++ Start postprocessing +++", self.attached_log_file)
905 self.my_timer.create_no_check('Conputing image postprocessing')
906
907 # Look up parameters of the last postproc version which was selected in interactive mode.
908 version_index = self.configuration.postproc_data_object.version_selected
909 postproc_layers = self.configuration.postproc_data_object.versions[version_index].layers
910 rgb_automatic = self.configuration.postproc_data_object.versions[
911 version_index].rgb_automatic
912 rgb_gauss_width = self.configuration.postproc_data_object.versions[
913 version_index].rgb_gauss_width
914 rgb_resolution_index = self.configuration.postproc_data_object.versions[
915 version_index].rgb_resolution_index
916 shift_red = self.configuration.postproc_data_object.versions[version_index].shift_red
917 shift_blue = self.configuration.postproc_data_object.versions[version_index].shift_blue
918
919 try:
920 # Auto-align RGB channels, if requested.
921 if rgb_automatic:
922 sharpening_input, self.configuration.postproc_data_object.versions[
923 version_index].shift_red, self.configuration.postproc_data_object.versions[
924 version_index].shift_blue = Miscellaneous.auto_rgb_align(
925 self.postproc_input_image, self.configuration.postproc_max_shift,
926 interpolation_factor=[1, 2, 4][rgb_resolution_index], reduce_output=True,
927 blur_strength=rgb_gauss_width)
928 elif shift_red != (0., 0.) or shift_blue != (0., 0.):
929 # Shift the image with the resolution given by the selected interpolation factor.
930 interpolation_factor = [1, 2, 4][rgb_resolution_index]
931 sharpening_input = Miscellaneous.shift_colors(self.postproc_input_image,
932 shift_red, shift_blue,
933 interpolate_input=interpolation_factor,
934 reduce_output=interpolation_factor)
935 else:
936 sharpening_input = self.postproc_input_image
937
938 # Apply all sharpening layers of the postprocessing version selected last time.
939 self.postprocessed_image = Miscellaneous.post_process(sharpening_input, postproc_layers)
940
941 except Exception as e:
942 self.abort_job_signal.emit(
943 "Error in postprocessing: " + str(e) + ", continuing with next job")
944 return
945
946 self.my_timer.stop('Conputing image postprocessing')
947
948 self.work_next_task_signal.emit("Save postprocessed image")
949
950 @QtCore.pyqtSlot(object)
951 def execute_save_postprocessed_image(self, postprocessed_image):
952
953 # The signal payload is None only if the editor was left with "cancel" in interactive mode.
954 # In this case, skip saving the result and proceed with the next job.
955 if postprocessed_image is not None:
956
957 # Print postprocessing info if sharpening layers have been applied or RGB alignment was
958 # active.
959 if self.configuration.global_parameters_protocol_level > 1:
960 version_selected = self.configuration.postproc_data_object.version_selected
961 postproc_version = self.configuration.postproc_data_object.versions[
962 self.configuration.postproc_data_object.version_selected]
963 if version_selected or postproc_version.rgb_automatic:
964 Miscellaneous.print_postproc_parameters(postproc_version,
965 self.attached_log_file)
966 else:
967 Miscellaneous.protocol(
968 " The image was not modified in postprocessing.",
969 self.attached_log_file, precede_with_timestamp=False)
970
971 self.set_status_bar_processing_phase("saving result")
972 # Save the image as 16bit int (color or mono).
973 if self.configuration.global_parameters_protocol_level > 0:
974 Miscellaneous.protocol("+++ Start saving the postprocessed image +++",
975 self.attached_log_file)
976 self.my_timer.create_no_check('Saving the postprocessed image')
977 Frames.save_image(self.postprocessed_image_name, postprocessed_image,
978 color=(len(postprocessed_image.shape) == 3), avoid_overwriting=False,
979 header=self.configuration.global_parameters_version)
980 self.my_timer.stop('Saving the postprocessed image')
981 if self.configuration.global_parameters_protocol_level > 1:
982 Miscellaneous.protocol(
983 " The postprocessed image was written to: " +
984 self.postprocessed_image_name,
985 self.attached_log_file, precede_with_timestamp=False)
986
987 self.work_next_task_signal.emit("Next job")
988
989 # Print timing info for this job.
990 self.my_timer.stop('Execution over all')
991 if self.configuration.global_parameters_protocol_level > 0:
992 self.my_timer.protocol(self.attached_log_file)
993 if self.attached_log_file:
994 self.attached_log_file.close()
995 # If the attached log name was defined for a stacking job, rename it to include
996 # parameter information.
997 if self.attached_log_name_new and self.attached_log_name_new != self.attached_log_name:
998 try:
999 remove(self.attached_log_name_new)
1000 except:
1001 pass
1002 rename(self.attached_log_name, self.attached_log_name_new)
1003 self.attached_log_name = self.attached_log_name_new
1004
1005 def set_status_bar_processing_phase(self, phase):
1006 """
1007 Put a text of the form
1008 "Processing < job name >, < processing step >."
1009 on the main window status bar.
1010
1011 :param phase: Processing phase (string)
1012 :return: -
1013 """
1014
1015 self.set_status_bar_signal.emit("Processing " + self.input_name + ", " + phase + ".",
1016 "black")