Debian Codegraph @

planetary_system_stacker/stack_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 math import ceil
25 from statistics import median
26 from time import sleep
27 from warnings import filterwarnings
28
29 import matplotlib
30 matplotlib.use('Agg')
31 import matplotlib.pyplot as plt
32 from cv2 import FONT_HERSHEY_SIMPLEX, putText, resize, INTER_CUBIC, INTER_LINEAR
33 from numpy import zeros, full, empty, float32, newaxis, arange, count_nonzero, \
34 sqrt, uint16, clip, minimum, mean
35 from skimage import img_as_uint, img_as_ubyte
36
37 from align_frames import AlignFrames
38 from alignment_points import AlignmentPoints
39 from configuration import Configuration
40 from exceptions import InternalError, NotSupportedError, Error
41 from frames import Frames
42 from miscellaneous import Miscellaneous
43 from rank_frames import RankFrames
44 from timer import timer
45
46
47 class StackFrames(object):
48 """
49 For every frame de-warp the quality areas selected for stacking. Then stack all the
50 de-warped frame sections into a single image.
51
52 """
53
54 def __init__(self, configuration, frames, rank_frames, align_frames, alignment_points, my_timer,
55 progress_signal=None, debug=False, create_image_window_signal=None,
56 update_image_window_signal=None, terminate_image_window_signal=None):
57 """
58 Initialze the StackFrames object. In particular, allocate empty numpy arrays used in the
59 stacking process for buffering and the final stacked image. The size of all those objects
60 in y and x directions is equal to the intersection of all frames.
61
62 :param configuration: Configuration object with parameters
63 :param frames: Frames object with all video frames
64 :param rank_frames: RankFrames object with global quality ranks (between 0. and 1.,
65 1. being optimal) for all frames
66 :param align_frames: AlignFrames object with global shift information for all frames
67 :param alignment_points: AlignmentPoints object with information of all alignment points
68 :param my_timer: Timer object for accumulating times spent in specific code sections
69 :param progress_signal: Either None (no progress signalling), or a signal with the signature
70 (str, int) with the current activity (str) and the progress in
71 percent (int).
72 """
73
74 # Suppress warnings about precision loss in skimage file format conversions.
75 filterwarnings("ignore", category=UserWarning)
76
77 self.configuration = configuration
78 self.frames = frames
79 self.rank_frames = rank_frames
80 self.align_frames = align_frames
81 self.alignment_points = alignment_points
82 self.my_timer = my_timer
83 self.progress_signal = progress_signal
84 self.signal_step_size = max(int(self.frames.number / 10), 1)
85 self.shift_distribution = None
86
87 # Set a flag which indicates if drizzling is active.
88 self.drizzle = self.configuration.drizzle_factor != 1
89
90 for name in ['Stacking: AP initialization', 'Stacking: initialize background blending',
91 'Stacking: compute AP shifts', 'Stacking: remapping and adding',
92 'Stacking: computing background', 'Stacking: merging AP buffers']:
93 self.my_timer.create_no_check(name)
94
95 self.my_timer.start('Stacking: AP initialization')
96 # Allocate work space for image buffer and the image converted for output.
97 # [dim_y_drizzled, dim_x_drizzled] is the size of the intersection of all frames in drizzled
98 # coordinates.
99 self.dim_y = (self.align_frames.intersection_shape[0][1] -
100 self.align_frames.intersection_shape[0][0])
101 self.dim_y_drizzled = self.dim_y * self.configuration.drizzle_factor
102 self.dim_x = (self.align_frames.intersection_shape[1][1] -
103 self.align_frames.intersection_shape[1][0])
104 self.dim_x_drizzled = self.dim_x * self.configuration.drizzle_factor
105 self.number_pixels = self.dim_y * self.dim_x
106 self.number_pixels_drizzled = self.dim_y_drizzled * self.dim_x_drizzled
107
108 # Allocate AP stacking buffers and compute drizzled patch index bounds.
109 for ap in self.alignment_points.alignment_points:
110 AlignmentPoints.initialize_ap_stacking_buffer(ap, self.configuration.drizzle_factor,
111 self.frames.color)
112
113 # The summation buffer needs to accommodate three color channels in the case of color
114 # images. The size is extended if drizzling is active. In this case also allocate a buffer
115 # where the interpolated frames are stored.
116 if self.frames.color:
117 self.stacked_image_buffer = zeros([self.dim_y_drizzled, self.dim_x_drizzled, 3],
118 dtype=float32)
119 if self.drizzle:
120 self.frame_drizzled = zeros([self.dim_y_drizzled, self.dim_x_drizzled, 3],
121 dtype=float32)
122 else:
123 self.stacked_image_buffer = zeros([self.dim_y_drizzled, self.dim_x_drizzled],
124 dtype=float32)
125 if self.drizzle:
126 self.frame_drizzled = zeros([self.dim_y_drizzled, self.dim_x_drizzled],
127 dtype=float32)
128
129 # If the alignment point patches do not cover the entire frame, a background image must
130 # be computed and blended in. At this point it is not yet clear if this is necessary.
131 self.background_patches = None
132 self.averaged_background = None
133
134 # Allocate a buffer which for each pixel of the image accumulates the weights at each pixel.
135 # This buffer is used to normalize the image buffer. It is initialized with a small value to
136 # avoid divide by zero.
137 self.sum_single_frame_weights = full([self.dim_y_drizzled, self.dim_x_drizzled], 1.e-30,
138 dtype=float32)
139
140 # Prepare for debugging the local de-warping: In each frame a shifted AP patch can be
141 # compared to the corresponding section of the reference frame. This is visualized in a
142 # separate GUI window. Visualization control is done via three signals passed from the
143 # workflow thread.
144 self.debug = debug
145 self.scale_factor = 3
146 self.border = 2
147 self.image_delay = 0.5
148 self.create_image_window_signal = create_image_window_signal
149 self.update_image_window_signal = update_image_window_signal
150 self.terminate_image_window_signal = terminate_image_window_signal
151
152 self.my_timer.stop('Stacking: AP initialization')
153
154 def prepare_for_stack_blending(self):
155 """
156 Find image locations where the background image is needed for stacking. If the fraction of
157 such pixels is above a given parameter, a full background image is constructed from the best
158 frames during the stacking process. If the fraction is low, the image is subdivided into
159 quadratic patches. To save computing time, the background image is constructed only in those
160 patches which contain at least one pixel where the background is needed.
161
162 :return:
163 """
164
165 self.my_timer.start('Stacking: initialize background blending')
166
167 # The stack size is the number of frames which contribute to each AP stack.
168 single_stack_size_float = float(self.alignment_points.stack_size)
169
170 # Add the contributions of all alignment points into a single buffer.
171 for alignment_point in self.alignment_points.alignment_points:
172 patch_y_low_drizzled = alignment_point['patch_y_low_drizzled']
173 patch_y_high_drizzled = alignment_point['patch_y_high_drizzled']
174 patch_x_low_drizzled = alignment_point['patch_x_low_drizzled']
175 patch_x_high_drizzled = alignment_point['patch_x_high_drizzled']
176
177 # If the patch is on the image boundary, do not ramp down the weight from the patch
178 # center towards that boundary. This way it is avoided that the background image is
179 # computed there and blended in with the patch.
180 extend_low_y = patch_y_low_drizzled == 0
181 extend_high_y = patch_y_high_drizzled == self.dim_y_drizzled
182 extend_low_x = patch_x_low_drizzled == 0
183 extend_high_x = patch_x_high_drizzled == self.dim_x_drizzled
184
185 # Compute the weights used in AP blending and store them with the AP.
186 alignment_point['weights_yx'] = minimum(self.one_dim_weight(patch_y_low_drizzled,
187 patch_y_high_drizzled,
188 alignment_point['y_drizzled'],
189 extend_low=extend_low_y,
190 extend_high=extend_high_y)[
191 :, newaxis],
192 self.one_dim_weight(patch_x_low_drizzled,
193 patch_x_high_drizzled,
194 alignment_point['x_drizzled'],
195 extend_low=extend_low_x,
196 extend_high=extend_high_x)[
197 newaxis, :])
198
199 # This is an alternative where the weights decrease more rapidly towards the corners.
200 # alignment_point['weights_yx'] = self.one_dim_weight(patch_y_low, patch_y_high,
201 # alignment_point['y'], extend_low=extend_low_y,
202 # extend_high=extend_high_y)[:, newaxis] * \
203 # self.one_dim_weight(patch_x_low, patch_x_high,
204 # alignment_point['x'], extend_low=extend_low_x,
205 # extend_high=extend_high_x)
206
207 # For each image buffer pixel add the weights. This is used for normalization later.
208 self.sum_single_frame_weights[patch_y_low_drizzled:patch_y_high_drizzled,
209 patch_x_low_drizzled: patch_x_high_drizzled] += single_stack_size_float \
210 * alignment_point['weights_yx']
211
212 # Compute the fraction of pixels where no AP patch contributes.
213 self.number_stacking_holes = count_nonzero(self.sum_single_frame_weights < 1.e-10)
214
215 # If all pixels are covered by AP patches, no background image is required.
216 if self.number_stacking_holes == 0:
217 self.my_timer.stop('Stacking: initialize background blending')
218 return
219
220 # If the alignment points do not cover the full frame, blend the AP contributions with
221 # a background computed as the average of globally shifted best frames. The background
222 # should only shine through outside AP patches.
223 #
224 # The "real" alignment point contributions are collected in the "stacked_image_buffer".
225 # Only the "holes" in the buffer have to be filled with the "averaged_background".
226 # Allocate a buffer for the background image.
227 if self.frames.color:
228 self.averaged_background = zeros([self.dim_y, self.dim_x, 3], dtype=float32)
229 else:
230 self.averaged_background = zeros([self.dim_y, self.dim_x], dtype=float32)
231
232 # Compute the number of points where the background image will be used in patch blending.
233 points_where_background_used = count_nonzero(self.sum_single_frame_weights <
234 self.configuration.stack_frames_background_blend_threshold *
235 single_stack_size_float)
236
237 # If the fraction is below a certain limit, it is worthwhile to compute the background
238 # image only where it is needed. Construct a list with patches where the background is
239 # needed.
240 if points_where_background_used/self.number_pixels_drizzled < \
241 self.configuration.stack_frames_background_fraction:
242
243 # Initialize a list of background patches.
244 self.background_patches = []
245
246 # Subdivide the image area in quadratic patches. Cycle through all patch locations.
247 for patch_y_low in range(0, self.dim_y,
248 self.configuration.stack_frames_background_patch_size):
249 patch_y_high = min(
250 patch_y_low + self.configuration.stack_frames_background_patch_size,
251 self.dim_y - 1)
252
253 # Handle the special case where the patch has zero size in one direction.
254 if patch_y_low == patch_y_high:
255 continue
256 for patch_x_low in range(0, self.dim_x,
257 self.configuration.stack_frames_background_patch_size):
258 patch_x_high = min(
259 patch_x_low + self.configuration.stack_frames_background_patch_size,
260 self.dim_x - 1)
261 if patch_x_low == patch_x_high:
262 continue
263
264 # If the patch contains pixels where the background is used, add it to the list.
265 if count_nonzero(self.sum_single_frame_weights[
266 patch_y_low * self.configuration.drizzle_factor:
267 patch_y_high * self.configuration.drizzle_factor,
268 patch_x_low * self.configuration.drizzle_factor:
269 patch_x_high * self.configuration.drizzle_factor] <
270 self.configuration.stack_frames_background_blend_threshold *
271 single_stack_size_float) > 0:
272 background_patch = {}
273 background_patch['patch_y_low'] = patch_y_low
274 background_patch['patch_y_high'] = patch_y_high
275 background_patch['patch_x_low'] = patch_x_low
276 background_patch['patch_x_high'] = patch_x_high
277 self.background_patches.append(background_patch)
278
279 self.my_timer.stop('Stacking: initialize background blending')
280
281 def stack_frames(self):
282 """
283 Compute the shifted contributions of all frames to all alignment points and add them to the
284 appropriate alignment point stacking buffers.
285
286 :return: -
287 """
288
289 # First find out if there are holes between AP patches.
290 self.prepare_for_stack_blending()
291
292 # Initialize the array for shift distribution statistics.
293 self.shift_distribution = full((
294 self.configuration.alignment_points_search_width *
295 self.configuration.drizzle_factor * 2,), 0, dtype=int)
296 self.shift_failure_counter = 0
297
298 # If multi-level correlation AP matching is selected, prepare frame-independent data
299 # structures used by this particular search algorithm.
300 if self.configuration.alignment_points_method == 'MultiLevelCorrelation':
301 # Set the two-level reference boxes for all APs.
302 self.alignment_points.set_reference_boxes_correlation()
303
304 # Compute the "weight matrix" used in the first correlation phase. It penalizes search
305 # results far away from the center.
306 search_width_second_phase = 4
307 max_search_width_first_phase = int(
308 (self.configuration.alignment_points_search_width - search_width_second_phase) / 2)
309 search_width_first_phase = max_search_width_first_phase
310 extent = 2 * search_width_first_phase + 1
311 weight_matrix_first_phase = empty((extent, extent), dtype=float32)
312 for y in range(extent):
313 for x in range(extent):
314 weight_matrix_first_phase[
315 y, x] = 1. - self.configuration.alignment_points_penalty_factor * (
316 (y / search_width_first_phase - 1) ** 2 + (
317 x / search_width_first_phase - 1) ** 2)
318
319 else:
320 weight_matrix_first_phase = None
321
322 # In debug mode: Prepare for de-warp visualization.
323 if self.debug:
324 self.create_image_window_signal.emit()
325
326 # If brightness normalization is switched on, prepare for adjusting frame brightness.
327 if self.configuration.frames_normalization:
328 median_brightness = median([self.frames.average_brightness(index)
329 for index in range(self.frames.number)])
330 # print ("min: " + str(min(self.frames.frames_average_brightness)) + ", median: "
331 # + str(median_brightness) + ", max: "
332 # + str(max(self.frames.frames_average_brightness)))
333
334 # Initialize widths of border areas where artifacts occur because not all patches contribute.
335 self.border_y_low = self.border_y_high = self.border_x_low = self.border_x_high = 0
336
337 # Go through the list of all frames.
338 for frame_index in range(self.frames.number):
339
340 # If brightness normalization is switched on, change the brightness of this frame to
341 # the median of all frames.
342 if self.configuration.frames_normalization:
343 frame = self.frames.frames(frame_index) * median_brightness / \
344 (self.frames.average_brightness(frame_index) + 1.e-7)
345 else:
346 frame = self.frames.frames(frame_index)
347
348 # Change the current frame into float32. If drizzle is active, also interpolate values.
349 if self.drizzle:
350 self.frame_drizzled = resize(frame.astype(float32),
351 (frame.shape[1]*self.configuration.drizzle_factor, frame.shape[0]*self.configuration.drizzle_factor),
352 interpolation=INTER_LINEAR)
353 else:
354 self.frame_drizzled = frame.astype(float32)
355
356 frame_mono_blurred = self.frames.frames_mono_blurred(frame_index)
357
358 # After every "signal_step_size"th frame, send a progress signal to the main GUI.
359 if self.progress_signal is not None and frame_index % self.signal_step_size == 1:
360 self.progress_signal.emit("Stack frames",
361 int(round(10 * frame_index / self.frames.number) * 10))
362
363 # Look up the constant shifts of the given frame with respect to the mean frame.
364 dy = self.align_frames.dy[frame_index]
365 dx = self.align_frames.dx[frame_index]
366
367 # Go through all alignment points for which this frame was found to be among the best.
368 for alignment_point_index in self.frames.used_alignment_points[frame_index]:
369 alignment_point = self.alignment_points.alignment_points[alignment_point_index]
370
371 # Compute the local warp shift for this frame.
372 self.my_timer.start('Stacking: compute AP shifts')
373 [shift_y, shift_x], success = self.alignment_points.compute_shift_alignment_point(
374 frame_mono_blurred, frame_index, alignment_point_index,
375 de_warp=self.configuration.alignment_points_de_warp,
376 weight_matrix_first_phase=weight_matrix_first_phase,
377 subpixel_solve=self.drizzle)
378
379 # The total shift consists of three components: different coordinate origins for
380 # current frame and mean frame, global shift of current frame, and the local warp
381 # shift at this alignment point. The first two components are accounted for by dy,
382 # dx. If drizzle is active, translate shifts into drizzled pixel distances.
383 shift_y_drizzled = int(round(shift_y * self.configuration.drizzle_factor))
384 shift_x_drizzled = int(round(shift_x * self.configuration.drizzle_factor))
385 total_shift_y_drizzled = dy * self.configuration.drizzle_factor - shift_y_drizzled
386 total_shift_x_drizzled = dx * self.configuration.drizzle_factor - shift_x_drizzled
387
388 # Increment the counter corresponding to the 2D warp shift. Increase the resolution
389 # according to the drizzle factor.
390 if success:
391 self.shift_distribution[int(round(sqrt(shift_y_drizzled ** 2 + shift_x_drizzled ** 2)))] += 1
392 else:
393 self.shift_failure_counter += 1
394
395 self.my_timer.stop('Stacking: compute AP shifts')
396
397 # In debug mode: visualize shifted patch of the first AP and compare it with the
398 # corresponding patch of the reference frame.
399 if self.debug and not alignment_point_index:
400 frame_mono_blurred = self.frames.frames_mono_blurred(frame_index)
401 total_shift_y = dy - shift_y
402 total_shift_y_int = int(round(total_shift_y))
403 total_shift_x = dx - shift_x
404 total_shift_x_int = int(round(total_shift_x))
405 y_low = alignment_point['patch_y_low']
406 y_high = alignment_point['patch_y_high']
407 x_low = alignment_point['patch_x_low']
408 x_high = alignment_point['patch_x_high']
409 reference_patch = (self.alignment_points.mean_frame[y_low:y_high, x_low:x_high]).astype(uint16)
410 reference_patch = resize(reference_patch, None,
411 fx=float(self.scale_factor),
412 fy=float(self.scale_factor))
413
414 try:
415 # Cut out the globally stabilized and the de-warped patches
416 frame_stabilized = frame_mono_blurred[y_low+dy:y_high+dy, x_low+dx:x_high+dx]
417 frame_stabilized = resize(frame_stabilized, None,
418 fx=float(self.scale_factor),
419 fy=float(self.scale_factor))
420 font = FONT_HERSHEY_SIMPLEX
421 fontScale = 0.5
422 fontColor = (0, 255, 0)
423 lineType = 1
424 putText(frame_stabilized, 'stabilized: ' + str(dy) + ', ' + str(dx),
425 (5, 25), font, fontScale, fontColor, lineType)
426
427 frame_dewarped = frame_mono_blurred[y_low+total_shift_y_int:y_high+total_shift_y_int,
428 x_low+total_shift_x_int:x_high+total_shift_x_int]
429 frame_dewarped = resize(frame_dewarped, None,
430 fx=float(self.scale_factor),
431 fy=float(self.scale_factor))
432 putText(frame_dewarped, 'de-warped: ' + str(int(round(shift_y))) + ', ' +
433 str(int(round(shift_x))), (5, 25), font, fontScale, fontColor, lineType)
434 # Compose the three patches into a single image and send it to the
435 # visualization window.
436 composed_image = Miscellaneous.compose_image([frame_stabilized,
437 reference_patch, frame_dewarped],
438 border=self.border)
439 self.update_image_window_signal.emit(composed_image)
440 except Exception as e:
441 print(str(e))
442
443 # Insert a delay to keep the current frame long enough in the visualization
444 # window.
445 sleep(self.image_delay)
446
447 # Add the shifted alignment point patch to the AP's stacking buffer.
448 self.my_timer.start('Stacking: remapping and adding')
449 self.remap_rigid(self.frame_drizzled, alignment_point['stacking_buffer'],
450 total_shift_y_drizzled, total_shift_x_drizzled,
451 alignment_point['patch_y_low_drizzled'],
452 alignment_point['patch_y_high_drizzled'],
453 alignment_point['patch_x_low_drizzled'],
454 alignment_point['patch_x_high_drizzled'])
455 self.my_timer.stop('Stacking: remapping and adding')
456
457 # If there are holes between AP patches, add this frame's contribution (if any) to the
458 # averaged background image.
459 if self.number_stacking_holes > 0 and \
460 frame_index in self.rank_frames.quality_sorted_indices[
461 :self.alignment_points.stack_size]:
462 self.my_timer.start('Stacking: computing background')
463
464 # Treat the case that the background is computed for specific patches only.
465 if self.background_patches:
466 for patch in self.background_patches:
467 self.averaged_background[patch['patch_y_low']:patch['patch_y_high'],
468 patch['patch_x_low']:patch['patch_x_high']] += \
469 frame[patch['patch_y_low'] + dy : patch['patch_y_high'] + dy,
470 patch['patch_x_low'] + dx : patch['patch_x_high'] + dx]
471
472 # The complete background image is computed.
473 else:
474 self.averaged_background += frame[dy:self.dim_y + dy, dx:self.dim_x + dx]
475 self.my_timer.stop('Stacking: computing background')
476
477 if self.progress_signal is not None:
478 self.progress_signal.emit("Stack frames", 100)
479
480 # Compute counters for shift distribution analysis.
481 shift_counter = sum(self.shift_distribution)
482 self.shift_entries_total = shift_counter + self.shift_failure_counter
483 if self.shift_entries_total:
484 self.shift_failure_percent = round(
485 100. * self.shift_failure_counter / self.shift_entries_total, 3)
486 else:
487 # If the value is <0, the percentage is not printed.
488 self.shift_failure_percent = -1.
489
490 # In debug mode: Close de-warp visualization window.
491 if self.debug:
492 self.terminate_image_window_signal.emit()
493
494 # If a background image is being computed, extend the background buffer into drizzled
495 # coordinates and normalize the buffer values.
496 if self.number_stacking_holes > 0:
497 self.my_timer.start('Stacking: computing background')
498 # If drizzling is active, extend the background image into drizzled coordinates.
499 if self.drizzle:
500 # Be careful: OpenCV resize expects the "width" dimension first!
501 self.averaged_background = resize(self.averaged_background,
502 (self.dim_x_drizzled, self.dim_y_drizzled),
503 interpolation=INTER_CUBIC)
504 # Divide the buffer by the number of contributions.
505 self.averaged_background /= self.alignment_points.stack_size
506 self.my_timer.stop('Stacking: computing background')
507
508 def remap_rigid(self, frame, buffer, shift_y, shift_x, y_low, y_high, x_low, x_high):
509 """
510 The alignment point patch is taken from the given frame with a constant shift in x and y
511 directions. The shifted patch is then added to the given alignment point buffer.
512
513 :param frame: frame to be stacked
514 :param buffer: Stacking buffer of the corresponding alignment point
515 :param shift_y: Constant shift in y direction between frame stack and current frame
516 :param shift_x: Constant shift in x direction between frame stack and current frame
517 :param y_low: Lower y index of the quality window on which this method operates
518 :param y_high: Upper y index of the quality window on which this method operates
519 :param x_low: Lower x index of the quality window on which this method operates
520 :param x_high: Upper x index of the quality window on which this method operates
521 :return: -
522 """
523
524 # Compute index bounds for "source" patch in current frame, and for summation buffer
525 # ("target"). Because of local warp effects, the indexing may reach beyond frame borders.
526 # In this case reduce the copy area.
527 frame_size_y = frame.shape[0]
528 y_low_source = y_low + shift_y
529 y_high_source = y_high + shift_y
530 y_low_target = 0
531 # If the shift reaches beyond the frame, reduce the copy area.
532 if y_low_source < 0:
533 y_low_target = -y_low_source
534 y_low_source = 0
535 self.border_y_low = max(self.border_y_low, y_low_target)
536 if y_high_source > frame_size_y:
537 self.border_y_high = max(self.border_y_high, y_high_source - frame_size_y)
538 y_high_source = frame_size_y
539 y_high_target = y_low_target + y_high_source - y_low_source
540
541 frame_size_x = frame.shape[1]
542 x_low_source = x_low + shift_x
543 x_high_source = x_high + shift_x
544 x_low_target = 0
545 # If the shift reaches beyond the frame, reduce the copy area.
546 if x_low_source < 0:
547 x_low_target = -x_low_source
548 x_low_source = 0
549 self.border_x_low = max(self.border_x_low, x_low_target)
550 if x_high_source > frame_size_x:
551 self.border_x_high = max(self.border_x_high, x_high_source - frame_size_x)
552 x_high_source = frame_size_x
553 x_high_target = x_low_target + x_high_source - x_low_source
554
555 # If frames are in color, stack all three color channels using the same mapping. Please note
556 # that in this case the buffers have a third dimension (color), while monochrome buffers
557 # are two-dimensional. Add the frame contribution to the stacking buffer.
558 buffer[y_low_target:y_high_target, x_low_target:x_high_target] += \
559 frame[y_low_source:y_high_source, x_low_source:x_high_source]
560
561 def merge_alignment_point_buffers(self):
562 """
563 Merge the summation buffers for all alignment points into the global stacking buffer. For
564 every pixel location divide the global buffer by the number of contributing image patches.
565 This results in a uniform brightness level across the whole image, even if alignment point
566 patches overlap.
567
568 :return: The final stacked image
569 """
570
571 self.my_timer.start('Stacking: merging AP buffers')
572
573 # Add the contributions of all alignment points into a single buffer.
574 for alignment_point in self.alignment_points.alignment_points:
575 patch_y_low_drizzled = alignment_point['patch_y_low_drizzled']
576 patch_y_high_drizzled = alignment_point['patch_y_high_drizzled']
577 patch_x_low_drizzled = alignment_point['patch_x_low_drizzled']
578 patch_x_high_drizzled = alignment_point['patch_x_high_drizzled']
579
580 # Add the stacking buffer of the alignment point to the appropriate location of the
581 # global stacking buffer.
582 if self.frames.color:
583 self.stacked_image_buffer[patch_y_low_drizzled:patch_y_high_drizzled,
584 patch_x_low_drizzled: patch_x_high_drizzled, :] += \
585 alignment_point['stacking_buffer'] * alignment_point['weights_yx'][:, :, newaxis]
586 else:
587 self.stacked_image_buffer[patch_y_low_drizzled:patch_y_high_drizzled,
588 patch_x_low_drizzled: patch_x_high_drizzled] += alignment_point['stacking_buffer'] * \
589 alignment_point['weights_yx']
590
591 # Divide the global stacking buffer pixel-wise by the number of image contributions. Please
592 # note that there is no division by zero because the array "sum_single_frame_weights" was
593 # initialized to 1.E-30.
594 if self.frames.color:
595 self.stacked_image_buffer /= self.sum_single_frame_weights[:, :, newaxis]
596 else:
597 self.stacked_image_buffer /= self.sum_single_frame_weights
598
599 self.my_timer.stop('Stacking: merging AP buffers')
600
601 # If the alignment points do not cover the full frame, blend the AP contributions with
602 # a background computed as the average of globally shifted best frames. The background
603 # should only shine through outside AP patches.
604 if self.number_stacking_holes > 0:
605 self.my_timer.create_no_check('Stacking: blending APs with background')
606
607 # The background image has been computed where self.sum_single_frame_weights is below the
608 # threshold. Compute for every pixel the weight (between 0. and 1.) with which the
609 # stacked patches are to be blended with the background image. Please note that the
610 # weights have to be divided by the stack size first, to normalize them to 1. at patch
611 # centers.
612 foreground_weight = self.sum_single_frame_weights / \
613 (self.configuration.stack_frames_background_blend_threshold *
614 self.alignment_points.stack_size)
615 clip(foreground_weight, 0., 1., out=foreground_weight)
616
617 # Blend the AP buffer with the background.
618 if self.frames.color:
619 self.stacked_image_buffer = (self.stacked_image_buffer-self.averaged_background) * \
620 foreground_weight[:, :, newaxis] + \
621 self.averaged_background
622 else:
623 self.stacked_image_buffer = (self.stacked_image_buffer-self.averaged_background) * \
624 foreground_weight + self.averaged_background
625
626 self.my_timer.stop('Stacking: blending APs with background')
627
628 # Trim the borders of the stacked buffer such that no artifacts from incomplete stacks
629 # (caused by warp shifts) remain.
630 if self.border_y_low or self.border_y_high or self.border_x_low or self.border_x_high:
631 self.stacked_image_buffer = self.stacked_image_buffer[
632 self.border_y_low:self.dim_y_drizzled - self.border_y_high,
633 self.border_x_low:self.dim_x_drizzled - self.border_x_high]
634
635 # Scale the image buffer such that entries are in the interval [0., 1.]. Then convert the
636 # float image buffer to 16bit int (or 48bit in color mode).
637 if self.frames.depth == 8:
638 self.stacked_image = img_as_uint(
639 clip(self.stacked_image_buffer / 255, 0., 1., out=self.stacked_image_buffer))
640 else:
641 self.stacked_image = img_as_uint(
642 clip(self.stacked_image_buffer / 65535, 0., 1., out=self.stacked_image_buffer))
643
644 return self.stacked_image
645
646 def half_stacked_image_buffer_resolution(self):
647 """
648 If drizzling is active with the option 1.5x, the computations are performed with the factor
649 3x. As a final step, the resolution of the stacked image buffer is halved.
650
651 :return: -
652 """
653
654 self.stacked_image = resize(self.stacked_image, None,
655 fx=float(0.5), fy=float(0.5))
656
657 @staticmethod
658 def one_dim_weight(patch_low, patch_high, box_center, extend_low=False, extend_high=False):
659 """
660 Compute one-dimensional weighting ramps between box center and patch borders. This function
661 is called for y and x dimensions separately.
662
663 :param patch_low: Lower index of AP patch in the given coordinate direction
664 :param patch_high: Upper index of AP patch in the given coordinate direction
665 :param box_center: AP coordinate index in the given direction (center of box)
666 :param extend_low: If true, set all weights from patch_low to box_center to 1.
667 (and thus replace the ramp in that index range)
668 :param extend_high: If true, set all weights from box_center to patch_high-1 to 1.
669 (and thus replace the ramp in that index range)
670 :return: Vector with weights, starting with 1./(box_center - patch_low +1) at patch_low,
671 ramping up to 1. at box_center, and than ramping down to
672 1./(patch_high - box_center) at patch_high-1.
673 """
674
675 # Compute offsets relative to patch_low.
676 patch_high_offset = patch_high - patch_low
677 center_offset = box_center - patch_low
678
679 # Allocate weights array, length given by patch size.
680 weights = empty((patch_high_offset,), dtype=float32)
681
682 # If extend_low: Replace lower ramp with constant value 1.
683 if extend_low:
684 weights[0:center_offset] = 1.
685 # Ramp up from a small value to 1. at the center coordinate.
686 else:
687 weights[0:center_offset] = arange(1, center_offset + 1, 1) / float32(
688 center_offset + 1)
689
690 # Now set the weights for indices starting with the center coordinate (weight 1.) and
691 # ending at the upper patch boundary with a small value. Again, if "extend_high" is set
692 # to True, the ramp is replaced with a constant value 1.
693 if extend_high:
694 weights[center_offset:patch_high_offset] = 1.
695 else:
696 weights[center_offset:patch_high_offset] = arange(patch_high - box_center, 0,
697 -1) / float32(
698 patch_high - box_center)
699
700 return weights
701
702 def print_shift_table(self):
703 """
704 Print a table giving for each shift (in pixels) the number of occurrences. The table ends at
705 the last non-zero entry.
706
707 :return: String with three lines to be printed to the protocol file(s)
708 """
709
710 # Find the last non-zero entry in the array.
711 if max(self.shift_distribution) > 0:
712 max_index = [index for index, item in enumerate(self.shift_distribution) if item != 0][-1] \
713 + 1
714
715 # Initialize the three table lines.
716 s = " Shift (pixels):"
717 line = " ---------------"
718 t = " Percent: "
719
720 # Extend the three table lines up to the max index.
721 for index in range(max_index):
722 s += "|{:7d} ".format(index)
723 line += "---------"
724 t += "|{:7.3f} ".format(100.*self.shift_distribution[index]/self.shift_entries_total)
725
726 # Finish the three table lines.
727 s += "|"
728 line += "-"
729 t += "|"
730
731 # Return the lines to be printed to the protocol.
732 return s + "\n" + line + "\n" + t + "\n\n" + \
733 " Failed shift measurements: {:7.3f} %".format(
734 self.shift_failure_percent)
735 else:
736 return ""
737
738
739 if __name__ == "__main__":
740 # Initalize the timer object used to measure execution times of program sections.
741 my_timer = timer()
742
743 # Images can either be extracted from a video file or a batch of single photographs. Select
744 # the example for the test run.
745 type = 'video'
746 if type == 'image':
747 names = glob('Images/2012*.tif')
748 # names = glob.glob('Images/Moon_Tile-031*ap85_8b.tif')
749 # names = glob.glob('Images/Example-3*.jpg')
750 else:
751 names = 'Videos/another_short_video.avi'
752 print(names)
753
754 my_timer.create('Execution over all')
755
756 # Get configuration parameters.
757 configuration = Configuration()
758 configuration.initialize_configuration()
759
760 my_timer.create('Read all frames')
761 try:
762 frames = Frames(configuration, names, type=type, bayer_option_selected="Grayscale")
763 print("Number of images read: " + str(frames.number))
764 print("Image shape: " + str(frames.shape))
765 except Error as e:
766 print("Error: " + e.message)
767 exit()
768 my_timer.stop('Read all frames')
769
770 # Rank the frames by their overall local contrast.
771 my_timer.create('Ranking images')
772 rank_frames = RankFrames(frames, configuration)
773 rank_frames.frame_score()
774 my_timer.stop('Ranking images')
775
776 print("Index of maximum: " + str(rank_frames.frame_ranks_max_index))
777 print("Frame scores: " + str(rank_frames.frame_ranks))
778 print("Frame scores (sorted): " + str(
779 [rank_frames.frame_ranks[i] for i in rank_frames.quality_sorted_indices]))
780 print("Sorted index list: " + str(rank_frames.quality_sorted_indices))
781
782 # Initialize the frame alignment object.
783 my_timer.create('Select optimal alignment patch')
784 align_frames = AlignFrames(frames, rank_frames, configuration)
785
786 if configuration.align_frames_mode == "Surface":
787 # Select the local rectangular patch in the image where the L gradient is highest in both x
788 # and y direction. The scale factor specifies how much smaller the patch is compared to the
789 # whole image frame.
790 (y_low_opt, y_high_opt, x_low_opt, x_high_opt) = align_frames.compute_alignment_rect(
791 configuration.align_frames_rectangle_scale_factor)
792 my_timer.stop('Select optimal alignment patch')
793 print("optimal alignment rectangle, x_low: " + str(x_low_opt) + ", x_high: " + str(
794 x_high_opt) + ", y_low: " + str(y_low_opt) + ", y_high: " + str(y_high_opt))
795 reference_frame_with_alignment_points = frames.frames_mono(
796 rank_frames.frame_ranks_max_index).copy()
797 reference_frame_with_alignment_points[y_low_opt,
798 x_low_opt:x_high_opt] = reference_frame_with_alignment_points[y_high_opt - 1,
799 x_low_opt:x_high_opt] = 255
800 reference_frame_with_alignment_points[y_low_opt:y_high_opt,
801 x_low_opt] = reference_frame_with_alignment_points[y_low_opt:y_high_opt, x_high_opt - 1] = 255
802 # plt.imshow(reference_frame_with_alignment_points, cmap='Greys_r')
803 # plt.show()
804
805 # Align all frames globally relative to the frame with the highest score.
806 my_timer.create('Global frame alignment')
807 try:
808 align_frames.align_frames()
809 except NotSupportedError as e:
810 print("Error: " + e.message)
811 exit()
812 except InternalError as e:
813 print("Warning: " + e.message)
814 my_timer.stop('Global frame alignment')
815
816 # print("Frame shifts: " + str(align_frames.frame_shifts))
817 print("Intersection: " + str(align_frames.intersection_shape))
818
819 # Compute the reference frame by averaging the best frames.
820 my_timer.create('Compute reference frame')
821 average = align_frames.average_frame()
822 my_timer.stop('Compute reference frame')
823 print("Reference frame computed from the best " + str(
824 align_frames.average_frame_number) + " frames.")
825 # plt.imshow(align_frames.mean_frame, cmap='Greys_r')
826 # plt.show()
827
828 # align_frames.set_roi(100, 700, 200, 700)
829
830 # Initialize the AlignmentPoints object. This includes the computation of the average frame
831 # against which the alignment point shifts are measured.
832 my_timer.create('Initialize alignment point object')
833 alignment_points = AlignmentPoints(configuration, frames, rank_frames, align_frames)
834 my_timer.stop('Initialize alignment point object')
835
836 # Create alignment points, and show alignment point boxes and patches.
837 my_timer.create('Create alignment points')
838 alignment_points.create_ap_grid()
839 my_timer.stop('Create alignment points')
840 print("Number of alignment points created: " + str(len(alignment_points.alignment_points)) +
841 ", number of dropped aps (dim): " + str(alignment_points.alignment_points_dropped_dim) +
842 ", number of dropped aps (structure): " + str(
843 alignment_points.alignment_points_dropped_structure))
844
845 # color_image = alignment_points.show_alignment_points(average)
846 # plt.imshow(color_image)
847 # plt.show()
848
849 # For each alignment point rank frames by their quality.
850 my_timer.create('Rank frames at alignment points')
851 alignment_points.compute_frame_qualities()
852 my_timer.stop('Rank frames at alignment points')
853
854 # Allocate StackFrames object.
855 stack_frames = StackFrames(configuration, frames, rank_frames, align_frames, alignment_points, my_timer)
856
857 # Stack all frames.
858 stack_frames.stack_frames()
859
860 # Merge the stacked alignment point buffers into a single image.
861 stacked_image = stack_frames.merge_alignment_point_buffers()
862
863 # If the drizzle factor is 1.5, reduce the pixel resolution of the stacked image buffer
864 # to half the size used in stacking.
865 if configuration.drizzle_factor_is_1_5:
866 stack_frames.half_stacked_image_buffer_resolution()
867
868 # Save the stacked image as 16bit int (color or mono).
869 Frames.save_image('Images/example_stacked.tiff', stacked_image, color=frames.color,
870 header=configuration.global_parameters_version)
871
872 # Convert to 8bit and show in Window.
873 plt.imshow(img_as_ubyte(stacked_image))
874 plt.show()
875
876 # Print out timer results.
877 my_timer.stop('Execution over all')
878 my_timer.print()