Debian Codegraph @

planetary_system_stacker/rectangular_patch_editor.py

raw symbols SCIP
1 # -*- coding: utf-8; -*-
2 """
3 Copyright (c) 2018 Rolf Hempel, [email protected]
4
5 This file is part of the PlanetarySystemStacker tool (PSS).
6 https://github.com/Rolf-Hempel/PlanetarySystemStacker
7
8 PSS is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with PSS. If not, see <http://www.gnu.org/licenses/>.
20
21 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 from glob import glob
26 from sys import argv, exit
27 from time import time
28
29 from PyQt5 import QtCore, QtWidgets
30 from numpy import uint8, uint16, int32
31
32 from align_frames import AlignFrames
33 from alignment_point_editor import SelectionRectangleGraphicsItem
34 from configuration import Configuration
35 from exceptions import InternalError, NotSupportedError, Error
36 from frame_viewer import FrameViewer
37 from frames import Frames
38 from rank_frames import RankFrames
39 from rectangular_patch_editor_gui import Ui_rectangular_patch_editor
40
41
42 class GraphicsScene(QtWidgets.QGraphicsScene):
43 """
44 Handle mouse events on the graphics scene depicting the image with a rectangular patch
45 superimposed. The left mouse button can be used to create the patch.
46
47 """
48
49 def __init__(self, photo_editor, parent=None):
50 """
51 Initialize the scene object.
52
53 :param photo_editor: the object in which the scene is defined
54 :param parent: The parent class
55 """
56
57 QtWidgets.QGraphicsScene.__init__(self, parent)
58 self.photo_editor = photo_editor
59 self.left_button_pressed = False
60 self.right_button_pressed = False
61
62 self.remember_rp = None
63
64 def mousePressEvent(self, event):
65 """
66 A mouse button is pressed.
67
68 :param event: event object
69 :return: -
70 """
71
72 # The following actions are not performed in drag-and-zoom mode. The switch between both
73 # modes is handled in the higher-level object "photo_viewer".
74 if not self.photo_editor.drag_mode and self.photo_editor.hasPhoto():
75
76 # If a rectangular patch had been drawn before, remove it from the scene.
77 if self.remember_rp:
78 self.removeItem(self.remember_rp)
79 self.remember_rp = None
80
81 pos = event.lastScenePos()
82 x = int(pos.x())
83 y = int(pos.y())
84
85 # The left button is pressed.
86 if event.button() == QtCore.Qt.LeftButton:
87 self.left_button_pressed = True
88
89 # Remember the location.
90 self.left_y_start = y
91 self.left_x_start = x
92
93
94 def mouseReleaseEvent(self, event):
95 """
96 A mouse button is released.
97
98 :param event: event object
99 :return: -
100 """
101
102 if not self.photo_editor.drag_mode and self.photo_editor.hasPhoto():
103
104 # The left button is released.
105 if event.button() == QtCore.Qt.LeftButton:
106 self.left_button_pressed = False
107
108 # If a rectangular patch has been defined, store its coordinates.
109 if self.remember_rp:
110 self.photo_editor.set_selection_rectangle(self.remember_rp.y_low,
111 self.remember_rp.y_high,
112 self.remember_rp.x_low,
113 self.remember_rp.x_high)
114 # If the rectangle is void, set all coordinates to zero.
115 else:
116 self.photo_editor.set_selection_rectangle(0, 0, 0, 0)
117
118
119
120 def mouseMoveEvent(self, event):
121 """
122 The mouse is moved while being pressed.
123
124 :param event: event object
125 :return: -
126 """
127
128 pos = event.lastScenePos()
129 x = int(pos.x())
130 y = int(pos.y())
131
132 if not self.photo_editor.drag_mode and self.photo_editor.hasPhoto():
133
134 # The mouse is moved with the left button pressed.
135 if self.left_button_pressed:
136
137 # Compute the new rectangular patch.
138 new_sp = SelectionRectangleGraphicsItem(self.left_y_start, self.left_x_start, y, x)
139
140 # If the rectangle was drawn for a previous location, replace it with the new one.
141 if self.remember_rp is not None:
142 self.removeItem(self.remember_rp)
143 self.addItem(new_sp)
144 self.remember_rp = new_sp
145
146 self.update()
147
148
149 class RectangularPatchEditor(FrameViewer):
150 """
151 This widget implements an editor for handling a rectangular patch superimposed onto an image.
152 It supports two modes:
153 - In "drag mode" the mouse can be used for panning, and the scroll wheel for zooming.
154 - In "alignment point mode" the mouse is used to create/remove APs, to move them or to change
155 their sizes.
156 The "cntrl" key is used to switch between the two modes.
157 """
158
159 def __init__(self, image):
160 super(RectangularPatchEditor, self).__init__()
161
162 self.image = image
163
164 # Initialize the rectangular patch.
165 self.y_low = None
166 self.y_high = None
167 self.x_low = None
168 self.x_high = None
169
170 self.setPhoto(self.image)
171
172 def initialize_scene(self):
173 """
174 Initialize the scene. This object handles mouse events if not in drag mode. In derived
175 viewer classes this method is replaced with the instantiation of a custom version of the
176 graphics scene.
177
178 :return:
179 """
180
181 self._scene = GraphicsScene(self, self)
182 self._scene.addItem(self._photo)
183 self.setScene(self._scene)
184
185 def set_selection_rectangle(self, y_low, y_high, x_low, x_high):
186 """
187 This method is invoked from the underlying scene object when the left mouse button is
188 released, and thus a rectangular patch is defined.
189
190 :param y_low: Lower y bound of patch
191 :param y_high: Upper y bound of patch
192 :param x_low: Lower x bound of patch
193 :param x_high: Upper x bound of patch
194 :return: -
195 """
196
197 self.y_low = max(0, y_low)
198 self.y_high = min(self.shape_y, y_high)
199 self.x_low = max(0, x_low)
200 self.x_high = min(self.shape_x, x_high)
201
202 def selection_rectangle(self):
203 """
204 Return the coordinate bounds of the selected rectangle.
205
206 :return: Tuple with 4 ints: (lower y bound, upper y bound, lower x bound, upper x bound)
207 """
208
209 if self.y_low is not None:
210 return (self.y_low, self.y_high, self.x_low, self.x_high)
211 else:
212 return (0, 0, 0, 0)
213
214
215 class RectangularPatchEditorWidget(QtWidgets.QFrame, Ui_rectangular_patch_editor):
216 """
217 This widget implements a rectangular patch editor, to be used for the selection of the
218 stabilization patch and the ROI rectangle.
219 """
220
221 def __init__(self, parent_gui, frame, message, signal_finished):
222 """
223 Initialization of the widget.
224
225 :param parent_gui: Parent GUI object
226 :param frame: Background image on which the patch is superimposed. Usually, the mean frame
227 is used for this purpose.
228 :param message: Message to tell the user what to do.
229 :param signal_finished: Qt signal with signature (int, int, int, int) sending the
230 coordinate bounds (y_low, y_high, x_low, x_high) of the patch
231 selected, or (0, 0, 0, 0) if unsuccessful.
232 """
233
234 super(RectangularPatchEditorWidget, self).__init__(parent_gui)
235 self.setupUi(self)
236
237 self.parent_gui = parent_gui
238
239 # Convert the frame into uint8 format. If the frame type is uint16, values
240 # correspond to 16bit resolution.
241 if frame.dtype == uint16 or frame.dtype == int32:
242 self.frame = (frame / 256).astype(uint8)
243 elif frame.dtype == uint8:
244 self.frame = frame
245 else:
246 raise NotSupportedError("Attempt to set a photo in frame viewer with type neither"
247 " uint8 nor uint16 not int32")
248
249 self.message = message
250 self.signal_finished = signal_finished
251
252 self.viewer = RectangularPatchEditor(self.frame)
253 self.verticalLayout.insertWidget(0, self.viewer)
254
255 self.messageLabel.setText(self.message)
256 self.messageLabel.setStyleSheet('color: red')
257 self.buttonBox.accepted.connect(self.done)
258 self.buttonBox.rejected.connect(self.reject)
259 self.shape_y = None
260 self.shape_x = None
261 self.y_low = None
262 self.y_high = None
263 self.x_low = None
264 self.x_high = None
265
266 def done(self):
267 """
268 On exit from the rectangular patch editor, look up the coordinate bounds of the rectangular
269 patch.
270
271 :return: -
272 """
273
274 if self.viewer.selection_rectangle() is not None:
275 self.y_low, self.y_high, self.x_low, self.x_high = self.viewer.selection_rectangle()
276
277 # If the patch was selected successfully, send the patch bounds to the workflow thread.
278 # If it was not successful, send (0, 0, 0, 0).
279 if self.parent_gui is not None:
280 if self.y_low is not None:
281 self.signal_finished.emit(self.y_low, self.y_high,
282 self.x_low, self.x_high)
283 # If the patch is not valid, do frame alignment in automatic mode. This is done if
284 # all bounds are zero.
285 else:
286 self.signal_finished.emit(0, 0, 0, 0)
287
288 # Close the Window.
289 self.close()
290
291 def reject(self):
292 """
293 If the "cancel" button is pressed, the coordinates are not stored.
294
295 :return: -
296 """
297
298 # No rectangle was selected. Continue the workflow in automatic mode.
299 self.signal_finished.emit(0, 0, 0, 0)
300 self.close()
301
302
303 if __name__ == '__main__':
304 # Images can either be extracted from a video file or a batch of single photographs. Select
305 # the example for the test run.
306 type = 'video'
307 if type == 'image':
308 names = glob('Images/2012*.tif')
309 # names = glob.glob('Images/Moon_Tile-031*ap85_8b.tif')
310 # names = glob.glob('Images/Example-3*.jpg')
311 else:
312 names = 'Videos/another_short_video.avi'
313 print(names)
314
315 # Get configuration parameters.
316 configuration = Configuration()
317 configuration.initialize_configuration()
318 try:
319 frames = Frames(configuration, names, type=type)
320 print("Number of images read: " + str(frames.number))
321 print("Image shape: " + str(frames.shape))
322 except Error as e:
323 print("Error: " + e.message)
324 exit()
325
326 # Rank the frames by their overall local contrast.
327 rank_frames = RankFrames(frames, configuration)
328 start = time()
329 rank_frames.frame_score()
330 end = time()
331 print('Elapsed time in ranking images: {}'.format(end - start))
332 print("Index of maximum: " + str(rank_frames.frame_ranks_max_index))
333 print("Frame scores: " + str(rank_frames.frame_ranks))
334 print("Frame scores (sorted): " + str(
335 [rank_frames.frame_ranks[i] for i in rank_frames.quality_sorted_indices]))
336 print("Sorted index list: " + str(rank_frames.quality_sorted_indices))
337
338 # Initialize the frame alignment object.
339 align_frames = AlignFrames(frames, rank_frames, configuration)
340
341 if configuration.align_frames_mode == "Surface":
342 start = time()
343 # Select the local rectangular patch in the image where the L gradient is highest in both x
344 # and y direction. The scale factor specifies how much smaller the patch is compared to the
345 # whole image frame.
346 (y_low_opt, y_high_opt, x_low_opt, x_high_opt) = align_frames.compute_alignment_rect(
347 configuration.align_frames_rectangle_scale_factor)
348 end = time()
349 print('Elapsed time in computing optimal alignment rectangle: {}'.format(end - start))
350 print("optimal alignment rectangle, x_low: " + str(x_low_opt) + ", x_high: " + str(
351 x_high_opt) + ", y_low: " + str(y_low_opt) + ", y_high: " + str(y_high_opt))
352 reference_frame_with_alignment_points = frames.frames_mono(
353 rank_frames.frame_ranks_max_index).copy()
354 reference_frame_with_alignment_points[y_low_opt,
355 x_low_opt:x_high_opt] = reference_frame_with_alignment_points[y_high_opt - 1,
356 x_low_opt:x_high_opt] = 255
357 reference_frame_with_alignment_points[y_low_opt:y_high_opt,
358 x_low_opt] = reference_frame_with_alignment_points[y_low_opt:y_high_opt,
359 x_high_opt - 1] = 255
360 # plt.imshow(reference_frame_with_alignment_points, cmap='Greys_r')
361 # plt.show()
362
363 # Align all frames globally relative to the frame with the highest score.
364 start = time()
365 try:
366 align_frames.align_frames()
367 except NotSupportedError as e:
368 print("Error: " + e.message)
369 exit()
370 except InternalError as e:
371 print("Warning: " + e.message)
372 for index, frame_number in enumerate(align_frames.failed_index_list):
373 print("Shift computation failed for frame " + str(
374 align_frames.failed_index_list[index]) + ", minima list: " + str(
375 align_frames.dev_r_list[index]))
376 end = time()
377 print('Elapsed time in aligning all frames: {}'.format(end - start))
378 print("Frame shifts: " + str(align_frames.frame_shifts))
379 print("Intersection: " + str(align_frames.intersection_shape))
380
381 start = time()
382 # Compute the reference frame by averaging the best frames.
383 average = align_frames.average_frame()
384 border = configuration.align_frames_search_width
385 # border = 100
386
387 app = QtWidgets.QApplication(argv)
388 window = RectangularPatchEditorWidget(None, average[border:-border, border:-border],
389 "With 'ctrl' and the left mouse button pressed, draw a rectangular patch "
390 "to be used for frame alignment. Or just press 'OK / Cancel' (automatic selection).",
391 None)
392 window.setMinimumSize(800, 600)
393 window.showMaximized()
394 app.exec_()
395
396 print("Rectangle selected, y_low: " + str(border+window.y_low) + ", y_high: " +
397 str(border+window.y_high) + ", x_low: " + str(border+window.x_low) + ", x_high: "
398 + str(border+window.x_high))
399
400 exit()
401