Debian Codegraph @

planetary_system_stacker/frame_selector.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 Part of this module (in class "AlignmentPointEditor" was copied from
22 https://stackoverflow.com/questions/35508711/how-to-enable-pan-and-zoom-in-a-qgraphicsview
23
24 """
25 # The following PyQt5 imports must precede any matplotlib imports. This is a workaround
26 # for a Matplotlib 2.2.2 bug.
27
28 from glob import glob
29 from sys import argv, exit
30 from time import sleep
31
32 from PyQt5 import QtCore, QtGui, QtWidgets
33 from PyQt5.QtCore import Qt
34
35 from configuration import Configuration
36 from exceptions import Error
37 from frame_selector_gui import Ui_frame_selector
38 from frame_viewer import FrameViewer
39 from frames import Frames
40 from miscellaneous import Miscellaneous
41 from rank_frames import RankFrames
42
43
44 class VideoFrameSelector(FrameViewer):
45 """
46 This widget implements a frame viewer for frames in a video file. Panning and zooming is
47 implemented by using the mouse and scroll wheel.
48
49 """
50
51 def __init__(self, frames, index_included, frame_index=0):
52 super(VideoFrameSelector, self).__init__()
53 self.frames = frames
54 self.index_included = index_included
55 self.frame_index = frame_index
56
57 self.setPhoto(self.frame_index)
58
59 def setPhoto(self, index):
60 """
61 Convert a grayscale image to a pixmap and assign it to the photo object. If the image is
62 marked as excluded from the stacking workflow, place a crossed-out red circle in the
63 upper left image corner.
64
65 :param index: Index into the frame list. Frames are assumed to be grayscale image in format
66 float32.
67 :return: -
68 """
69
70 # Indicate that an image is being loaded.
71 self.image_loading_busy = True
72
73 image = self.frames.frames_mono(index)
74
75 super(VideoFrameSelector, self).setPhoto(image,
76 overlay_exclude_mark=not self.index_included[index])
77
78
79 class FrameSelectorWidget(QtWidgets.QFrame, Ui_frame_selector):
80 """
81 This widget implements a frame viewer together with control elements to visualize frame
82 qualities, and to manipulate the stack limits.
83 """
84
85 frame_player_start_signal = QtCore.pyqtSignal()
86
87 def __init__(self, parent_gui, configuration, frames, rank_frames, stacked_image_log_file,
88 signal_finished):
89 """
90 Initialization of the widget.
91
92 :param parent_gui: Parent GUI object
93 :param configuration: Configuration object with parameters
94 :param frames: Frames object with all video frames
95 :param rank_frames: RankFrames object with global quality ranks (between 0. and 1.,
96 1. being optimal) for all frames
97 :param stacked_image_log_file: Log file to be stored with results, or None.
98 :param signal_finished: Qt signal to trigger the next activity when the viewer exits.
99 """
100
101 super(FrameSelectorWidget, self).__init__(parent_gui)
102 self.setupUi(self)
103
104 # Keep references to upper level objects.
105 self.parent_gui = parent_gui
106 self.configuration = configuration
107 self.stacked_image_log_file = stacked_image_log_file
108 self.signal_finished = signal_finished
109 self.frames = frames
110 self.index_included = frames.index_included.copy()
111 self.quality_sorted_indices = rank_frames.quality_sorted_indices
112 self.rank_indices = rank_frames.rank_indices
113
114 # Start with ordering frames by quality. This can be changed by the user using a radio
115 # button.
116 self.frame_ordering = "quality"
117
118 # Initialize the frame list selection.
119 self.items_selected = None
120 self.indices_selected = None
121
122 # Set colors for the frame list.
123 self.background_included = QtGui.QColor(130, 255, 130)
124 self.foreground_included = QtGui.QColor(0, 0, 0)
125 self.background_excluded = QtGui.QColor(120, 120, 120)
126 self.foreground_excluded = QtGui.QColor(255, 255, 255)
127
128 self.addButton.clicked.connect(self.use_triggered)
129 self.removeButton.clicked.connect(self.not_use_triggered)
130
131 # Be careful: Indices are counted from 0, while widget contents are counted from 1 (to make
132 # it easier for the user.
133 self.quality_index = 0
134 self.frame_index = self.quality_sorted_indices[self.quality_index]
135
136 # Set up the frame selector and put it in the upper left corner.
137 self.frame_selector = VideoFrameSelector(self.frames, self.index_included, self.frame_index)
138 self.frame_selector.setObjectName("frame_selector")
139 self.gridLayout.addWidget(self.frame_selector, 0, 0, 2, 3)
140
141 # Initialize the list widget.
142 self.fill_list_widget()
143 self.listWidget.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
144 self.listWidget.installEventFilter(self)
145 self.listWidget.itemClicked.connect(self.select_items)
146 self.listWidget.currentRowChanged.connect(self.synchronize_slider)
147
148 # Group widget elements which are to be blocked during player execution in a list.
149 self.widget_elements = [self.listWidget,
150 self.slider_frames,
151 self.addButton,
152 self.removeButton,
153 self.pushButton_play,
154 self.GroupBox_frame_sorting]
155
156 # Initialize a variable for communication with the frame_player object later.
157 self.run_player = False
158
159 # Create the frame player thread and start it. The player displays frames in succession.
160 # It is pushed on a different thread because otherwise the user could not stop it before it
161 # finishes.
162 self.player_thread = QtCore.QThread()
163 self.frame_player = FramePlayer(self)
164 self.frame_player.moveToThread(self.player_thread)
165 self.frame_player.block_widgets_signal.connect(self.block_widgets)
166 self.frame_player.unblock_widgets_signal.connect(self.unblock_widgets)
167 self.frame_player.set_photo_signal.connect(self.frame_selector.setPhoto)
168 self.frame_player.set_slider_value.connect(self.slider_frames.setValue)
169 self.frame_player_start_signal.connect(self.frame_player.play)
170 self.player_thread.start()
171
172 # Initialization of GUI elements
173 self.slider_frames.setMinimum(1)
174 self.slider_frames.setMaximum(self.frames.number)
175 self.slider_frames.setValue(self.quality_index + 1)
176 self.radioButton_quality.setChecked(True)
177
178 self.gridLayout.setColumnStretch(0, 7)
179 self.gridLayout.setColumnStretch(1, 0)
180 self.gridLayout.setColumnStretch(2, 0)
181 self.gridLayout.setColumnStretch(3, 0)
182 self.gridLayout.setColumnStretch(4, 1)
183 self.gridLayout.setRowStretch(0, 0)
184 self.gridLayout.setRowStretch(1, 0)
185
186 # Connect signals with slots.
187 self.buttonBox.accepted.connect(self.done)
188 self.buttonBox.rejected.connect(self.reject)
189 self.slider_frames.valueChanged.connect(self.slider_frames_changed)
190 self.pushButton_play.clicked.connect(self.pushbutton_play_clicked)
191 self.pushButton_stop.clicked.connect(self.pushbutton_stop_clicked)
192 self.radioButton_quality.toggled.connect(self.radiobutton_quality_changed)
193
194 if self.configuration.global_parameters_protocol_level > 0:
195 Miscellaneous.protocol("+++ Start selecting frames +++", self.stacked_image_log_file)
196
197 def block_widgets(self):
198 """
199 Disable GUI elements to prevent unwanted user interaction while the frame player is running.
200
201 :return: -
202 """
203
204 # De-select all items in the listWidget when the player starts.
205 self.listWidget.clearSelection()
206
207 for element in self.widget_elements:
208 element.setDisabled(True)
209
210 def unblock_widgets(self):
211 """
212 Enable GUI elements which were temporarily blocked when the player stops.
213
214 :return: -
215 """
216
217 for element in self.widget_elements:
218 element.setDisabled(False)
219
220 self.listWidget.setFocus()
221
222 def fill_list_widget(self):
223 """
224 Initialize the list widget with frames, ordered as selected (by rank or chronological).
225 Set the colors of each item according to its current inclusion / exclusion state.
226
227 :return: -
228 """
229
230 # Initialize the inclusion / exclusion state of frames in the frame list.
231 self.listWidget.clear()
232 for i in range(self.frames.number_original):
233 if self.frame_ordering == "quality":
234 frame_number = self.quality_sorted_indices[i]
235 else:
236 frame_number = i
237
238 if self.index_included[frame_number]:
239 item = QtWidgets.QListWidgetItem("Frame %i included" % (frame_number + 1))
240 item.setBackground(self.background_included)
241 item.setForeground(self.foreground_included)
242 else:
243 item = QtWidgets.QListWidgetItem("Frame %i excluded" % (frame_number + 1))
244 item.setBackground(self.background_excluded)
245 item.setForeground(self.foreground_excluded)
246 self.listWidget.addItem(item)
247
248 # Set the list widget to the current position.
249 if self.frame_ordering == "quality":
250 self.listWidget.setCurrentRow(self.quality_index,
251 QtCore.QItemSelectionModel.SelectCurrent)
252 else:
253 self.listWidget.setCurrentRow(self.frame_index,
254 QtCore.QItemSelectionModel.SelectCurrent)
255
256 def select_items(self):
257 """
258 If a list item or a range of items is selected, store the items and corresponding indices.
259 Synchronize the frame slider and frame viewer with the the current list position.
260
261 :return: -
262 """
263
264 self.listWidget.currentItem().setSelected(True)
265 self.items_selected = self.listWidget.selectedItems()
266
267 if self.frame_ordering == "quality":
268 self.indices_selected = [self.quality_sorted_indices[self.listWidget.row(item)] for item
269 in self.items_selected]
270 self.frame_index = self.indices_selected[0]
271 self.quality_index = self.rank_indices[self.frame_index]
272 else:
273 self.indices_selected = [self.listWidget.row(item) for item in self.items_selected]
274 self.frame_index = self.indices_selected[0]
275 self.quality_index = self.rank_indices[self.frame_index]
276
277 self.synchronize_slider()
278
279 def synchronize_slider(self):
280 """
281 Set the frame slider to the value currently selected in the listWidget. Update the photo
282 displayed in the viewer.
283
284 :return: -
285 """
286
287 # Block slider signals to avoid a shortcut.
288 self.slider_frames.blockSignals(True)
289
290 if self.frame_ordering == "quality":
291 self.quality_index = self.listWidget.currentRow()
292 self.frame_index = self.quality_sorted_indices[self.quality_index]
293 self.slider_frames.setValue(self.quality_index + 1)
294 else:
295 self.frame_index = self.listWidget.currentRow()
296 self.quality_index = self.rank_indices[self.frame_index]
297 self.slider_frames.setValue(self.frame_index + 1)
298
299 # Unblock the slider signals again.
300 self.slider_frames.blockSignals(False)
301
302 # Update the image in the viewer.
303 self.frame_selector.setPhoto(self.frame_index)
304
305 def eventFilter(self, source, event):
306 """
307 This eventFilter is listening for events on the listWidget. List items can be marked as
308 included / excluded by either using a context menu, by pressing the "+" or "-" buttons, or
309 by pressing the keyboard keys "+" or "-".
310
311 :param source: Source object to listen on.
312 :param event: Event found
313 :return: -
314 """
315
316 if source is self.listWidget:
317
318 # Open a context menu with two choices. Depending on the user's choice, either
319 # trigger the "use_triggered" or "not_use_triggered" method below.
320 if event.type() == QtCore.QEvent.ContextMenu:
321 menu = QtWidgets.QMenu()
322 action1 = QtWidgets.QAction('Use for stacking', menu)
323 action1.triggered.connect(self.use_triggered)
324 menu.addAction((action1))
325 action2 = QtWidgets.QAction("Don't use for stacking", menu)
326 action2.triggered.connect(self.not_use_triggered)
327 menu.addAction((action2))
328 menu.exec_(event.globalPos())
329
330 # Do the same as above if the user prefers to use the keyboard keys "+" or "-".
331 elif event.type() == QtCore.QEvent.KeyPress:
332 if event.key() == Qt.Key_Plus:
333 self.use_triggered()
334 elif event.key() == Qt.Key_Minus:
335 self.not_use_triggered()
336 elif event.key() == Qt.Key_Escape:
337 self.items_selected = []
338 self.indices_selected = []
339 self.listWidget.clearSelection()
340
341 return super(FrameSelectorWidget, self).eventFilter(source, event)
342
343 def use_triggered(self):
344 """
345 The user has selected a list item or a range of items to be included in the stacking
346 workflow. Change the appearance of the list entry, update the "index_included" values for
347 the corresponding frames, and reload the image of the current index. The latter step is
348 important to update the overlay mark in the upper left image corner.
349
350 :return: -
351 """
352
353 self.select_items()
354 if self.items_selected:
355 for index, item in enumerate(self.items_selected):
356 index_selected = self.indices_selected[index]
357 frame_selected = index_selected + 1
358 item.setText("Frame %i included" % frame_selected)
359 item.setBackground(self.background_included)
360 item.setForeground(QtGui.QColor(0, 0, 0))
361 self.index_included[index_selected] = True
362 self.frame_selector.setPhoto(self.frame_index)
363
364 def not_use_triggered(self):
365 """
366 Same as above in case the user has de-selected a list item or a range of items.
367 :return: -
368 """
369
370 self.select_items()
371 if self.items_selected:
372 for index, item in enumerate(self.items_selected):
373 index_selected = self.indices_selected[index]
374 frame_selected = index_selected + 1
375 item.setText("Frame %i excluded" % frame_selected)
376 item.setBackground(self.background_excluded)
377 item.setForeground(QtGui.QColor(255, 255, 255))
378 self.index_included[index_selected] = False
379 self.frame_selector.setPhoto(self.frame_index)
380
381 def slider_frames_changed(self):
382 """
383 The frames slider is changed by the user. Update the frame in the viewer and scroll the
384 frame list to show the current frame index.
385
386 :return: -
387 """
388
389 # Again, please note the difference between indexing and GUI displays.
390 index = self.slider_frames.value() - 1
391
392 # Differentiate between frame ordering (by quality or chronologically).
393 if self.frame_ordering == "quality":
394 self.frame_index = self.quality_sorted_indices[index]
395 self.quality_index = index
396
397 else:
398 self.frame_index = index
399 self.quality_index = self.rank_indices[self.frame_index]
400
401 # Adjust the frame list and select the current frame.
402
403 self.listWidget.setCurrentRow(index, QtCore.QItemSelectionModel.SelectCurrent)
404
405 # Update the image in the viewer.
406 self.frame_selector.setPhoto(self.frame_index)
407 self.listWidget.setFocus()
408
409 def radiobutton_quality_changed(self):
410 """
411 Toggle back and forth between frame ordering modes. The frame slider is updated to reflect
412 the index of the current frame in the new ordering scheme. The frame ordering in the list
413 widget is changed.
414
415 :return: -
416 """
417
418 # Block listWidget signals. Otherwise, changes to the widget triggered by changing the
419 # slider would cause trouble.
420 self.listWidget.blockSignals(True)
421
422 if self.frame_ordering == "quality":
423 self.frame_ordering = "chronological"
424 self.slider_frames.setValue(self.frame_index + 1)
425 else:
426 self.frame_ordering = "quality"
427 self.slider_frames.setValue(self.quality_index + 1)
428
429 self.fill_list_widget()
430
431 # Unblock listWidget signals again.
432 self.listWidget.blockSignals(False)
433
434 def pushbutton_play_clicked(self):
435 """
436 Start the frame player if it is not running already.
437
438 :return: -
439 """
440
441 self.frame_player_start_signal.emit()
442
443 def pushbutton_stop_clicked(self):
444 """
445 When the frame player is running, it periodically checks this variable. If it is set to
446 False, the player stops.
447
448 :return: -
449 """
450
451 if self.frame_player.run_player:
452 self.frame_player.run_player = False
453
454 def done(self):
455 """
456 On exit from the frame viewer, update the selection status of all frames and send a
457 completion signal.
458
459 :return: -
460 """
461
462 # Check if the status of frames has changed.
463 indices_included = []
464 indices_excluded = []
465 for index in range(self.frames.number_original):
466 if self.index_included[index] and not self.frames.index_included[index]:
467 indices_included.append(index)
468 self.frames.index_included[index] = True
469 elif not self.index_included[index] and self.frames.index_included[index]:
470 indices_excluded.append(index)
471 self.frames.index_included[index] = False
472
473 # Write the changes in frame selection to the protocol.
474 if self.configuration.global_parameters_protocol_level > 1:
475 if indices_included:
476 Miscellaneous.protocol(
477 " The user has included the following frames into the stacking "
478 "workflow: " + str(
479 [item + 1 for item in indices_included]), self.stacked_image_log_file,
480 precede_with_timestamp=False)
481 if indices_excluded:
482 Miscellaneous.protocol(
483 " The user has excluded the following frames from the stacking "
484 "workflow: " + str(
485 [item + 1 for item in indices_excluded]), self.stacked_image_log_file,
486 precede_with_timestamp=False)
487 frames_remaining = sum(self.frames.index_included)
488 if frames_remaining != self.frames.number:
489 Miscellaneous.protocol(" " + str(
490 frames_remaining) + " frames will be used in the stacking workflow.",
491 self.stacked_image_log_file, precede_with_timestamp=False)
492
493 # Send a completion message. The "execute_rank_frames" method is triggered on the workflow
494 # thread. The signal payload is True if the status was changed for at least one frame.
495 # In this case, the index translation table is updated before the frame ranking starts.
496 if self.parent_gui is not None:
497 self.signal_finished.emit()
498
499 # Close the Window.
500 self.player_thread.quit()
501 self.close()
502
503 def reject(self):
504 """
505 If the "cancel" button is pressed, the coordinates are not stored.
506
507 :return: -
508 """
509
510 # Send a completion message.
511 if self.parent_gui is not None:
512 self.signal_finished.emit()
513
514 # Close the Window.
515 self.player_thread.quit()
516 self.close()
517
518
519 class FramePlayer(QtCore.QObject):
520 """
521 This class implements a video player using the FrameViewer and the control elements of the
522 FrameViewerWidget. The player is started by the widget on a separate thread. This way the user
523 can instruct the GUI to stop the running player.
524
525 """
526 block_widgets_signal = QtCore.pyqtSignal()
527 unblock_widgets_signal = QtCore.pyqtSignal()
528 set_photo_signal = QtCore.pyqtSignal(int)
529 set_slider_value = QtCore.pyqtSignal(int)
530
531 def __init__(self, frame_selector_widget):
532 super(FramePlayer, self).__init__()
533
534 # Store a reference of the frame selector widget and create a list of GUI elements. This
535 # makes it easier to perform the same operation on all elements.
536 self.frame_selector_widget = frame_selector_widget
537
538 # Set the delay time between frames.
539 self.delay_between_frames = 0.1
540
541 # Initialize a variable used to stop the player in the GUI thread.
542 self.run_player = False
543
544 def play(self):
545 """
546 Start the player.
547 :return: -
548 """
549
550 # Block signals from GUI elements to avoid cross-talk, and disable them to prevent unwanted
551 # user interaction.
552 self.block_widgets_signal.emit()
553
554 # Set the player running.
555 self.run_player = True
556
557 # The frames are ordered by their quality.
558 if self.frame_selector_widget.frame_ordering == "quality":
559
560 # The player stops when the end of the video is reached, or when the "run_player"
561 # variable is set to False in the GUI thread.
562 while self.frame_selector_widget.quality_index < self.frame_selector_widget.frames.number_original \
563 - 1 and self.run_player:
564
565 if not self.frame_selector_widget.frame_selector.image_loading_busy:
566 self.frame_selector_widget.quality_index += 1
567 self.frame_selector_widget.frame_index = \
568 self.frame_selector_widget.quality_sorted_indices[
569 self.frame_selector_widget.quality_index]
570
571 self.set_slider_value.emit(self.frame_selector_widget.quality_index + 1)
572 self.set_photo_signal.emit(self.frame_selector_widget.frame_index)
573
574 # Insert a short pause to keep the video from running too fast.
575 sleep(self.delay_between_frames)
576
577 else:
578 # The same for chronological frame ordering.
579 while self.frame_selector_widget.frame_index < self.frame_selector_widget.frames.number_original \
580 - 1 and self.run_player:
581 if not self.frame_selector_widget.frame_selector.image_loading_busy:
582 self.frame_selector_widget.frame_index += 1
583 self.frame_selector_widget.quality_index = \
584 self.frame_selector_widget.quality_sorted_indices.index(
585 self.frame_selector_widget.frame_index)
586 self.set_slider_value.emit(self.frame_selector_widget.frame_index + 1)
587 self.set_photo_signal.emit(self.frame_selector_widget.frame_index)
588
589 sleep(self.delay_between_frames)
590
591 self.run_player = False
592
593 # Re-set the GUI elements to their normal state.
594 self.unblock_widgets_signal.emit()
595
596
597 if __name__ == '__main__':
598 # Images can either be extracted from a video file or a batch of single photographs. Select
599 # the example for the test run.
600 type = 'video'
601 if type == 'image':
602 names = glob(
603 'Images/2012*.tif') # names = glob.glob('Images/Moon_Tile-031*ap85_8b.tif') # names
604 # = glob.glob('Images/Example-3*.jpg')
605 else:
606 names = 'Videos/another_short_video.avi'
607 print(names)
608
609 # Get configuration parameters.
610 configuration = Configuration()
611 configuration.initialize_configuration()
612 try:
613 frames = Frames(configuration, names, type=type)
614 print("Number of images: " + str(frames.number))
615 print("Image shape: " + str(frames.shape))
616 except Error as e:
617 print("Error: " + e.message)
618 exit()
619
620 # Rank the frames by their overall local contrast.
621 rank_frames = RankFrames(frames, configuration)
622 rank_frames.frame_score()
623
624 print("Best frame index: " + str(rank_frames.frame_ranks_max_index))
625
626 app = QtWidgets.QApplication(argv)
627 window = FrameSelectorWidget(None, configuration, frames, rank_frames, None, None)
628 window.setMinimumSize(800, 600)
629 # window.showMaximized()
630 window.show()
631 app.exec_()
632
633 exit()