Debian Codegraph @

planetary_system_stacker/align_frames.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 """
22
23 from glob import glob
24 from itertools import chain
25 from time import time
26
27 import matplotlib
28 matplotlib.use('Agg')
29 import matplotlib.pyplot as plt
30 from math import ceil
31 from numpy import float32, zeros, empty, int32, uint8, uint16, clip, histogram
32 from cv2 import imwrite, moments, threshold, THRESH_BINARY, Laplacian, CV_32F, minMaxLoc
33
34 from configuration import Configuration
35 from exceptions import WrongOrderingError, NotSupportedError, InternalError, ArgumentError, Error
36 from frames import Frames
37 from miscellaneous import Miscellaneous
38 from rank_frames import RankFrames
39
40
41 class AlignFrames(object):
42 """
43 Based on a list of frames and a (parallel) list of frame quality values, an averaged
44 reference frame is created and all frames are aligned with this frame. The alignment is
45 performed on a small rectangular area where structure is optimal in both x and y directions.
46
47 """
48
49 def __init__(self, frames, rank_frames, configuration, progress_signal=None):
50 """
51 Initialize the AlignFrames object with info from the objects "frames" and "rank_frames".
52
53 :param frames: Frames object with all video frames
54 :param rank_frames: RankFrames object with global quality ranks (between 0. and 1.,
55 1. being optimal) for all frames
56 :param configuration: Configuration object with parameters
57 :param progress_signal: Either None (no progress signalling), or a signal with the signature
58 (str, int) with the current activity (str) and the progress in
59 percent (int).
60 """
61
62 self.frames = frames
63 self.rank_frames = rank_frames
64 self.shape = frames.shape
65 self.alignment_rect_qualities = None
66 self.alignment_rect_bounds = None
67 self.frame_shifts = None
68 self.intersection_shape = None
69 self.intersection_shape_original = None
70 self.mean_frame = None
71 self.mean_frame_original = None
72 self.quality_loss_percent = None
73 self.cog_mean_frame = None
74 self.configuration = configuration
75 self.progress_signal = progress_signal
76 self.signal_step_size = max(int(self.frames.number / 10), 1)
77 self.x_low_opt = self.x_high_opt = self.y_low_opt = self.y_high_opt = None
78 self.dy = self.dx = None
79 self.y_low_opt = self.y_high_opt = self.x_low_opt = self.x_high_opt = None
80 self.dy_original = self.dx_original = None
81 self.ROI_set = False
82 self.dev_table = empty((2 * self.configuration.align_frames_search_width,
83 2 * self.configuration.align_frames_search_width), dtype=float32)
84
85 def compute_alignment_rect(self, scale_factor):
86 """
87 Using the frame with the highest rank (sharpest image), compute the rectangular patch
88 where structure is best in both x and y directions. The size of the patch is the size of the
89 frame divided by "scale_factor" in both coordinate directions.
90
91 :param scale_factor: Ratio of the size of the frame and the alignment patch in both
92 coordinate directions
93 :return: A four tuple (y_low, y_high, x_low, x_high) with pixel coordinates of the
94 optimal patch
95 """
96
97 dim_y, dim_x = self.shape[0:2]
98
99 # Compute the extensions of the alignment rectangle in y and x directions. Take into account
100 # a border and the search radius for frame shifts.
101 border_width = self.configuration.align_frames_border_width + \
102 self.configuration.align_frames_search_width
103 rect_y = int((dim_y - 2 * border_width) / scale_factor)
104 rect_y_2 = int(rect_y / 2)
105 rect_x = int((dim_x - 2 * border_width) / scale_factor)
106 rect_x_2 = int(rect_x / 2)
107
108 # Initialize lists which for each location store the quality measure and the index bounds.
109 self.alignment_rect_qualities = []
110 self.alignment_rect_bounds = []
111
112 # Compute for all locations in the frame the "quality measure" and store the location
113 # and quality measure in above lists.
114 best_frame_mono_blurred = self.frames.frames_mono_blurred(self.rank_frames.frame_ranks_max_index)
115 x_low = border_width
116 x_high = x_low + rect_x
117 while x_high <= dim_x - border_width:
118 y_low = border_width
119 y_high = y_low + rect_y
120 while y_high <= dim_y - border_width:
121 # new_quality = Miscellaneous.local_contrast(
122 # self.frames_mono_blurred[self.frame_ranks_max_index][y_low:y_high,
123 # x_low:x_high], self.configuration.quality_area_pixel_stride)
124 self.alignment_rect_qualities.append(
125 Miscellaneous.quality_measure_threshold_weighted(
126 best_frame_mono_blurred[y_low:y_high, x_low:x_high],
127 stride=self.configuration.align_frames_rectangle_stride,
128 black_threshold=self.configuration.align_frames_rectangle_black_threshold,
129 min_fraction=self.configuration.align_frames_rectangle_min_fraction))
130 self.alignment_rect_bounds.append((y_low, y_high, x_low, x_high))
131
132 y_low += rect_y_2
133 y_high += rect_y_2
134 x_low += rect_x_2
135 x_high += rect_x_2
136
137 try:
138 # Sort lists by quality.
139 arq, arb = zip(*sorted(zip(self.alignment_rect_qualities, self.alignment_rect_bounds),
140 reverse=True))
141 self.alignment_rect_qualities = list(arq)
142 self.alignment_rect_bounds = list(arb)
143
144 # Set the optimal coordinates and return them as a tuple.
145 (self.y_low_opt, self.y_high_opt, self.x_low_opt, self.x_high_opt) = \
146 self.alignment_rect_bounds[0]
147 return self.alignment_rect_bounds[0]
148 except:
149 raise ArgumentError("The frame is too small for alignment parameters chosen")
150
151 def select_alignment_rect(self, index):
152 """
153 Select an alignment patch from the list computed in "compute_aligment_rect" to be used
154 for frame aligment.
155
156 :param index: index of the alignment patch in the list in decreasing quality order.
157 :return: True, if successful. Otherwise return False.
158 """
159
160 if index < 0 or index > len(self.alignment_rect_bounds):
161 return False
162 else:
163 self.y_low_opt, self.y_high_opt, self.x_low_opt, self.x_high_opt = \
164 self.alignment_rect_bounds[index]
165 return True
166
167 def set_alignment_rect(self, y_low_opt, y_high_opt, x_low_opt, x_high_opt):
168 """
169 As an alternative to "select_alignment_rect", the rectangular patch can be set explicitly
170
171 :param y_low_opt: Lower y pixel coordinate of patch
172 :param y_high_opt: Upper y pixel coordinate of patch
173 :param x_low_opt: Lower x pixel coordinate of patch
174 :param x_high_opt: Upper x pixel coordinate of patch
175 :return: -
176 """
177
178 self.y_low_opt = y_low_opt
179 self.y_high_opt = y_high_opt
180 self.x_low_opt = x_low_opt
181 self.x_high_opt = x_high_opt
182
183 # If the user has set the patch manually, set the lists to this single element.
184 self.alignment_rect_qualities = [1.]
185 self.alignment_rect_bounds = [(self.y_low_opt, self.y_high_opt, self.x_low_opt,
186 self.x_high_opt)]
187
188 def align_frames(self):
189 """
190 Compute the displacement of all frames relative to the sharpest frame using the alignment
191 rectangle.
192
193 :return: -
194 """
195
196 if self.configuration.align_frames_mode == "Surface":
197 # For "Surface" mode the alignment rectangle has to be selected first.
198 if self.x_low_opt is None:
199 raise WrongOrderingError(
200 "Method 'align_frames' is called before 'select_alignment_rect'")
201
202 # From the sharpest frame cut out the alignment rectangle. The shifts of all other frames
203 # will be computed relativ to this patch.
204 if self.configuration.align_frames_method == "MultiLevelCorrelation":
205 # MultiLevelCorrelation uses two reference windows with different resolution. Also,
206 # please note that the data type is float32 in this case.
207 reference_frame = self.frames.frames_mono_blurred(
208 self.rank_frames.frame_ranks_max_index).astype(float32)
209 self.reference_window = reference_frame[self.y_low_opt:self.y_high_opt,
210 self.x_low_opt:self.x_high_opt]
211 # For the first phase a box with half the resolution is constructed.
212 self.reference_window_first_phase = self.reference_window[::2, ::2]
213 else:
214 # For all other methods, the reference window is of type int32.
215 reference_frame = self.frames.frames_mono_blurred(
216 self.rank_frames.frame_ranks_max_index).astype(int32)
217 self.reference_window = reference_frame[
218 self.y_low_opt:self.y_high_opt,
219 self.x_low_opt:self.x_high_opt]
220
221 self.reference_window_shape = self.reference_window.shape
222
223 elif self.configuration.align_frames_mode == "Planet":
224 # For "Planetary" mode compute the center of gravity for the reference image.
225 cog_reference_y, cog_reference_x = AlignFrames.center_of_gravity(
226 self.frames.frames_mono_blurred(self.rank_frames.frame_ranks_max_index))
227
228 else:
229 raise NotSupportedError(
230 "Frame alignment mode '" + self.configuration.align_frames_mode +
231 "' not supported")
232
233 # Initialize a list which for each frame contains the shifts in y and x directions.
234 self.frame_shifts = [None] * self.frames.number
235
236 # Initialize a counter of processed frames for progress bar signalling. It is set to one
237 # because in the loop below the optimal frame is not counted.
238 number_processed = 1
239
240 # Loop over all frames. Begin with the sharpest (reference) frame
241 for idx in chain(reversed(range(self.rank_frames.frame_ranks_max_index + 1)),
242 range(self.rank_frames.frame_ranks_max_index, self.frames.number)):
243
244 if idx == self.rank_frames.frame_ranks_max_index:
245 # For the sharpest frame the displacement is 0 because it is used as the reference.
246 self.frame_shifts[idx] = [0, 0]
247 # Initialize two variables which keep the shift values of the previous step as
248 # the starting point for the next step. This reduces the search radius if frames are
249 # drifting.
250 dy_min_cum = dx_min_cum = 0
251
252 # For all other frames: Compute the global shift, using the "blurred" monochrome image.
253 else:
254 # After every "signal_step_size"th frame, send a progress signal to the main GUI.
255 if self.progress_signal is not None and number_processed % self.signal_step_size == 1:
256 self.progress_signal.emit("Align all frames",
257 int(round(10*number_processed / self.frames.number) * 10))
258
259 frame = self.frames.frames_mono_blurred(idx)
260
261 # In Planetary mode the shift of the "center of gravity" of the image is computed.
262 # This algorithm cannot fail.
263 if self.configuration.align_frames_mode == "Planet":
264
265 cog_frame = AlignFrames.center_of_gravity(frame)
266 self.frame_shifts[idx] = [cog_reference_y - cog_frame[0],
267 cog_reference_x - cog_frame[1]]
268
269 # In Surface mode various methods can be used to measure the shift from one frame
270 # to the next. The method "Translation" is special: Using phase correlation it is
271 # the only method not based on a local search algorithm. It is treated differently
272 # here because it does not require a re-shifting of the alignment patch.
273 elif self.configuration.align_frames_method == "Translation":
274 # The shift is computed with cross-correlation. Cut out the alignment patch and
275 # compute its translation relative to the reference.
276 frame_window = self.frames.frames_mono_blurred(idx)[
277 self.y_low_opt:self.y_high_opt, self.x_low_opt:self.x_high_opt]
278 self.frame_shifts[idx] = Miscellaneous.translation(self.reference_window,
279 frame_window,
280 self.reference_window_shape)
281
282 # Now treat all "Surface" mode cases using local search algorithms. In each case
283 # the result is the shift vector [dy_min, dx_min]. The search can fail (if within
284 # the search radius no optimum is found). If that happens for at least one frame,
285 # an exception is raised. The workflow thread then tries again using another
286 # alignment patch.
287 else:
288
289 if self.configuration.align_frames_method == "MultiLevelCorrelation":
290 # The shift is computed in two phases: First on a coarse pixel grid,
291 # and then on the original grid in a small neighborhood around the optimum
292 # found in the first phase.
293 shift_y_local_first_phase, shift_x_local_first_phase, \
294 success_first_phase, shift_y_local_second_phase, \
295 shift_x_local_second_phase, success_second_phase = \
296 Miscellaneous.multilevel_correlation(
297 self.reference_window_first_phase, frame,
298 self.configuration.frames_gauss_width,
299 self.reference_window, self.y_low_opt - dy_min_cum,
300 self.y_high_opt - dy_min_cum,
301 self.x_low_opt - dx_min_cum,
302 self.x_high_opt - dx_min_cum,
303 self.configuration.align_frames_search_width,
304 weight_matrix_first_phase=None)
305
306 success = success_first_phase and success_second_phase
307 if success:
308 [dy_min, dx_min] = [
309 shift_y_local_first_phase + shift_y_local_second_phase,
310 shift_x_local_first_phase + shift_x_local_second_phase]
311
312
313 elif self.configuration.align_frames_method == "RadialSearch":
314 # Spiral out from the shift position of the previous frame and search for the
315 # local optimum.
316 [dy_min, dx_min], dev_r = Miscellaneous.search_local_match(
317 self.reference_window, frame, self.y_low_opt - dy_min_cum,
318 self.y_high_opt - dy_min_cum,
319 self.x_low_opt - dx_min_cum,
320 self.x_high_opt - dx_min_cum,
321 self.configuration.align_frames_search_width,
322 self.configuration.align_frames_sampling_stride, sub_pixel=False)
323
324 # The search was not successful if a zero shift was reported after more
325 # than two search cycles.
326 success = len(dev_r) <= 2 or dy_min != 0 or dx_min != 0
327
328 elif self.configuration.align_frames_method == "SteepestDescent":
329 # Spiral out from the shift position of the previous frame and search for the
330 # local optimum.
331 [dy_min, dx_min], dev_r = Miscellaneous.search_local_match_gradient(
332 self.reference_window, frame, self.y_low_opt - dy_min_cum,
333 self.y_high_opt - dy_min_cum,
334 self.x_low_opt - dx_min_cum,
335 self.x_high_opt - dx_min_cum,
336 self.configuration.align_frames_search_width,
337 self.configuration.align_frames_sampling_stride, self.dev_table)
338
339 # The search was not successful if a zero shift was reported after more
340 # than two search cycles.
341 success = len(dev_r) <= 2 or dy_min != 0 or dx_min != 0
342
343 else:
344 raise NotSupportedError(
345 "Frame alignment method " + configuration.align_frames_method +
346 " not supported")
347
348 # If the local search was unsuccessful, quit the frame loop with an error.
349 if not success:
350 raise InternalError("frame " + str(idx))
351
352 # Update the cumulative shift values to be used as starting point for the
353 # next frame.
354 dy_min_cum += dy_min
355 dx_min_cum += dx_min
356 self.frame_shifts[idx] = [dy_min_cum, dx_min_cum]
357
358 # If the alignment window gets too close to a frame edge, move it away from
359 # that edge by half the border width. First check if the reference window still
360 # fits into the shifted frame.
361 if self.shape[0] - abs(
362 dy_min_cum) - 2 * self.configuration.align_frames_search_width - \
363 self.configuration.align_frames_border_width < \
364 self.reference_window_shape[0] or self.shape[1] - abs(
365 dx_min_cum) - 2 * self.configuration.align_frames_search_width - \
366 self.configuration.align_frames_border_width < \
367 self.reference_window_shape[1]:
368 raise ArgumentError("Frame stabilization window does not fit into"
369 " intersection")
370
371 new_reference_window = False
372 # Start with the lower y edge.
373 while self.y_low_opt - dy_min_cum < \
374 self.configuration.align_frames_search_width + \
375 self.configuration.align_frames_border_width / 2:
376 self.y_low_opt += ceil(self.configuration.align_frames_border_width / 2.)
377 self.y_high_opt += ceil(self.configuration.align_frames_border_width / 2.)
378 new_reference_window = True
379 # Now the upper y edge.
380 while self.y_high_opt - dy_min_cum > self.shape[
381 0] - self.configuration.align_frames_search_width - \
382 self.configuration.align_frames_border_width / 2:
383 self.y_low_opt -= ceil(self.configuration.align_frames_border_width / 2.)
384 self.y_high_opt -= ceil(self.configuration.align_frames_border_width / 2.)
385 new_reference_window = True
386 # Now the lower x edge.
387 while self.x_low_opt - dx_min_cum < \
388 self.configuration.align_frames_search_width + \
389 self.configuration.align_frames_border_width / 2:
390 self.x_low_opt += ceil(self.configuration.align_frames_border_width / 2.)
391 self.x_high_opt += ceil(self.configuration.align_frames_border_width / 2.)
392 new_reference_window = True
393 # Now the upper x edge.
394 while self.x_high_opt - dx_min_cum > self.shape[
395 1] - self.configuration.align_frames_search_width - \
396 self.configuration.align_frames_border_width / 2:
397 self.x_low_opt -= ceil(self.configuration.align_frames_border_width / 2.)
398 self.x_high_opt -= ceil(self.configuration.align_frames_border_width / 2.)
399 new_reference_window = True
400
401 # If the window was moved, update the "reference window(s)".
402 if new_reference_window:
403 if self.configuration.align_frames_method == "MultiLevelCorrelation":
404 self.reference_window = reference_frame[self.y_low_opt:self.y_high_opt,
405 self.x_low_opt:self.x_high_opt]
406 # For the first phase a box with half the resolution is constructed.
407 self.reference_window_first_phase = self.reference_window[::2, ::2]
408 else:
409 self.reference_window = reference_frame[self.y_low_opt:self.y_high_opt,
410 self.x_low_opt:self.x_high_opt]
411
412 # This frame is processed, go to next one.
413 number_processed += 1
414
415 if self.progress_signal is not None:
416 self.progress_signal.emit("Align all frames", 100)
417
418 # Compute the shape of the area contained in all frames in the form [[y_low, y_high],
419 # [x_low, x_high]]
420 self.intersection_shape = [[max(b[0] for b in self.frame_shifts),
421 min(b[0] for b in self.frame_shifts) + self.shape[0]],
422 [max(b[1] for b in self.frame_shifts),
423 min(b[1] for b in self.frame_shifts) + self.shape[1]]]
424
425 @staticmethod
426 def center_of_gravity(frame):
427 """
428 Comppute (y, x) pixel coordinates of the center of gravity for a given monochrome frame.
429 Raise an error if the computed cog is outside the frame index bounds.
430
431 :param frame: Monochrome frame (2D numpy array)
432 :return: Integer pixel coordinates (center_y, center_x) of center of gravity
433 """
434
435 # The following is the old algorithm (up to Version 0.8.5). It does not work well for
436 # planets on a bright sky background.
437 #
438 # Convert the grayscale image to binary image, where all pixels
439 # brighter than half the maximum image brightness are set to 1,
440 # and all others are set to 0.
441 # thresh = threshold(frame, frame.max()/2, 1, THRESH_BINARY)[1]
442
443 # This new code sets the threshold between the minimal brightness (background) and
444 # the maximal brightness (object). The hope is that this way the threshold is far away from
445 # background noise. Also, no binary image is created, but brightness variations are allowed
446 # to influence the center of gravity. This gives brighter parts of the image more weight,
447 # which results in a slightly better precision.
448 minVal, maxVal, minLoc, maxLoc = minMaxLoc(frame)
449 brightness_threshold = int((minVal+maxVal)/2)
450 thresh = clip(frame, brightness_threshold, None)[:,:]-brightness_threshold
451
452 # Calculate moments of binary image
453 M = moments(thresh)
454
455 # Calculate coordinates for center of gravity and round pixel
456 # coordinates to the nearest integers.
457 cog_x = round(M["m10"] / M["m00"])
458 cog_y = round(M["m01"] / M["m00"])
459
460 # If the computed center of gravity is outside the frame bounds, raise an error (should be
461 # impossible).
462 if not 0 < cog_y < frame.shape[0] or not 0 < cog_x < frame.shape[1]:
463 raise InternalError(
464 "Center of gravity coordinates [" + str(cog_y) + ", " + str(
465 cog_x) + "] of reference frame are out of bounds")
466
467 return cog_y, cog_x
468
469 def average_frame(self, average_frame_number=None, color=False):
470 """
471 Compute an averaged frame from the best (monochrome) frames.
472
473 :param average_frame_number: Number of best frames to be averaged. If None, the number is
474 computed from the configuration parameter
475 "align_frames_average_frame_percent"
476 :param color: If True, compute an average of the original (color) images. Otherwise use the
477 monochrome frame versions.
478 :return: The averaged frame
479 """
480
481 if self.intersection_shape is None:
482 raise WrongOrderingError("Method 'average_frames' is called before 'align_frames'")
483
484 # Compute global offsets of current frame relative to intersection frame. Start with
485 # Initializing lists which for each frame give the dy and dx displacements between the
486 # reference frame and current frame.
487 self.dy = [self.intersection_shape[0][0] - self.frame_shifts[idx][0] for idx in range(self.frames.number)]
488 self.dx = [self.intersection_shape[1][0] - self.frame_shifts[idx][1] for idx in range(self.frames.number)]
489
490 # If the number of frames is not specified explicitly, compute it from configuration.
491 if average_frame_number is not None:
492 self.average_frame_number = average_frame_number
493 else:
494 self.average_frame_number = max(
495 ceil(self.frames.number * self.configuration.align_frames_average_frame_percent / 100.), 1)
496
497 # If the object is changing fast (Jupiter, Sun), restrict interval from which frames are
498 # taken for computing the reference frame.
499 if self.configuration.align_frames_fast_changing_object:
500 window_size = min(
501 self.average_frame_number *
502 self.configuration.align_frames_best_frames_window_extension,
503 self.frames.number)
504 average_frame_indices, self.quality_loss_percent, self.cog_mean_frame = \
505 self.rank_frames.find_best_frames(self.average_frame_number, window_size)
506 else:
507 average_frame_indices = self.rank_frames.quality_sorted_indices[:self.average_frame_number]
508
509 # Create an empty numpy buffer. The first and second dimensions are the y and x
510 # coordinates. For color frames add a third dimension. Add all frames to the buffer.
511 if color:
512 self.mean_frame = zeros([self.intersection_shape[0][1] - self.intersection_shape[0][0],
513 self.intersection_shape[1][1] - self.intersection_shape[1][0], 3], dtype=float32)
514 for frame_index in average_frame_indices:
515 shift = self.frame_shifts[frame_index]
516 self.mean_frame += self.frames.frames(frame_index) \
517 [self.intersection_shape[0][0] - shift[0]:
518 self.intersection_shape[0][1] - shift[0],
519 self.intersection_shape[1][0] - shift[1]:
520 self.intersection_shape[1][1] - shift[1], :]
521 else:
522 self.mean_frame = zeros([self.intersection_shape[0][1] - self.intersection_shape[0][0],
523 self.intersection_shape[1][1] - self.intersection_shape[1][0]],
524 dtype=float32)
525 for frame_index in average_frame_indices:
526 shift = self.frame_shifts[frame_index]
527 self.mean_frame += self.frames.frames_mono(frame_index) \
528 [self.intersection_shape[0][0] - shift[0]:
529 self.intersection_shape[0][1] - shift[0],
530 self.intersection_shape[1][0] - shift[1]:
531 self.intersection_shape[1][1] - shift[1]]
532
533 # Compute the mean frame by dividing by the number of frames, and convert values to 16bit.
534 if self.frames.dt0 == uint8:
535 scaling = 256. / self.average_frame_number
536 elif self.frames.dt0 == uint16:
537 scaling = 1. / self.average_frame_number
538 else:
539 raise NotSupportedError("Attempt to compute the reference frame from images with type"
540 " neither uint8 nor uint16")
541
542 self.mean_frame = (self.mean_frame*scaling).astype(int32)
543
544 return self.mean_frame
545
546 def set_roi(self, y_min, y_max, x_min, x_max):
547 """
548 Make the stacking region snmaller than the intersection size. Be careful: The pixel
549 indices in this method refer to the shape of the intersection of all frames, i.e., the
550 shape of the full mean frame. In general, the original frames are somewhat larger.
551
552 If all four index bounds are zero, set the ROI to the full frame.
553
554 :param y_min: Lower y pixel bound
555 :param y_max: Upper y pixel bound
556 :param x_min: Lower x pixel bound
557 :param x_max: Upper x pixel bound
558 :return: The new averaged frame, restricted to the ROI
559 """
560
561 if self.intersection_shape is None:
562 raise WrongOrderingError("Method 'set_roi' is called before 'align_frames'")
563
564 # On the first call, keep a copy of the full mean frame and original intersection shape.
565 if not self.ROI_set:
566 self.mean_frame_original = self.mean_frame.copy()
567 self.intersection_shape_original = self.intersection_shape.copy()
568
569 if y_min == 0 and y_max == 0 and x_min == 0 and x_max == 0:
570 y_min = 0
571 y_max = self.intersection_shape_original[0][1] - \
572 self.intersection_shape_original[0][0]
573 x_min = 0
574 x_max = self.intersection_shape_original[1][1] - \
575 self.intersection_shape_original[1][0]
576 elif y_min < 0 or y_max > self.intersection_shape_original[0][1] - \
577 self.intersection_shape_original[0][0] or \
578 x_min < 0 or x_max > self.intersection_shape_original[1][1] - \
579 self.intersection_shape_original[1][0] or \
580 y_min >= y_max or x_min >= x_max:
581 raise ArgumentError("Invalid ROI index bounds specified")
582
583 # Reduce the intersection shape and mean frame to the ROI.
584 self.intersection_shape = [[y_min+self.intersection_shape_original[0][0],
585 y_max+self.intersection_shape_original[0][0]],
586 [x_min+self.intersection_shape_original[1][0],
587 x_max+self.intersection_shape_original[1][0]]]
588
589 # Re-compute global offsets of current frame relative to reference frame.
590 self.dy = [self.intersection_shape[0][0] - self.frame_shifts[idx][0] for idx in range(self.frames.number)]
591 self.dx = [self.intersection_shape[1][0] - self.frame_shifts[idx][1] for idx in range(self.frames.number)]
592
593 self.ROI_set = True
594
595 self.mean_frame = self.mean_frame_original[y_min:y_max, x_min:x_max]
596
597 return self.mean_frame
598
599 def reset_roi(self):
600 """
601 After a ROI has been set, reset the ROI to the full frame. Restore the mean frame and
602 the intersection shape to their original values. If no ROI has been set, do nothing.
603
604 :return: -
605 """
606
607 if self.ROI_set:
608 self.mean_frame = self.mean_frame_original
609 self.intersection_shape = self.intersection_shape_original
610
611 def write_stabilized_video(self, name, fps, stabilized=True):
612 """
613 Write out a stabilized videos. For all frames the part common to all frames is extracted
614 and written into a video file.
615
616 :param name: File name of the video output
617 :param fps: Frames per second of video
618 :param stabilized: if False, switch off image stabilization. Write original frames.
619 :return: -
620 """
621
622 # Initialize lists of stabilized frames and index strings.
623 frames_mono_stabilized = []
624 frame_indices = []
625
626 if stabilized:
627 # For each frame: cut out the shifted window with the intersection of all frames.
628 # Append it to the list, and add its index to the list of index strings.
629 for idx in range(self.frames.number):
630 frame_mono = self.frames.frames_mono(idx)
631 frames_mono_stabilized.append(frame_mono[
632 self.intersection_shape[0][0] -
633 self.frame_shifts[idx][0]:
634 self.intersection_shape[0][1] -
635 self.frame_shifts[idx][0],
636 self.intersection_shape[1][0] -
637 self.frame_shifts[idx][1]:
638 self.intersection_shape[1][1] -
639 self.frame_shifts[idx][1]])
640 frame_indices.append(str(idx))
641 Miscellaneous.write_video(name, frames_mono_stabilized, frame_indices, 5)
642 else:
643 # Write the original frames (not stabilized) with index number insertions.
644 frames_mono = []
645 for idx in range(self.frames.number):
646 frame_indices.append(str(idx))
647 frames_mono.append(self.frames.frames_mono(idx))
648 Miscellaneous.write_video(name, frames_mono, frame_indices, 5)
649
650
651 if __name__ == "__main__":
652 # Images can either be extracted from a video file or a batch of single photographs. Select
653 # the example for the test run.
654 type = 'video'
655 if type == 'image':
656 names = glob(
657 'Images/2012*.tif')
658 # names = glob.glob('Images/Moon_Tile-031*ap85_8b.tif')
659 # names = glob.glob('Images/Example-3*.jpg')
660 else:
661 # file = 'Moon_Tile-013_205538_short'
662 # file = 'another_short_video'
663 # file = 'Moon_Tile-024_043939'
664 # file = 'Moon_Tile-013_205538'
665 file = "Venus_06_01"
666 names = 'Videos/' + file + '.avi'
667 print(names)
668
669 # Get configuration parameters.
670 configuration = Configuration()
671 configuration.initialize_configuration()
672 try:
673 # In creating the Frames object the images are read from the specified file(s).
674 frames = Frames(configuration, names, type=type)
675 print("Number of images read: " + str(frames.number))
676 print("Image shape: " + str(frames.shape))
677 except Error as e:
678 print("Error: " + str(e))
679 exit()
680
681 # Rank the frames by their overall local contrast.
682 rank_frames = RankFrames(frames, configuration)
683 rank_frames.frame_score()
684
685 print("Best frame index: " + str(rank_frames.frame_ranks_max_index))
686 output_file = 'Images/' + file + '.jpg'
687 imwrite(output_file, frames.frames_mono(rank_frames.frame_ranks_max_index))
688
689 # Initialize the frame alignment object.
690 align_frames = AlignFrames(frames, rank_frames, configuration)
691
692 if configuration.align_frames_mode == "Surface":
693 # Select the local rectangular patch in the image where the L gradient is highest in both x
694 # and y direction. The scale factor specifies how much smaller the patch is compared to the
695 # whole image frame.
696 (y_low_opt, y_high_opt, x_low_opt, x_high_opt) = align_frames.compute_alignment_rect(
697 configuration.align_frames_rectangle_scale_factor)
698
699 # Alternative: Set the alignment rectangle by hand.
700 # (align_frames.x_low_opt, align_frames.x_high_opt, align_frames.y_low_opt,
701 # align_frames.y_high_opt) = (x_low_opt, x_high_opt, y_low_opt, y_high_opt) = (
702 # 650, 950, 550, 750)
703
704 print("optimal alignment rectangle, x_low: " + str(x_low_opt) + ", x_high: " + str(
705 x_high_opt) + ", y_low: " + str(y_low_opt) + ", y_high: " + str(y_high_opt))
706 frame = frames.frames_mono_blurred(rank_frames.frame_ranks_max_index).copy()
707 frame[y_low_opt, x_low_opt:x_high_opt] = frame[y_high_opt - 1, x_low_opt:x_high_opt] = 255
708 frame[y_low_opt:y_high_opt, x_low_opt] = frame[y_low_opt:y_high_opt, x_high_opt - 1] = 255
709 plt.imshow(frame, cmap='Greys_r')
710 plt.show()
711
712 # Align all frames globally relative to the frame with the highest score.
713 try:
714 align_frames.align_frames()
715 except NotSupportedError as e:
716 print("Error: " + e.message)
717 exit()
718 except InternalError as e:
719 print("Warning: " + e.message)
720
721 print("Frame shifts: " + str(align_frames.frame_shifts))
722 print("Intersection: " + str(align_frames.intersection_shape))
723
724 # Compute the reference frame by averaging the best frames.
725 average = align_frames.average_frame()
726 plt.imshow(average, cmap='Greys_r')
727 plt.show()
728
729 # Write video with stabilized frames, annotated with their frame indices.
730 stabilized = True
731 if stabilized:
732 name = 'Videos/stabilized_video_with_frame_numbers.avi'
733 else:
734 name = 'Videos/not_stabilized_video_with_frame_numbers.avi'
735 align_frames.write_stabilized_video(name, 5, stabilized=stabilized)
736
737 # print ("Setting ROI and computing new average frame")
738 # average = align_frames.set_roi(300, 600, 500, 1000)
739 # plt.imshow(average, cmap='Greys_r')
740 # plt.show()
741