Debian Codegraph @

planetary_system_stacker/frame_viewer.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 time, sleep
31
32 import matplotlib
33
34 matplotlib.use('Agg')
35 import matplotlib.pyplot as plt
36 from PyQt5 import QtCore, QtGui, QtWidgets
37 from cv2 import NORM_MINMAX, normalize, cvtColor, COLOR_GRAY2RGB, circle, line
38 from matplotlib import patches
39 from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as Canvas
40 from matplotlib.figure import Figure
41 from numpy import array, full, uint8, uint16, float64
42
43 from align_frames import AlignFrames
44 from configuration import Configuration
45 from exceptions import NotSupportedError, InternalError, Error
46 from frame_viewer_gui import Ui_frame_viewer
47 from frames import Frames
48 from miscellaneous import Miscellaneous
49 from rank_frames import RankFrames
50
51
52 class MatplotlibWidget(Canvas):
53 """
54 This widget creates a plot of frame qualities, either sorted chronologically or by quality.
55
56 """
57
58 def __init__(self, configuration, rank_frames, parent=None):
59 """
60 Initialize the widget.
61
62 :param configuration: Configuration object with parameters
63 :param rank_frames: RankFrames object with global quality ranks (between 0. and 1.,
64 1. being optimal) for all frames
65 :param parent: Parent object
66 """
67
68 super(MatplotlibWidget, self).__init__(Figure())
69
70 self.setParent(parent)
71 self.configuration = configuration
72 self.rank_frames = rank_frames
73 self.line_chronological = None
74 self.line_quality = None
75 self.dot = None
76 self.line_quality_cutoff = None
77 self.patch_quality_cutoff = None
78
79 plt.rcParams.update({'font.size': 8})
80
81 self.fig, self.ax = plt.subplots()
82 self.ax.invert_xaxis()
83 plt.subplots_adjust(left=0.23, right=0.95, top=0.98, bottom=0.12)
84
85 def renew_plot(self, index, frame_ordering, alignment_points_frame_number):
86 """
87 Update the complete plot, including the quality line, the cutoff line, and the dot at the
88 position of the current frame.
89
90 :param index: Index of the current frame (relative to the selected order)
91 :param frame_ordering: Ordering of frames, either "chronological" or "quality"
92 :param alignment_points_frame_number: Number of frames to be stacked at each AP.
93 :return: -
94 """
95
96 self.ax.clear()
97 self.line_quality_cutoff = None
98 self.patch_quality_cutoff = None
99
100 # The quality axis starts with 1. (highest quality).
101 self.ax.invert_xaxis()
102
103 # Remember objects drawn into the plot.
104 self.line_chronological = None
105 self.line_quality = None
106 self.dot = None
107 self.line_quality_cutoff = None
108
109 # Plot the new data.
110 self.plot_data(frame_ordering)
111 self.plot_cutoff_lines(frame_ordering, alignment_points_frame_number)
112 self.plot_dot(index)
113
114 def plot_data(self, frame_ordering):
115 """
116 Plot the quality line. Frames (y axis) are ordered as specified with parameter
117 "frame_ordering".
118
119 :param frame_ordering: Ordering of frames, either "chronological" or "quality"
120 :return: -
121 """
122
123 self.ax.set_ylim(0, self.rank_frames.number + 1)
124 self.y = array(range(1, self.rank_frames.number + 1))
125 if frame_ordering == "chronological":
126 if self.line_chronological is not None:
127 self.line_chronological.remove()
128 self.x = array(self.rank_frames.frame_ranks)
129 plt.ylabel('Frame numbers ordered chronologically')
130 plt.gca().invert_yaxis()
131 plt.xlabel('Quality')
132 self.line_chronological, = plt.plot(self.x, self.y, lw=1, color='blue')
133 plt.grid(True)
134 else:
135 if self.line_quality is not None:
136 self.line_quality.remove()
137 self.x = array(
138 [self.rank_frames.frame_ranks[i] for i in self.rank_frames.quality_sorted_indices])
139 plt.ylabel('Frame numbers ordered by quality')
140 plt.gca().invert_yaxis()
141 plt.xlabel('Quality')
142 self.line_quality, = plt.plot(self.x, self.y, lw=1, color='green')
143 plt.grid(True)
144 self.fig.canvas.draw()
145 self.fig.canvas.flush_events()
146
147 def plot_cutoff_lines(self, frame_ordering, alignment_points_frame_number):
148 """
149 Plot a horizontal (if frames are ordered by quality) or vertical (if frames are ordered
150 chronologically) line to separate frames to be stacked from the other ones.
151
152 :param frame_ordering: Ordering of frames, either "chronological" or "quality"
153 :param alignment_points_frame_number: Number of frames to be stacked at each AP.
154 :return: -
155 """
156 if frame_ordering == "chronological":
157 if self.line_quality_cutoff is not None:
158 self.line_quality_cutoff.remove()
159 if self.patch_quality_cutoff is not None:
160 self.patch_quality_cutoff.remove()
161 quality_cutoff = self.rank_frames.frame_ranks[
162 self.rank_frames.quality_sorted_indices[alignment_points_frame_number-1]]
163 x_cutoff = full((self.rank_frames.number,), quality_cutoff)
164 self.line_quality_cutoff, = plt.plot(x_cutoff, self.y, lw=1, color='orange')
165 width = 1. - quality_cutoff
166 height = self.rank_frames.number - 1
167 xy = (quality_cutoff, 1.)
168 else:
169 if self.line_quality_cutoff is not None:
170 self.line_quality_cutoff.remove()
171 if self.patch_quality_cutoff is not None:
172 self.patch_quality_cutoff.remove()
173 y_cutoff = full((self.rank_frames.number,), alignment_points_frame_number)
174 self.line_quality_cutoff, = plt.plot(self.x, y_cutoff, lw=1, color='orange')
175 width = 1. - self.x[-1]
176 height = alignment_points_frame_number
177 xy = (self.x[-1], 0.)
178 self.patch_quality_cutoff = patches.Rectangle(xy, width, height, linewidth=None,
179 facecolor=(0.5, 0.2, 0., 0.15))
180 self.ax.add_patch(self.patch_quality_cutoff)
181 self.fig.canvas.draw()
182 self.fig.canvas.flush_events()
183
184 def plot_dot(self, frame_index):
185 """
186 Plot a dot on the quality line at the position of the current frame.
187
188 :param frame_index: Frame index
189 :return: -
190 """
191
192 if self.dot is not None:
193 self.dot.remove()
194 self.dot = plt.scatter(self.x[frame_index], self.y[frame_index], s=20, color='red')
195 self.fig.canvas.draw()
196 self.fig.canvas.flush_events()
197
198
199 class FrameViewer(QtWidgets.QGraphicsView):
200 """
201 This widget implements a frame viewer. Panning and zooming is implemented by using the mouse
202 and scroll wheel.
203
204 """
205
206 zoom_factor_signal = QtCore.pyqtSignal(int)
207
208 def __init__(self):
209 super(FrameViewer, self).__init__()
210 self._empty = True
211
212 # Initialize a flag which indicates when an image is being loaded.
213 self.image_loading_busy = False
214
215 # Initialize the photo object. No image is loaded yet.
216 self._photo = QtWidgets.QGraphicsPixmapItem()
217 self.shape_y = None
218 self.shape_x = None
219
220 self.viewrect = self.viewport().rect()
221
222 self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
223 self.setResizeAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
224 self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
225 self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
226 self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(30, 30, 30)))
227 self.setFrameShape(QtWidgets.QFrame.NoFrame)
228 self.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag)
229 self.drag_mode = True
230
231 # Set the focus on the viewer.
232 self.setFocus()
233
234 def resizeEvent(self, event):
235 """
236 This method is called when the window size changes. In this case the image is zoomed so it
237 fills the entire view.
238
239 :param event: Resize event.
240 :return: -
241 """
242
243 # Set the rectangle surrounding the current view.
244 self.viewrect = self.viewport().rect()
245 self.fitInView()
246 return super(FrameViewer, self).resizeEvent(event)
247
248 def hasPhoto(self):
249 return not self._empty
250
251 def get_zoom_factor(self):
252 """
253 Compute the current zoom factor. It is sent to the GUI widget via the "zoom_factor_signal".
254
255 :return: The current zoom factor, rounded to the next int.
256 """
257
258 zoom_factor = round(self.scenerect.width() / self.photorect.width() * 100.)
259 self.zoom_factor_signal.emit(zoom_factor)
260 return zoom_factor
261
262 def fitInView(self):
263 """
264 Scale the scene such that it fits into the window completely.
265
266 :return: -
267 """
268
269 if not self.photorect.isNull():
270 if self.hasPhoto():
271 factor = min(self.viewrect.width() / self.scenerect.width(),
272 self.viewrect.height() / self.scenerect.height())
273 self.scale(factor, factor)
274 self.scenerect = self.transform().mapRect(self.photorect)
275 self.get_zoom_factor()
276
277 def set_original_scale(self):
278 """
279 Scale the scene to the original size of the photo. If the photo has more pixels than the
280 current view, only part of the image is displayed.
281
282 :return: -
283 """
284
285 if not self.photorect.isNull():
286 if self.hasPhoto():
287 factor = min(self.photorect.width() / self.scenerect.width(),
288 self.photorect.height() / self.scenerect.height())
289 self.scale(factor, factor)
290 self.scenerect = self.transform().mapRect(self.photorect)
291 self.get_zoom_factor()
292
293 def setPhoto(self, image, overlay_exclude_mark=False):
294 """
295 Convert a color or grayscale image to a pixmap and assign it to the photo object.
296
297 :param image: Image to be displayed. The image is assumed to be in color or grayscale
298 format of length uint8 or uint16.
299 :param overlay_exclude_mark: If True, overlay a crossed-out red circle in the upper left
300 corner of the image.
301 :return: -
302 """
303
304 # Indicate that an image is being loaded.
305 self.image_loading_busy = True
306
307 # Convert the image into uint8 format. If the frame type is uint16, values correspond to
308 # 16bit resolution.
309 if image.dtype == uint16:
310 image_uint8 = (image / 256.).astype(uint8)
311 elif image.dtype == uint8:
312 image_uint8 = image.astype(uint8)
313 elif image.dtype == float64:
314 image_uint8 = image.astype(uint8)
315 else:
316 raise NotSupportedError("Attempt to set a photo in frame viewer with type neither"
317 " uint8 nor uint16 nor float64")
318
319 self.shape_y = image_uint8.shape[0]
320 self.shape_x = image_uint8.shape[1]
321
322 # Normalize the frame brightness.
323 image_uint8 = normalize(image_uint8, None, alpha=0, beta=255, norm_type=NORM_MINMAX)
324
325 # Overlay a crossed-out red circle in the upper left image corner.
326 if overlay_exclude_mark:
327 if len(image_uint8.shape) == 2:
328 image_uint8 = cvtColor(image_uint8, COLOR_GRAY2RGB)
329
330 # The position and size of the mark are relative to the image size.
331 pos_x = int(round(self.shape_x / 10))
332 pos_y = int(round(self.shape_y / 10))
333 diameter = int(round(min(pos_x, pos_y) / 4))
334 circle(image_uint8, (pos_x, pos_y), diameter, (255, 0, 0), 2)
335 line(image_uint8, (pos_x - diameter, pos_y + diameter),
336 (pos_x + diameter, pos_y - diameter), (255, 0, 0), 2)
337
338 # The image is monochrome:
339 if len(image_uint8.shape) == 2:
340 qt_image = QtGui.QImage(image_uint8, self.shape_x, self.shape_y, self.shape_x,
341 QtGui.QImage.Format_Grayscale8)
342 # The image is RGB color.
343 else:
344 qt_image = QtGui.QImage(image_uint8, self.shape_x,
345 self.shape_y, 3 * self.shape_x, QtGui.QImage.Format_RGB888)
346 pixmap = QtGui.QPixmap(qt_image)
347
348 if pixmap and not pixmap.isNull():
349 self._empty = False
350 self._photo.setPixmap(pixmap)
351 else:
352 self._empty = True
353 self._photo.setPixmap(QtGui.QPixmap())
354
355 # Initialize the scene. This object handles mouse events if not in drag mode.
356 self.initialize_scene()
357
358 # Set the new rectangles surrounding the photo and the current scene.
359 self.photorect = QtCore.QRectF(self._photo.pixmap().rect())
360 self.scenerect = self.transform().mapRect(self.photorect)
361
362 # Release the image loading flag.
363 self.image_loading_busy = False
364
365 def initialize_scene(self):
366 """
367 Initialize the scene. This object handles mouse events if not in drag mode. In derived
368 viewer classes this method is replaced with the instantiation of a custom version of the
369 graphics scene.
370
371 :return:
372 """
373
374 self._scene = QtWidgets.QGraphicsScene()
375 self._scene.addItem(self._photo)
376 self.setScene(self._scene)
377
378 def wheelEvent(self, event):
379 """
380 Handle scroll events for zooming in and out of the scene. This is only active when a photo
381 is loaded.
382
383 :param event: wheel event object
384 :return: -
385 """
386
387 if self.drag_mode:
388 # Depending of wheel direction, set the direction value to greater or smaller than 1.
389 self.zoom(event.angleDelta().y())
390
391 # If not in drag mode, the wheel event is handled at the scene level.
392 else:
393 try:
394 self._scene.wheelEvent(event)
395
396 # This exception occurs if the user uses "Ctrl + Wheel action" in the postproc_editor.
397 # There this activity does not make any sense, so just ignore the event.
398 except TypeError:
399 pass
400
401 def zoom(self, direction):
402 """
403 Zoom in or out. This is only active when a photo is loaded. For small images (smaller than
404 the current view), zooming out is limited by the original photo resolution. For larger
405 images zooming out stops when the scene fills the entire view.
406
407 :param direction: If > 0, zoom in, otherwise zoom out.
408 :return: -
409 """
410
411 if self.hasPhoto():
412 # Depending of direction value, set the zoom factor to greater or smaller than 1.
413 if direction > 0:
414 factor = 1.25
415 else:
416 min_factor = min(
417 min(self.photorect.width(), self.viewrect.width()) / self.scenerect.width(),
418 min(self.photorect.height(), self.viewrect.height()) / self.scenerect.height())
419 factor = max(0.8, min_factor)
420
421 self.scale(factor, factor)
422 self.scenerect = self.transform().mapRect(self.photorect)
423 self.get_zoom_factor()
424
425 def keyPressEvent(self, event):
426 """
427 The + and - keys are used for zooming.
428
429 :param event: event object
430 :return: -
431 """
432
433 # If the "+" key is pressed, zoom in. If "-" is pressed, zoom out.
434 if event.key() == QtCore.Qt.Key_Control:
435 self.setDragMode(QtWidgets.QGraphicsView.NoDrag)
436 self.drag_mode = False
437 elif event.key() == QtCore.Qt.Key_Plus and not event.modifiers() & QtCore.Qt.ControlModifier:
438 self.zoom(1)
439 elif event.key() == QtCore.Qt.Key_Minus and not event.modifiers() & QtCore.Qt.ControlModifier:
440 self.zoom(-1)
441 elif event.key() == QtCore.Qt.Key_1 and not event.modifiers() & QtCore.Qt.ControlModifier:
442 self.set_original_scale()
443 else:
444 super(FrameViewer, self).keyPressEvent(event)
445
446 def keyReleaseEvent(self, event):
447 # If the control key is released, switch back to "drag mode".
448 # Use default handling for other keys.
449 if event.key() == QtCore.Qt.Key_Control:
450 self.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag)
451 self.drag_mode = True
452 else:
453 super(FrameViewer, self).keyReleaseEvent(event)
454
455
456 class VideoFrameViewer(FrameViewer):
457 """
458 This widget implements a frame viewer for frames in a video file. Panning and zooming is
459 implemented by using the mouse and scroll wheel.
460
461 """
462
463 def __init__(self, frames, align_frames, frame_index=0):
464 super(VideoFrameViewer, self).__init__()
465 self.frames = frames
466 self.align_frames = align_frames
467 self.frame_index = frame_index
468
469 self.setPhoto(self.frame_index)
470
471 def setPhoto(self, index):
472 """
473 Convert a grayscale image to a pixmap and assign it to the photo object.
474
475 :param index: Index into the frame list. Frames are assumed to be grayscale image in format
476 uint8 or uint16.
477 :return: -
478 """
479
480 # Indicate that an image is being loaded.
481 self.image_loading_busy = True
482
483 image = self.frames.frames_mono(index)[self.align_frames.intersection_shape[0][0] -
484 self.align_frames.frame_shifts[index][0]:
485 self.align_frames.intersection_shape[0][1] -
486 self.align_frames.frame_shifts[index][0],
487 self.align_frames.intersection_shape[1][0] -
488 self.align_frames.frame_shifts[index][1]:
489 self.align_frames.intersection_shape[1][1] -
490 self.align_frames.frame_shifts[index][1]]
491
492 super(VideoFrameViewer, self).setPhoto(image)
493
494
495 class FrameViewerWidget(QtWidgets.QFrame, Ui_frame_viewer):
496 """
497 This widget implements a frame viewer together with control elements to visualize frame
498 qualities, and to manipulate the stack limits.
499 """
500
501 frame_player_start_signal = QtCore.pyqtSignal()
502
503 def __init__(self, parent_gui, configuration, frames, rank_frames, align_frames,
504 stacked_image_log_file, signal_finished, signal_payload):
505 """
506 Initialization of the widget.
507
508 :param parent_gui: Parent GUI object
509 :param configuration: Configuration object with parameters
510 :param frames: Frames object with all video frames
511 :param rank_frames: RankFrames object with global quality ranks (between 0. and 1.,
512 1. being optimal) for all frames
513 :param align_frames: AlignFrames object with global shift information for all frames
514 :param stacked_image_log_file: Log file to be stored with results, or None.
515 :param signal_finished: Qt signal with signature (str) to trigger the next activity when
516 the viewer exits.
517 :param signal_payload: Payload of "signal_finished" (str).
518 """
519
520 super(FrameViewerWidget, self).__init__(parent_gui)
521 self.setupUi(self)
522
523 # Keep references to upper level objects.
524 self.parent_gui = parent_gui
525 self.configuration = configuration
526 self.stacked_image_log_file = stacked_image_log_file
527 self.signal_finished = signal_finished
528 self.signal_payload = signal_payload
529 self.frames = frames
530 self.rank_frames = rank_frames
531 self.align_frames = align_frames
532
533 # Be careful: Indices are counted from 0, while widget contents are counted from 1 (to make
534 # it easier for the user.
535 self.quality_index = 0
536 self.frame_index = self.rank_frames.quality_sorted_indices[self.quality_index]
537
538 # Set up the frame viewer and put it in the upper left corner.
539 self.frame_viewer = VideoFrameViewer(self.frames, self.align_frames, self.frame_index)
540 self.frame_viewer.setObjectName("framewiever")
541 self.grid_layout.addWidget(self.frame_viewer, 0, 0, 4, 3)
542
543 self.widget_elements = [self.spinBox_chronological,
544 self.spinBox_quality,
545 self.slider_frames,
546 self.pushButton_play]
547
548 # Initialize variables. The values for "alignment_point_frame_number" and
549 # "alignment_points_frame_percent" are held as copies in this object. Only if the user
550 # presses "OK" at the end, the values are copied back into the configuration object.
551 self.stack_size_changed = None
552
553 # The number of frames to be stacked is selected explicitly.
554 if self.configuration.alignment_points_frame_number > 0:
555 self.alignment_points_frame_number = min(
556 self.configuration.alignment_points_frame_number, self.frames.number)
557 self.alignment_points_frame_percent = max(1, min(round(
558 self.alignment_points_frame_number / self.frames.number * 100.), 100))
559 else:
560 self.alignment_points_frame_percent = self.configuration.alignment_points_frame_percent
561 self.alignment_points_frame_number = max(1, round(
562 self.frames.number * self.alignment_points_frame_percent / 100.))
563
564 self.frame_ranks = rank_frames.frame_ranks
565 self.quality_sorted_indices = rank_frames.quality_sorted_indices
566
567 # Start with ordering frames by quality. This can be changed by the user using a radio
568 # button.
569 self.frame_ordering = "quality"
570
571 # Initialize a variable for communication with the frame_player object later.
572 self.run_player = False
573
574 # Create the frame player thread and start it. The player displays frames in succession.
575 # It is pushed on a different thread because otherwise the user could not stop it before it
576 # finishes.
577 self.frame_player = FramePlayer(self)
578 self.player_thread = QtCore.QThread()
579 self.frame_player.setParent(None)
580 self.frame_player.moveToThread(self.player_thread)
581 self.frame_player.block_widgets_signal.connect(self.block_widgets)
582 self.frame_player.unblock_widgets_signal.connect(self.unblock_widgets)
583 self.frame_player.set_photo_signal.connect(self.frame_viewer.setPhoto)
584 self.frame_player.set_slider_value.connect(self.slider_frames.setValue)
585 self.frame_player_start_signal.connect(self.frame_player.play)
586 self.player_thread.start()
587
588 # Initialization of GUI elements
589 self.slider_frames.setMinimum(1)
590 self.slider_frames.setMaximum(self.frames.number)
591 self.slider_frames.setValue(self.quality_index + 1)
592 self.spinBox_chronological.setMinimum(1)
593 self.spinBox_chronological.setMaximum(self.frames.number)
594 self.spinBox_chronological.setValue(self.frame_index + 1)
595 self.spinBox_quality.setMinimum(1)
596 self.spinBox_quality.setMaximum(self.frames.number)
597 self.spinBox_quality.setValue(self.quality_index + 1)
598 self.radioButton_quality.setChecked(True)
599
600 self.spinBox_number_frames.setMaximum(self.frames.number)
601 self.spinBox_number_frames.setValue(self.alignment_points_frame_number)
602 self.spinBox_percentage_frames.setValue(self.alignment_points_frame_percent)
603
604 # Create the Matplotlib widget showing the quality lines.
605 self.matplotlib_widget = MatplotlibWidget(self.configuration, self.rank_frames)
606
607 self.grid_layout.addWidget(Canvas(self.matplotlib_widget.fig), 0, 3, 2, 1)
608
609 self.grid_layout.setColumnStretch(0, 5)
610 self.grid_layout.setColumnStretch(1, 0)
611 self.grid_layout.setColumnStretch(2, 0)
612 self.grid_layout.setColumnStretch(3, 1)
613 self.grid_layout.setRowStretch(0, 1)
614 self.grid_layout.setRowStretch(1, 0)
615 self.grid_layout.setRowStretch(2, 0)
616 self.grid_layout.setRowStretch(3, 0)
617
618 # Connect signals with slots.
619 self.buttonBox.accepted.connect(self.done)
620 self.buttonBox.rejected.connect(self.reject)
621 self.slider_frames.valueChanged.connect(self.slider_frames_changed)
622 self.spinBox_number_frames.valueChanged.connect(self.spinbox_number_frames_changed)
623 self.spinBox_percentage_frames.valueChanged.connect(self.spinbox_percentage_frames_changed)
624 self.radioButton_quality.toggled.connect(self.radiobutton_quality_changed)
625 self.spinBox_chronological.valueChanged.connect(self.spinbox_chronological_changed)
626 self.spinBox_quality.valueChanged.connect(self.spinbox_quality_changed)
627 self.pushButton_set_stacking_limit.clicked.connect(
628 self.pushbutton_set_stacking_limit_clicked)
629 self.pushButton_play.clicked.connect(self.pushbutton_play_clicked)
630 self.pushButton_stop.clicked.connect(self.pushbutton_stop_clicked)
631
632 # Initialize the Matplotlib widget contents.
633 self.matplotlib_widget.renew_plot(self.quality_index, self.frame_ordering,
634 self.alignment_points_frame_number)
635
636 @QtCore.pyqtSlot()
637 def block_widgets(self):
638 """
639 Disable GUI elements to prevent unwanted user interaction while the frame player is running.
640
641 :return: -
642 """
643
644 for element in self.widget_elements:
645 element.setDisabled(True)
646
647 @QtCore.pyqtSlot()
648 def unblock_widgets(self):
649 """
650 Enable GUI elements which were temporarily blocked when the player stops.
651
652 :return: -
653 """
654
655 for element in self.widget_elements:
656 element.setDisabled(False)
657
658 def slider_frames_changed(self):
659 """
660 The frames slider is changed by the user.
661
662 :return: -
663 """
664
665 # Again, please note the difference between indexing and GUI displays.
666 index = self.slider_frames.value() - 1
667
668 # Differentiate between frame ordering (by quality or chronologically).
669 if self.frame_ordering == "quality":
670 self.frame_index = self.rank_frames.quality_sorted_indices[index]
671 self.quality_index = index
672
673 # Plot a dot on the quality line at the position of the current frame.
674 self.matplotlib_widget.plot_dot(self.quality_index)
675 else:
676 self.frame_index = index
677 self.quality_index = self.rank_frames.quality_sorted_indices.index(self.frame_index)
678 self.matplotlib_widget.plot_dot(self.frame_index)
679
680 # Block signals temporarily to avoid feedback loops. Then update widget contents.
681 self.spinBox_chronological.blockSignals(True)
682 self.spinBox_quality.blockSignals(True)
683 self.spinBox_chronological.setValue(self.frame_index + 1)
684 self.spinBox_quality.setValue(self.quality_index + 1)
685 self.spinBox_chronological.blockSignals(False)
686 self.spinBox_quality.blockSignals(False)
687 self.frame_viewer.setPhoto(self.frame_index)
688
689 def spinbox_number_frames_changed(self):
690 """
691 The user has changed the number of frames to be stacked at each AP.
692
693 :return: -
694 """
695
696 self.alignment_points_frame_number = self.spinBox_number_frames.value()
697 self.alignment_points_frame_percent = int(
698 round(self.alignment_points_frame_number * 100. / self.frames.number))
699 self.spinBox_percentage_frames.blockSignals(True)
700 self.spinBox_percentage_frames.setValue(self.alignment_points_frame_percent)
701 self.spinBox_percentage_frames.blockSignals(False)
702 self.matplotlib_widget.plot_cutoff_lines(self.frame_ordering,
703 self.alignment_points_frame_number)
704 self.stack_size_changed = 'number'
705
706 def spinbox_percentage_frames_changed(self):
707 """
708 The user has changed the percentage of frames to be stacked at each AP.
709
710 :return:
711 """
712
713 self.alignment_points_frame_percent = self.spinBox_percentage_frames.value()
714 self.alignment_points_frame_number = max(1, round(
715 self.frames.number * self.alignment_points_frame_percent / 100.))
716 self.spinBox_number_frames.blockSignals(True)
717 self.spinBox_number_frames.setValue(self.alignment_points_frame_number)
718 self.spinBox_number_frames.blockSignals(False)
719 self.matplotlib_widget.plot_cutoff_lines(self.frame_ordering,
720 self.alignment_points_frame_number)
721 self.stack_size_changed = 'percent'
722
723 def radiobutton_quality_changed(self):
724 """
725 Toggle back and forth between frame ordering modes. The frame slider is updated to reflect
726 the index of the current frame in the new ordering scheme. The Matplotlib widget changes
727 its appearance.
728
729 :return: -
730 """
731
732 if self.frame_ordering == "quality":
733 self.frame_ordering = "chronological"
734 self.slider_frames.setValue(self.frame_index + 1)
735 self.matplotlib_widget.renew_plot(self.frame_index, self.frame_ordering,
736 self.alignment_points_frame_number)
737 else:
738 self.frame_ordering = "quality"
739 self.slider_frames.setValue(self.quality_index + 1)
740 self.matplotlib_widget.renew_plot(self.quality_index, self.frame_ordering,
741 self.alignment_points_frame_number)
742
743 def spinbox_chronological_changed(self):
744 """
745 The user has selected a new frame to be displayed by entering its chronological frame index.
746 All other widgets which depend on the current frame index are changed.
747
748 :return: -
749 """
750
751 self.frame_index = self.spinBox_chronological.value() - 1
752 self.quality_index = self.rank_frames.quality_sorted_indices.index(self.frame_index)
753 self.slider_frames.blockSignals(True)
754 self.spinBox_quality.blockSignals(True)
755 self.spinBox_quality.setValue(self.quality_index + 1)
756 if self.frame_ordering == "quality":
757 self.slider_frames.setValue(self.quality_index + 1)
758 self.matplotlib_widget.plot_dot(self.quality_index)
759 else:
760 self.slider_frames.setValue(self.frame_index + 1)
761 self.matplotlib_widget.plot_dot(self.frame_index)
762 self.slider_frames.blockSignals(False)
763 self.spinBox_quality.blockSignals(False)
764 self.frame_viewer.setPhoto(self.frame_index)
765
766 def spinbox_quality_changed(self):
767 """
768 The user has selected a new frame to be displayed by entering its quality index.
769 All other widgets which depend on the current frame index are changed.
770
771 :return:
772 """
773
774 self.quality_index = self.spinBox_quality.value() - 1
775 self.frame_index = self.rank_frames.quality_sorted_indices[self.quality_index]
776 self.slider_frames.blockSignals(True)
777 self.spinBox_chronological.blockSignals(True)
778 self.spinBox_chronological.setValue(self.frame_index + 1)
779 if self.frame_ordering == "quality":
780 self.slider_frames.setValue(self.quality_index + 1)
781 self.matplotlib_widget.plot_dot(self.quality_index)
782 else:
783 self.slider_frames.setValue(self.frame_index + 1)
784 self.matplotlib_widget.plot_dot(self.frame_index)
785 self.slider_frames.blockSignals(False)
786 self.spinBox_chronological.blockSignals(False)
787 self.frame_viewer.setPhoto(self.frame_index)
788
789 def pushbutton_set_stacking_limit_clicked(self):
790 """
791 The current frame defines the stacking limit. Compute the corresponding stack limit
792 variables and update the widgets. Since the signals are not deactivated before updating
793 the widgets, the Matplotlib widget gets updated as well.
794 :return:
795 """
796 self.alignment_points_frame_number = self.quality_index + 1
797 self.alignment_points_frame_percent = max(1, round(
798 self.alignment_points_frame_number * 100. / self.frames.number))
799 self.spinBox_number_frames.setValue(self.alignment_points_frame_number)
800 self.spinBox_percentage_frames.setValue(self.alignment_points_frame_percent)
801 self.stack_size_changed = 'number'
802
803 @QtCore.pyqtSlot()
804 def pushbutton_play_clicked(self):
805 """
806 Start the frame player if it is not running already.
807
808 :return: -
809 """
810
811 self.frame_player_start_signal.emit()
812
813 def pushbutton_stop_clicked(self):
814 """
815 When the frame player is running, it periodically checks this variable. If it is set to
816 False, the player stops.
817
818 :return:
819 """
820
821 self.frame_player.run_player = False
822
823 def done(self):
824 """
825 On exit from the frame viewer, update the stack frame size and send a completion signal.
826
827 :return: -
828 """
829
830 # Check if a new stack size was selected.
831 if self.stack_size_changed is not None:
832
833 # The number of frames has been set explicitly. Check if it has changed.
834 if self.stack_size_changed == 'number':
835 if self.spinBox_number_frames.value() != self.configuration.alignment_points_frame_number:
836 self.configuration.alignment_points_frame_number = self.spinBox_number_frames.value()
837 self.configuration.alignment_points_frame_percent = -1
838 if self.configuration.global_parameters_protocol_level > 1:
839 Miscellaneous.protocol(
840 " The user has selected a new stack size: " + str(
841 self.configuration.alignment_points_frame_number) + " frames.",
842 self.stacked_image_log_file, precede_with_timestamp=False)
843
844 # The percentage of frames has been set. Check if it has changed.
845 elif self.spinBox_percentage_frames.value() != self.configuration.alignment_points_frame_percent:
846 self.configuration.alignment_points_frame_number = -1
847 self.configuration.alignment_points_frame_percent = \
848 self.spinBox_percentage_frames.value()
849 if self.configuration.global_parameters_protocol_level > 1:
850 Miscellaneous.protocol(
851 " The user has selected a new stack size: " + str(
852 self.configuration.alignment_points_frame_percent) + "% of all frames.",
853 self.stacked_image_log_file, precede_with_timestamp=False)
854
855 # Send a completion message.
856 if self.parent_gui is not None:
857 self.signal_finished.emit(self.signal_payload)
858
859 # Close the Window.
860 self.player_thread.quit()
861 plt.close()
862 self.close()
863
864 def reject(self):
865 """
866 If the "cancel" button is pressed, the coordinates are not stored.
867
868 :return: -
869 """
870
871 # Send a completion message.
872 if self.parent_gui is not None:
873 self.signal_finished.emit(self.signal_payload)
874
875 # Close the Window.
876 self.player_thread.quit()
877 plt.close()
878 self.close()
879
880
881 class FramePlayer(QtCore.QObject):
882 """
883 This class implements a video player using the FrameViewer and the control elements of the
884 FrameViewerWidget. The player is started by the widget on a separate thread. This way the user
885 can instruct the GUI to stop the running player.
886
887 """
888
889 block_widgets_signal = QtCore.pyqtSignal()
890 unblock_widgets_signal = QtCore.pyqtSignal()
891 set_photo_signal = QtCore.pyqtSignal(int)
892 set_slider_value = QtCore.pyqtSignal(int)
893
894 def __init__(self, frame_viewer_widget, parent=None):
895 super(FramePlayer, self).__init__()
896
897 # Store a reference of the frame viewer widget.
898 self.frame_viewer_widget = frame_viewer_widget
899
900 # Set the delay time between frames.
901 self.delay_between_frames = 0.1
902
903 # Initialize a variable used to stop the player in the GUI thread.
904 self.run_player = False
905
906 @QtCore.pyqtSlot()
907 def play(self):
908 """
909 Start the player.
910 :return: -
911 """
912
913 # Block signals from GUI elements to avoid cross-talk, and disable them to prevent unwanted
914 # user interaction.
915 self.block_widgets_signal.emit()
916
917 # Set the plaer running.
918 self.run_player = True
919
920 # The frames are ordered by their quality.
921 if self.frame_viewer_widget.frame_ordering == "quality":
922
923 # The player stops when the end of the video is reached, or when the "run_player"
924 # variable is set to False in the GUI thread.
925 while self.frame_viewer_widget.quality_index < self.frame_viewer_widget.frames.number \
926 - 1 and self.run_player:
927 # Go to the next frame only if the viewer has finished loading the previous one.
928 if not self.frame_viewer_widget.frame_viewer.image_loading_busy:
929 self.frame_viewer_widget.quality_index += 1
930 self.frame_viewer_widget.frame_index = \
931 self.frame_viewer_widget.rank_frames.quality_sorted_indices[
932 self.frame_viewer_widget.quality_index]
933 self.set_slider_value.emit(self.frame_viewer_widget.quality_index + 1)
934 self.set_photo_signal.emit(self.frame_viewer_widget.frame_index)
935
936 # Insert a short pause to keep the video from running too fast.
937 sleep(self.delay_between_frames)
938
939 else:
940 # The same for chronological frame ordering.
941 while self.frame_viewer_widget.frame_index < self.frame_viewer_widget.frames.number \
942 - 1 and self.run_player:
943 if not self.frame_viewer_widget.frame_viewer.image_loading_busy:
944 self.frame_viewer_widget.frame_index += 1
945 self.frame_viewer_widget.quality_index = \
946 self.frame_viewer_widget.rank_frames.quality_sorted_indices.index(
947 self.frame_viewer_widget.frame_index)
948 self.set_slider_value.emit(self.frame_viewer_widget.frame_index + 1)
949 self.set_photo_signal.emit(self.frame_viewer_widget.frame_index)
950 sleep(self.delay_between_frames)
951
952 self.run_player = False
953
954 # Re-set the GUI elements to their normal state.
955 self.unblock_widgets_signal.emit()
956
957
958 if __name__ == '__main__':
959 # Images can either be extracted from a video file or a batch of single photographs. Select
960 # the example for the test run.
961 type = 'video'
962 if type == 'image':
963 names = glob(
964 'Images/2012*.tif') # names = glob.glob('Images/Moon_Tile-031*ap85_8b.tif') # names
965 # = glob.glob('Images/Example-3*.jpg')
966 else:
967 names = 'Videos/another_short_video.avi'
968 print(names)
969
970 # Get configuration parameters.
971 configuration = Configuration()
972 configuration.initialize_configuration()
973 try:
974 frames = Frames(configuration, names, type=type)
975 print("Number of images read: " + str(frames.number))
976 print("Image shape: " + str(frames.shape))
977 except Error as e:
978 print("Error: " + e.message)
979 exit()
980
981 # Rank the frames by their overall local contrast.
982 rank_frames = RankFrames(frames, configuration)
983 start = time()
984 rank_frames.frame_score()
985 end = time()
986 print('Elapsed time in ranking images: {}'.format(end - start))
987 print("Index of maximum: " + str(rank_frames.frame_ranks_max_index))
988 print("Frame scores: " + str(rank_frames.frame_ranks))
989 print("Frame scores (sorted): " + str(
990 [rank_frames.frame_ranks[i] for i in rank_frames.quality_sorted_indices]))
991 print("Sorted index list: " + str(rank_frames.quality_sorted_indices))
992
993 # Initialize the frame alignment object.
994 align_frames = AlignFrames(frames, rank_frames, configuration)
995
996 if configuration.align_frames_mode == "Surface":
997 # Select the local rectangular patch in the image where the L gradient is highest in both x
998 # and y direction. The scale factor specifies how much smaller the patch is compared to the
999 # whole image frame.
1000 (y_low_opt, y_high_opt, x_low_opt, x_high_opt) = align_frames.compute_alignment_rect(
1001 configuration.align_frames_rectangle_scale_factor)
1002
1003 print("optimal alignment rectangle, y_low: " + str(y_low_opt) + ", y_high: " +
1004 str(y_high_opt) + ", x_low: " + str(x_low_opt) + ", x_high: " + str(x_high_opt))
1005
1006 # Align all frames globally relative to the frame with the highest score.
1007 try:
1008 align_frames.align_frames()
1009 except NotSupportedError as e:
1010 print("Error: " + e.message)
1011 exit()
1012 except InternalError as e:
1013 print("Warning: " + e.message)
1014
1015 print("Intersection, y_low: " + str(align_frames.intersection_shape[0][0]) + ", y_high: "
1016 + str(align_frames.intersection_shape[0][1]) + ", x_low: " \
1017 + str(align_frames.intersection_shape[1][0]) + ", x_high: " \
1018 + str(align_frames.intersection_shape[1][1]))
1019
1020 app = QtWidgets.QApplication(argv)
1021 window = FrameViewerWidget(None, configuration, frames, rank_frames, align_frames, None, None,
1022 None)
1023 window.setMinimumSize(800, 600)
1024 window.showMaximized()
1025 app.exec_()
1026
1027 print("Percentage of frames to be stacked: " + str(
1028 configuration.alignment_points_frame_percent) + ", number of frames: " + str(
1029 configuration.alignment_points_frame_number))
1030
1031 exit()