Debian Codegraph @

planetary_system_stacker/alignment_points.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 time import time
25
26 import matplotlib
27 matplotlib.use('Agg')
28 import matplotlib.pyplot as plt
29 from math import ceil
30 from numpy import arange, amax, stack, amin, float32, uint8, zeros, sqrt, empty, int32, uint16
31 from scipy import ndimage
32 try:
33 from skimage.registration import phase_cross_correlation
34 except ImportError:
35 from skimage.feature import register_translation as phase_cross_correlation
36 from cv2 import meanStdDev, GaussianBlur
37
38 from align_frames import AlignFrames
39 from configuration import Configuration
40 from exceptions import NotSupportedError, Error
41 from frames import Frames
42 from miscellaneous import Miscellaneous
43 from rank_frames import RankFrames
44
45
46 class AlignmentPoints(object):
47 """
48 Create a rectangular grid of potential places for alignment points. For each location
49 create a small "alignment box" around it. For each alignment box test if there is enough
50 structure and brightness in the picture to use it as an alignment point. For all
51 alignment points in all frames, compute the local shifts relative to the mean frame.
52
53 """
54
55 def __init__(self, configuration, frames, rank_frames, align_frames, progress_signal=None):
56 """
57 Initialize the AlignmentPoints object and compute the mean frame.
58
59 :param configuration: Configuration object with parameters
60 :param frames: Frames object with all video frames
61 :param rank_frames: RankFrames object with global quality ranks (between 0. and 1.,
62 1. being optimal) for all frames
63 :param align_frames: AlignFrames object with global shift information for all frames
64 :param progress_signal: Either None (no progress signalling), or a signal with the signature
65 (str, int) with the current activity (str) and the progress in
66 percent (int).
67 """
68
69 self.configuration = configuration
70 self.frames = frames
71 self.rank_frames = rank_frames
72 self.align_frames = align_frames
73 self.progress_signal = progress_signal
74
75 # Apply a low-pass filter on the mean frame as a preparation for shift detection.
76 self.mean_frame = GaussianBlur(align_frames.mean_frame.astype(uint16),
77 (self.configuration.frames_gauss_width,
78 self.configuration.frames_gauss_width), 0).astype(int32)
79 self.num_pixels_y = self.mean_frame.shape[0]
80 self.num_pixels_x = self.mean_frame.shape[1]
81 self.alignment_points_dropped_dim = None
82 self.alignment_points_dropped_structure = None
83
84 # Initialize counters for APs which are dropped because
85 # they do not satisfy the brightness or structure condition.
86 self.alignment_points = []
87 self.alignment_points_dropped_dim = 0
88 self.alignment_points_dropped_structure = 0
89
90 # Initialize the number of frames to be stacked at each AP.
91 self.stack_size = None
92
93 self.dev_table = empty((2 * self.configuration.alignment_points_search_width + 1,
94 2 * self.configuration.alignment_points_search_width + 1), dtype=float32)
95
96 @staticmethod
97 def ap_locations(num_pixels, min_boundary_distance, step_size, even):
98 """
99 Compute optimal alignment patch coordinates in one coordinate direction. Place boundary
100 neighbors as close as possible to the boundary.
101
102 :param num_pixels: Number of pixels in the given coordinate direction
103 :param min_boundary_distance: Minimum distance of an AP from the boundary
104 :param step_size: Distance of alignment boxes
105 :param even: If True, compute locations for even row indices. Otherwise, for odd ones.
106 :return: List of alignment point coordinates in the given direction
107 """
108 # Initialize list of locations.
109 locations = []
110
111 # If the frame size is too small for the AP size chosen, no AP locations can be computed.
112 # In this case an empty list is returned.
113 try:
114 # The number of interior alignment boxes in general is not an integer. Round to the next
115 # higher number.
116 num_interior_odd = int(ceil((num_pixels - 2 * min_boundary_distance) / step_size))
117 # Because alignment points are arranged in a staggered grid, in even rows there is one point
118 # more.
119 num_interior_even = num_interior_odd + 1
120
121 # The precise distance between alignment points will differ slightly from the specified
122 # step_size. Compute the exact distance. Integer locations will be rounded later.
123 distance_corrected = (num_pixels - 2 * min_boundary_distance) / num_interior_odd
124
125 # Compute the AP locations, separately for even and odd rows.
126 if even:
127 locations = [int(min_boundary_distance + i * distance_corrected) for i in range(num_interior_even)]
128 else:
129 locations = [int(min_boundary_distance + 0.5 * distance_corrected +
130 i * distance_corrected) for i in range(num_interior_odd)]
131 except:
132 pass
133 return locations
134
135 def create_ap_grid(self):
136 """
137 Create a 2D staggered grid of alignment points. For each AP compute its center coordinates,
138 and the coordinate limits of its alignment box and alignment patch. Only alignment points
139 which satisfy the conditions on brightness, contrast and structure are eventually added to
140 the list.
141
142 :return: List of alignment points.
143 """
144
145 # The alignment patch is the area which is stacked after a rigid displacement.
146 half_patch_width = self.configuration.alignment_points_half_patch_width
147 # The alignment box is the object on which the displacement computation is performed.
148 half_box_width = self.configuration.alignment_points_half_box_width
149 # Number of pixels in one coordinate direction between alignment points
150 step_size = self.configuration.alignment_points_step_size
151 # Maximum displacement searched for in the alignment process.
152 search_width = self.configuration.alignment_points_search_width
153 # Minimum structure value for an alignment point (between 0. and 1.)
154 structure_threshold = self.configuration.alignment_points_structure_threshold
155 # The brightest pixel must be brighter than this value (0 < value <256). Please note that
156 # brightness and contrast values are converted to 16bit resolution.
157 brightness_threshold = self.configuration.alignment_points_brightness_threshold * 256
158 # The difference between the brightest and darkest pixel values must be larger than this
159 # value (0 < value < 256)
160 contrast_threshold = self.configuration.alignment_points_contrast_threshold * 256
161
162 # Reset the alignment point list, and initialize counters for APs which are dropped because
163 # they do not satisfy the brightness or structure condition.
164 self.alignment_points = []
165 self.alignment_points_dropped_dim = 0
166 self.alignment_points_dropped_structure = 0
167
168 # Compute the minimum distance of an AP from the boundary.
169 min_boundary_distance = max(half_box_width + search_width, half_patch_width)
170
171 # Compute y and x coordinate locations of alignment points. Note that the grid is staggered.
172 ap_locations_y = self.ap_locations(self.num_pixels_y, min_boundary_distance,
173 step_size, True)
174 ap_locations_x_even = self.ap_locations(self.num_pixels_x, min_boundary_distance,
175 step_size, True)
176 ap_locations_x_odd = self.ap_locations(self.num_pixels_x, min_boundary_distance,
177 step_size, False)
178
179 # If no AP coordinates fit into the frame, no APs are created.
180 if not ap_locations_y or not ap_locations_x_even or not ap_locations_x_odd:
181 return
182
183 # Compute the minimum distance of an AP center from the frame boundary.
184 min_boundary_distance = max(
185 self.configuration.alignment_points_half_box_width + \
186 self.configuration.alignment_points_search_width,
187 self.configuration.alignment_points_half_patch_width)
188
189 # Create alignment point rows, start with an even one.
190 even = True
191 for index_y, y in enumerate(ap_locations_y):
192 # For the first row extend the patch to the upper frame border, and for the last row
193 # to the lower frame border.
194 extend_y_low = (index_y == 0)
195 extend_y_high = (index_y == len(ap_locations_y)-1)
196
197 # Create x coordinate, depending on the y row being even or odd (staggered grid).
198 if even:
199 ap_locations_x = ap_locations_x_even
200 else:
201 ap_locations_x = ap_locations_x_odd
202
203 # For each location create an alignment point.
204 for index_x, x in enumerate(ap_locations_x):
205 # For the first point in a row, extend the patch to the left frame border, and for
206 # the last point in a row to the right frame border.
207 extend_x_low = (index_x == 0)
208 extend_x_high = (index_x == len(ap_locations_x) - 1)
209
210 alignment_point = self.new_alignment_point(y, x, extend_x_low, extend_x_high,
211 extend_y_low, extend_y_high)
212
213 # Compute structure and brightness information for the alignment box.
214 max_brightness = amax(alignment_point['reference_box'])
215 min_brightness = amin(alignment_point['reference_box'])
216 # If the alignment box satisfies the brightness conditions, add the AP to the list.
217 if max_brightness > brightness_threshold and max_brightness - \
218 min_brightness > contrast_threshold:
219
220 # Check if the fraction of dark pixels exceeds a threshold.
221 box = alignment_point['reference_box']
222 fraction = (box < brightness_threshold).sum() / (box.shape[0] * box.shape[1])
223 if fraction > self.configuration.alignment_points_dim_fraction_threshold:
224
225 # Compute the center of mass of the brightness distribution within the box,
226 # and shift the box center to this location.
227 com = ndimage.measurements.center_of_mass(box)
228 y_adapted = y + int(com[0]) - half_box_width
229 x_adapted = x + int(com[1]) - half_box_width
230
231 y_adapted = max(y_adapted, min_boundary_distance)
232 y_adapted = min(y_adapted, self.num_pixels_y - min_boundary_distance)
233 x_adapted = max(x_adapted, min_boundary_distance)
234 x_adapted = min(x_adapted, self.num_pixels_x - min_boundary_distance)
235
236 # Replace the alignment point with a new one, using the updated
237 # coordinates.
238 alignment_point = self.new_alignment_point(y_adapted, x_adapted,
239 extend_x_low, extend_x_high,
240 extend_y_low, extend_y_high)
241
242 alignment_point['structure'] = Miscellaneous.quality_measure(
243 alignment_point['reference_box'])
244 self.alignment_points.append(alignment_point)
245 else:
246 # If a point does not satisfy the conditions, increase the counter.
247 self.alignment_points_dropped_dim += 1
248
249 # Switch between even and odd rows.
250 even = not even
251
252 # Normalize the structure information for all alignment point boxes by dividing by the
253 # maximum value.
254 if self.alignment_points:
255 structure_max = max(
256 alignment_point['structure'] for alignment_point in self.alignment_points)
257 alignment_points_dropped_structure_indices = []
258 for alignment_point_index, alignment_point in enumerate(self.alignment_points):
259 alignment_point['structure'] /= structure_max
260 # Remove alignment points with too little structure and increment the counter.
261 if alignment_point['structure'] < structure_threshold:
262 alignment_points_dropped_structure_indices.append(alignment_point_index)
263 self.alignment_points_dropped_structure += 1
264
265 # Remove alignment points which do not satisfy the structure condition, if there is any.
266 if alignment_points_dropped_structure_indices:
267 alignment_points_new = []
268 dropped_index = 0
269 for alignment_point_index, alignment_point in enumerate(self.alignment_points):
270 if alignment_point_index != alignment_points_dropped_structure_indices[
271 dropped_index]:
272 alignment_points_new.append(alignment_point)
273 elif dropped_index < len(alignment_points_dropped_structure_indices) - 1:
274 dropped_index += 1
275 self.alignment_points = alignment_points_new
276
277 def new_alignment_point(self, y, x, extend_x_low, extend_x_high, extend_y_low, extend_y_high):
278 """
279 Create a new alignment point. This method is called in creating the initial alignment point
280 grid. Later it can be invoked by the user to add single alignment points.
281
282 :param y: y coordinate of alignment point center
283 :param x: x coordinate of alignment point center
284 :param extend_x_low: True, if patch is to be extended to the left frame boundary.
285 False otherwise.
286 :param extend_x_high: True, if patch is to be extended to the right frame boundary.
287 False otherwise.
288 :param extend_y_low: True, if patch is to be extended to the upper frame boundary.
289 False otherwise.
290 :param extend_y_high: True, if patch is to be extended to the lower frame boundary.
291 False otherwise.
292 :return: If successful, the alignment point object is returned; otherwise None.
293 """
294
295 # If the patch does not fit into the frame, or the AP box is too close to the border,
296 # the AP cannot be created at this place.
297 min_boundary_distance = max(self.configuration.alignment_points_half_box_width + \
298 self.configuration.alignment_points_search_width,
299 self.configuration.alignment_points_half_patch_width)
300 if y<min_boundary_distance or y>self.num_pixels_y-min_boundary_distance or \
301 x<min_boundary_distance or x>self.num_pixels_x-min_boundary_distance:
302 return None
303
304 alignment_point = {}
305 alignment_point['y'] = y
306 alignment_point['x'] = x
307 alignment_point['half_box_width'] = self.configuration.alignment_points_half_box_width
308 alignment_point['box_y_low'] = y - self.configuration.alignment_points_half_box_width
309 alignment_point['box_y_high'] = y + self.configuration.alignment_points_half_box_width
310 alignment_point['box_x_low'] = x - self.configuration.alignment_points_half_box_width
311 alignment_point['box_x_high'] = x + self.configuration.alignment_points_half_box_width
312
313 alignment_point['patch_y_low'] = y - self.configuration.alignment_points_half_patch_width
314 alignment_point['patch_y_high'] = y + self.configuration.alignment_points_half_patch_width
315 if extend_y_low:
316 alignment_point['patch_y_low'] = 0
317 elif extend_y_high:
318 alignment_point['patch_y_high'] = self.num_pixels_y
319
320 alignment_point['patch_x_low'] = x - self.configuration.alignment_points_half_patch_width
321 alignment_point['patch_x_high'] = x + self.configuration.alignment_points_half_patch_width
322 if extend_x_low:
323 alignment_point['patch_x_low'] = 0
324 elif extend_x_high:
325 alignment_point['patch_x_high'] = self.num_pixels_x
326
327 # Initialize the reference to the corresponding widget in the AP viewer scene.
328 alignment_point['graphics_item'] = None
329
330 # Allocate buffers and fill alignment point box with mean frame.
331 AlignmentPoints.set_reference_box(alignment_point, self.mean_frame)
332
333 return alignment_point
334
335 def add_alignment_point(self, ap):
336 """
337 Add an alignment point to the list.
338
339 :param ap: AP to be added
340 :return: -
341 """
342
343 self.alignment_points.append(ap)
344
345 def remove_alignment_points(self, ap_list):
346 """
347 Remove a list of alignment points from the current list.
348
349 :param ap_list: List of point objects to be removed
350 :return: -
351 """
352
353 # Create list with unique identifiers of all items on the list.
354 ap_list_ids = [id(ap_list_item) for ap_list_item in ap_list]
355
356 # Replace the original AP list with the reduced one.
357 # If the identifier of an alignment point does not match any list item, keep it.
358 self.alignment_points = [ap for ap in self.alignment_points if id(ap) not in ap_list_ids]
359
360 def replace_alignment_point(self, ap_old, ap_new):
361 """
362 Replace an alignment point with a new one.
363
364 :param ap_old: Existing alignment point to be replaced
365 :param ap_new: New alignment point to replace the old one
366 :return: True if successful, False otherwise
367 """
368
369 ap_old_id = id(ap_old)
370 for index, ap in enumerate(self.alignment_points):
371 if id(ap) == ap_old_id:
372 self.alignment_points[index] = ap_new
373 return True
374 return False
375
376 def move_alignment_point(self, ap, y_new, x_new):
377 """
378 Move an existing AP to a different position.
379
380 :param ap: Esisting alignment point to be moved
381 :param y_new: New y coordinate of AP center
382 :param x_new: New x coordinate of AP center
383 :return: The updated AP; or None, if unsuccessful
384 """
385
386 # Try to do the changes. If unsuccessful, return None.
387 return self.change_alignment_point(ap, y_new, x_new, ap['half_box_width'])
388
389 def resize_alignment_point(self, ap, factor):
390 """
391 Change the size of an existing alignment point.
392
393 :param ap: Esisting alignment point to be resized
394 :param factor: Factor by which the size is to be changed
395 :return: The resized alignment point; or None, if unsuccessful
396 """
397
398 half_box_width_new = ap['half_box_width'] * factor
399
400 # Try to do the changes. If unsuccessful, return None.
401 return self.change_alignment_point(ap, ap["y"], ap["x"], half_box_width_new)
402
403 def change_alignment_point(self, ap, y, x, half_box_width):
404 """
405 Try to fit a resized or moved AP into the frame.
406
407 :param ap: AP to be resized or moved
408 :param y: New y coordinate of center
409 :param x: New x coordinate of center
410 :param half_box_width: New half width of AP box
411 :return: The resized / moved AP; or None, if unsuccessful
412 """
413
414 # Test if the AP box is too small.
415 if half_box_width < self.configuration.alignment_points_min_half_box_width:
416 return None
417
418 # Compute new values for patch and box sizes.
419 half_patch_width_new_int = round(half_box_width *
420 self.configuration.alignment_points_half_patch_width /
421 self.configuration.alignment_points_half_box_width)
422 half_box_width_new_int = round(half_box_width)
423
424 # Compute resized patch bounds. If resizing hits the image boundary on at least one side,
425 # the operation is aborted.
426 patch_y_low = y - half_patch_width_new_int
427 if patch_y_low < 0:
428 return None
429 patch_y_high = y + half_patch_width_new_int
430 if patch_y_high > self.num_pixels_y:
431 return None
432 patch_x_low = x - half_patch_width_new_int
433 if patch_x_low < 0:
434 return None
435 patch_x_high = x + half_patch_width_new_int
436 if patch_x_high > self.num_pixels_x:
437 return None
438
439 # Compute resized box bounds. If resizing moves the box closer to the frame border than
440 # the search width on at least one side, the operation is aborted.
441 box_y_low = y - half_box_width_new_int
442 if box_y_low < self.configuration.alignment_points_search_width:
443 return None
444 box_y_high = y + half_box_width_new_int
445 if box_y_high > self.num_pixels_y - self.configuration.alignment_points_search_width:
446 return None
447 box_x_low = x - half_box_width_new_int
448 if box_x_low < self.configuration.alignment_points_search_width:
449 return None
450 box_x_high = x + half_box_width_new_int
451 if box_x_high > self.num_pixels_x - self.configuration.alignment_points_search_width:
452 return None
453
454 # Perform the changes.
455 ap['y'] = y
456 ap['x'] = x
457 ap['patch_y_low'] = patch_y_low
458 ap['patch_y_high'] = patch_y_high
459 ap['patch_x_low'] = patch_x_low
460 ap['patch_x_high'] = patch_x_high
461 ap['box_y_low'] = box_y_low
462 ap['box_y_high'] = box_y_high
463 ap['box_x_low'] = box_x_low
464 ap['box_x_high'] = box_x_high
465 ap['half_box_width'] = half_box_width
466
467 # Invalidate buffers. To save computing time, they are not re-computed at every wheel
468 # event.
469 ap['graphics_item'] = None
470 ap['reference_box'] = None
471 ap['stacking_buffer'] = None
472
473 return ap
474
475 @staticmethod
476 def set_reference_box(alignment_point, mean_frame):
477 """
478 For APs which have been changed in the AP editor, buffers have been invalidated. They have
479 to be re-computed after AP editing is done.
480
481 :param alignment_point: Alignment_point object
482 :param mean_frame: Average frame
483 :return: -
484 """
485
486 # Cut out the reference box from the mean frame, used in alignment.
487 box = mean_frame[alignment_point['box_y_low']:alignment_point['box_y_high'],
488 alignment_point['box_x_low']:alignment_point['box_x_high']]
489 alignment_point['reference_box'] = box
490
491 def set_reference_boxes_correlation(self):
492 """
493 This method is used if multilevel-correlation AP matching is selected. In this case two
494 reference boxes with different resolution are constructed. The box used in the first phase
495 contains only every second pixel of the original frame in each coordinate direction. The box
496 used in the second phase has the same resolution as the original frame.
497
498 This method is invoked when all APs are set, just before stacking.
499
500 :return: -
501 """
502
503 for ap_index, alignment_point in enumerate(self.alignment_points):
504
505 # Cut the reference box for this alignment point from the mean frame.
506 window_second_phase = self.align_frames.mean_frame[
507 alignment_point['box_y_low']:
508 alignment_point['box_y_high'],
509 alignment_point['box_x_low']:
510 alignment_point['box_x_high']].astype(float32)
511
512 # The reference box with the full resolution is used in the second phase.
513 alignment_point['reference_box_second_phase'] = window_second_phase
514
515 # In the first phase a box with half the resolution is constructed.
516 alignment_point['reference_box_first_phase'] = window_second_phase[::2, ::2]
517
518 @staticmethod
519 def initialize_ap_stacking_buffer(alignment_point, drizzle_factor, color):
520 """
521 In the stacking initialization, for each AP a stacking buffer has to be allocated. At the
522 same time, drizzled patch index bounds are computed.
523
524 :param alignment_point: Alignment_point object
525 :param drizzle_factor: Drizzle factor (integer: 1, 2 or 3)
526 :param color: True, if stacking is to be done for color frames. False for monochrome case.
527 :return: -
528 """
529
530 # Compute drizzled patch coordinates and index bounds.
531 alignment_point['y_drizzled'] = alignment_point['y'] * drizzle_factor
532 alignment_point['x_drizzled'] = alignment_point['x'] * drizzle_factor
533 alignment_point['patch_y_low_drizzled'] = alignment_point['patch_y_low'] * drizzle_factor
534 alignment_point['patch_y_high_drizzled'] = alignment_point['patch_y_high'] * drizzle_factor
535 alignment_point['patch_x_low_drizzled'] = alignment_point['patch_x_low'] * drizzle_factor
536 alignment_point['patch_x_high_drizzled'] = alignment_point['patch_x_high'] * drizzle_factor
537
538 # Allocate space for the stacking buffer.
539 if color:
540 alignment_point['stacking_buffer'] = zeros(
541 [alignment_point['patch_y_high_drizzled'] - alignment_point['patch_y_low_drizzled'],
542 alignment_point['patch_x_high_drizzled'] - alignment_point['patch_x_low_drizzled'],
543 3],
544 dtype=float32)
545 else:
546 alignment_point['stacking_buffer'] = zeros(
547 [alignment_point['patch_y_high_drizzled'] - alignment_point['patch_y_low_drizzled'],
548 alignment_point['patch_x_high_drizzled'] - alignment_point[
549 'patch_x_low_drizzled']], dtype=float32)
550
551 def find_alignment_points(self, y_low, y_high, x_low, x_high):
552 """
553 Find all alignment points the centers of which are within given (y, x) bounds.
554
555 :param y_low: Lower y pixel coordinate bound
556 :param y_high: Upper y pixel coordinate bound
557 :param x_low: Lower x pixel coordinate bound
558 :param x_high: Upper x pixel coordinate bound
559 :return: List of all alignment points with centers within the given coordinate bounds.
560 If no AP satisfies the condition, return an empty list.
561 """
562
563 return [ap for ap in self.alignment_points if y_low <= ap['y'] <= y_high and
564 x_low <= ap['x'] <= x_high]
565
566 @staticmethod
567 def find_neighbor(ap_y, ap_x, alignment_points):
568 """
569 For a given (y, x) position find the closest "real" alignment point.
570
571 :param ap_y: y cocrdinate of location of interest
572 :param ap_x: x cocrdinate of location of interest
573 :param alignment_points: List of alignment points to be searched
574
575 :return: Alignment point object of closest AP, and distance in pixels. If the list of
576 alignment points is empty, (None, None) is returned.
577 """
578
579 # If no APs have been created yet, return None for both results.
580 if not alignment_points:
581 return None, None
582
583 # Start with an impossibly large distance, and find the closest AP on the list.
584 min_distance_squared = 1.e30
585 ap_neighbor = None
586 for ap in alignment_points:
587 distance_squared = (ap['y'] - ap_y) ** 2 + (ap['x'] - ap_x) ** 2
588 if distance_squared < min_distance_squared:
589 ap_neighbor = ap
590 min_distance_squared = distance_squared
591 return ap_neighbor, sqrt(min_distance_squared)
592
593 def compute_frame_qualities(self):
594 """
595 For each alignment point compute a ranking of best frames. Store the list in the
596 alignment point dictionary with the key 'best_frame_indices'.
597
598 Consider the special case that sampled-down Laplacians have been stored for frame ranking.
599 In this case they can be re-used for ranking the boxes around alignment points (but only
600 if "Laplace" has been selected for alignment point ranking).
601
602 :return: -
603 """
604
605 # If the user has entered a value for the number of frames, use it.
606 if self.configuration.alignment_points_frame_number > 0:
607 self.stack_size = self.configuration.alignment_points_frame_number
608 # Otherwise compute the stack size from the given percentage. Take at least one frame.
609 else:
610 self.stack_size = max(int(ceil(
611 self.frames.number * self.configuration.alignment_points_frame_percent / 100.)), 1)
612
613 # Select the ranking method.
614 if self.configuration.alignment_points_rank_method == "xy gradient":
615 method = Miscellaneous.local_contrast
616 elif self.configuration.alignment_points_rank_method == "Laplace":
617 method = Miscellaneous.local_contrast_laplace
618 elif self.configuration.alignment_points_rank_method == "Sobel":
619 method = Miscellaneous.local_contrast_sobel
620 else:
621 raise NotSupportedError(
622 "Ranking method " + self.configuration.alignment_points_rank_method +
623 " not supported")
624
625 # Compute the frequency of progress signals in the computational loop.
626 if self.progress_signal is not None:
627 self.signal_loop_length = max(self.frames.number, 1)
628 self.signal_step_size = max(round(self.frames.number / 10), 1)
629
630 # Initialize a list which for each AP contains the qualities of all frames at this point.
631 for alignment_point in self.alignment_points:
632 alignment_point['frame_qualities'] = []
633
634 if self.configuration.rank_frames_method != "Laplace" or \
635 self.configuration.alignment_points_rank_method != "Laplace":
636 # There are no stored Laplacians, or they cannot be used for the specified method.
637 # Cycle through all frames and alignment points:
638 for frame_index in range(self.frames.number):
639 frame = self.frames.frames_mono_blurred(frame_index)
640
641 # After every "signal_step_size"th frame, send a progress signal to the main GUI.
642 if self.progress_signal is not None and frame_index % self.signal_step_size == 1:
643 self.progress_signal.emit("Rank frames at APs",
644 int(round(10 * frame_index / self.signal_loop_length) * 10))
645
646 for ap_index, alignment_point in enumerate(self.alignment_points):
647 # Compute patch bounds within the current frame.
648 y_low = max(0,
649 alignment_point['patch_y_low'] + self.align_frames.dy[frame_index])
650 y_high = min(self.frames.shape[0],
651 alignment_point['patch_y_high'] + self.align_frames.dy[
652 frame_index])
653 x_low = max(0,
654 alignment_point['patch_x_low'] + self.align_frames.dx[frame_index])
655 x_high = min(self.frames.shape[1],
656 alignment_point['patch_x_high'] + self.align_frames.dx[
657 frame_index])
658 # Compute the frame quality and append it to the list for this alignment point.
659 if self.configuration.frames_normalization:
660 alignment_point['frame_qualities'].append(
661 method(frame[y_low:y_high, x_low:x_high],
662 self.configuration.alignment_points_rank_pixel_stride) /
663 self.frames.average_brightness(frame_index))
664 else:
665 alignment_point['frame_qualities'].append(
666 method(frame[y_low:y_high, x_low:x_high],
667 self.configuration.alignment_points_rank_pixel_stride))
668 else:
669 # Sampled-down Laplacians of all blurred frames have been computed in
670 # "frames.frames_mono_blurred_laplacian". Cut out boxes around alignment points from
671 # those objects, rather than computing new Laplacians. Cycle through all frames and
672 # alignment points. Use the blurred monochrome image for ranking.
673 for frame_index in range(self.frames.number):
674 frame = self.frames.frames_mono_blurred_laplacian(frame_index)
675
676 # After every "signal_step_size"th frame, send a progress signal to the main GUI.
677 if self.progress_signal is not None and frame_index % self.signal_step_size == 1:
678 self.progress_signal.emit("Rank frames at APs",
679 int(round(10 * frame_index / self.signal_loop_length) * 10))
680
681 for ap_index, alignment_point in enumerate(self.alignment_points):
682 # Compute patch bounds within the current frame.
683 y_low = int(max(0, alignment_point['patch_y_low'] + self.align_frames.dy[
684 frame_index]) / self.configuration.align_frames_sampling_stride)
685 y_high = int(min(self.frames.shape[0],
686 alignment_point['patch_y_high'] + self.align_frames.dy[
687 frame_index]) / self.configuration.align_frames_sampling_stride)
688 x_low = int(max(0, alignment_point['patch_x_low'] + self.align_frames.dx[
689 frame_index]) / self.configuration.align_frames_sampling_stride)
690 x_high = int(min(self.frames.shape[1],
691 alignment_point['patch_x_high'] + self.align_frames.dx[
692 frame_index]) / self.configuration.align_frames_sampling_stride)
693 # Compute the frame quality and append it to the list for this alignment point.
694 if self.configuration.frames_normalization:
695 alignment_point['frame_qualities'].append(
696 meanStdDev(frame[y_low:y_high, x_low:x_high])[1][0][0] /
697 self.frames.average_brightness(frame_index))
698 else:
699 alignment_point['frame_qualities'].append(
700 meanStdDev(frame[y_low:y_high, x_low:x_high])[1][0][0])
701
702 if self.progress_signal is not None:
703 self.progress_signal.emit("Rank frames at APs", 100)
704
705 # Initialize the alignment point lists for all frames.
706 self.frames.reset_alignment_point_lists()
707 # For each alignment point sort the computed quality ranks in descending order.
708 for alignment_point_index, alignment_point in enumerate(self.alignment_points):
709 # Truncate the list to the number of frames to be stacked for each alignmeent point.
710 alignment_point['best_frame_indices'] = sorted(range(len(alignment_point['frame_qualities'])),
711 key=alignment_point['frame_qualities'].__getitem__, reverse=True)[:self.stack_size]
712 # Add this alignment point to the AP lists of those frames where the AP is to be used.
713 for frame_index in alignment_point['best_frame_indices']:
714 self.frames.used_alignment_points[frame_index].append(alignment_point_index)
715
716 def compute_shift_alignment_point(self, frame_mono_blurred, frame_index, alignment_point_index,
717 de_warp=True, weight_matrix_first_phase=None,
718 subpixel_solve=False):
719 """
720 Compute the [y, x] pixel shift vector at a given alignment point relative to the mean frame.
721 Four different methods can be used to compute the shift values:
722 - a multilevel cross correlation algorithm (miscellaneous.multilevel_correlation). This
723 method was implemented after PSS had shown bad performance for planetary videos captured
724 with bad seeing. Pixel shifts can be computed with subpixel accuracy, as specified with
725 the parameter "subpixel_solve". This is needed for drizzling.
726 - a subpixel algorithm from "skimage.feature"
727 - a phase correlation algorithm (miscellaneous.translation)
728 - a local search algorithm (spiralling outwards), see method "search_local_match",
729 optionally with subpixel accuracy.
730 - a local search algorithm, based on steepest descent, see method
731 "search_local_match_gradient". This method is faster than the previous one, but it has no
732 subpixel option.
733
734 Be careful with the sign of the local shift values. For the first two methods, a positive
735 value means that the current frame has to be shifted in the positive coordinate direction
736 in order to make objects in the frame match with their counterparts in the reference frame.
737 In other words: If the shift is positive, an object in the current frame is at lower pixel
738 coordinates as compared to the reference. This is very counter-intuitive, but to make the
739 three methods consistent, the same approach was followed in the implementation of the third
740 method "search_local_match", contained in this module. There, a pixel box around an
741 alignment point in the current frame is moved until the content of the box matches with the
742 corresponding box in the reference frame. If at this point the box is shifted towards a
743 higher coordinate value, this value is returned with a negative sign as the local shift.
744
745 :param frame_mono_blurred: Gaussian-blurred version of the frame with index "frame_index"
746 :param frame_index: Index of the selected frame in the list of frames
747 :param alignment_point_index: Index of the selected alignment point
748 :param de_warp: If True, include local warp shift computation. If False, only apply
749 global frame shift.
750 :param weight_matrix_first_phase: This parameter is only used by the alignment method
751 "MultiLevelCorrelation". If not None it defines a
752 weighting array by which the cross correlation results are
753 multiplied before the maximum value is determined. The
754 size of this 2D array in each coordinate direction is that
755 of the reference_box_first_phase plus two times the first
756 phase search width.
757 :param subpixel_solve: Used only for alignment method "MultiLevelCorrelation". If True,
758 in the second phase the optimum is computed with sub-pixel accuracy
759 (i.e. the returned shifts are not integer). If False, shifts are
760 computed as integer values.
761
762 :return: [shift_y, shift_x], success with: [shift_y, shift_x]: Local shift vector
763 success: True, if computation successful; False, otherwise.
764 """
765
766 # Initialize the "success" return value.
767 success = True
768
769 alignment_point = self.alignment_points[alignment_point_index]
770 y_low = alignment_point['box_y_low']
771 y_high = alignment_point['box_y_high']
772 x_low = alignment_point['box_x_low']
773 x_high = alignment_point['box_x_high']
774
775 # The offsets dy and dx are caused by two effects: First, the mean frame is smaller
776 # than the original frames. It only contains their intersection. And second, because the
777 # given frame is globally shifted as compared to the mean frame.
778 dy = self.align_frames.dy[frame_index]
779 dx = self.align_frames.dx[frame_index]
780
781 if de_warp:
782 # Use a two-level algorithm based on (weighted) cross correlation. The user-supplied
783 # noise level parameter is used as the blurring factor for the first correlation phase.
784 if self.configuration.alignment_points_method == 'MultiLevelCorrelation':
785 shift_y_local_first_phase, shift_x_local_first_phase, success_first_phase, \
786 shift_y_local_second_phase, shift_x_local_second_phase, success_second_phase = \
787 Miscellaneous.multilevel_correlation(
788 alignment_point['reference_box_first_phase'],
789 frame_mono_blurred, self.configuration.frames_gauss_width,
790 alignment_point['reference_box_second_phase'],
791 y_low + dy, y_high + dy, x_low + dx, x_high + dx,
792 self.configuration.alignment_points_search_width,
793 weight_matrix_first_phase=weight_matrix_first_phase,
794 subpixel_solve=subpixel_solve)
795
796 # Compute the combined warp shifts from both phases.
797 shift_pixel = [shift_y_local_first_phase + shift_y_local_second_phase,
798 shift_x_local_first_phase + shift_x_local_second_phase]
799 success = success_second_phase
800
801 # Use subpixel registration from skimage.feature, with accuracy 1/10 pixels.
802 elif self.configuration.alignment_points_method == 'Subpixel':
803 # Cut out the alignment box from the given frame. Take into account the offsets
804 # explained above.
805 box_in_frame = frame_mono_blurred[y_low + dy:y_high + dy,
806 x_low + dx:x_high + dx]
807 # The following use of "phase_cross_correlation" replaces the original call to
808 # "register_translation" which seems not to be in the package anymore. If this
809 # replacement really works has not been tested.
810 shift_pixel, error, diffphase = phase_cross_correlation(
811 alignment_point['reference_box'], box_in_frame, upsample_factor=10)
812
813 # Use a simple phase shift computation (contained in module "miscellaneous").
814 elif self.configuration.alignment_points_method == 'CrossCorrelation':
815 # Cut out the alignment box from the given frame. Take into account the offsets
816 # explained above.
817 box_in_frame = frame_mono_blurred[y_low + dy:y_high + dy,
818 x_low + dx:x_high + dx]
819 shift_pixel = Miscellaneous.translation(alignment_point['reference_box'],
820 box_in_frame, box_in_frame.shape)
821
822 # Use a local search (see method "search_local_match" below.
823 elif self.configuration.alignment_points_method == 'RadialSearch':
824 shift_pixel, dev_r = Miscellaneous.search_local_match(alignment_point['reference_box'],
825 frame_mono_blurred, y_low + dy, y_high + dy, x_low + dx, x_high + dx,
826 self.configuration.alignment_points_search_width,
827 self.configuration.alignment_points_sampling_stride,
828 sub_pixel=self.configuration.alignment_points_local_search_subpixel)
829 # If a zero shift was returned after a search with radius>2, thie means that
830 # the search was not successfu.
831 success = len(dev_r)<=2 or shift_pixel!=[0, 0]
832
833 # Use the steepest descent search method.
834 elif self.configuration.alignment_points_method == 'SteepestDescent':
835 shift_pixel, dev_r = Miscellaneous.search_local_match_gradient(
836 alignment_point['reference_box'],
837 frame_mono_blurred, y_low + dy, y_high + dy, x_low + dx, x_high + dx,
838 self.configuration.alignment_points_search_width,
839 self.configuration.alignment_points_sampling_stride, self.dev_table)
840 success = len(dev_r)<=2 or shift_pixel!=[0, 0]
841 else:
842 raise NotSupportedError("The point shift computation method " +
843 self.configuration.alignment_points_method +
844 " is not implemented")
845
846 # Return the computed shift vector.
847 return shift_pixel, success
848 else:
849 # If no de-warping is computed, just return the zero vector.
850 return [0, 0], success
851
852 def show_alignment_points(self, image):
853 """
854 Create an RGB version of a monochrome image and insert red crosses at all alignment
855 point locations. Draw green alignment point boxes and white alignment point patches.
856
857 :return: 8-bit RGB image with annotations.
858 """
859
860 if len(image.shape) == 3:
861 color_image = image.astype(uint8)
862 else:
863 # Expand the monochrome reference frame to RGB
864 color_image = stack((image.astype(uint8),) * 3, -1)
865
866 # For all alignment boxes insert a color-coded cross.
867 cross_half_len = 5
868
869 for alignment_point in (self.alignment_points):
870 y_center = alignment_point['y']
871 x_center = alignment_point['x']
872 Miscellaneous.insert_cross(color_image, y_center,
873 x_center, cross_half_len, 'red')
874 box_y_low = max(alignment_point['box_y_low'], 0)
875 box_y_high = min(alignment_point['box_y_high'], image.shape[0]) - 1
876 box_x_low = max(alignment_point['box_x_low'], 0)
877 box_x_high = min(alignment_point['box_x_high'], image.shape[1]) - 1
878 for y in arange(box_y_low, box_y_high):
879 color_image[y, box_x_low] = [255, 255, 255]
880 color_image[y, box_x_high] = [255, 255, 255]
881 for x in arange(box_x_low, box_x_high):
882 color_image[box_y_low, x] = [255, 255, 255]
883 color_image[box_y_high, x] = [255, 255, 255]
884
885 patch_y_low = max(alignment_point['patch_y_low'], 0)
886 patch_y_high = min(alignment_point['patch_y_high'], image.shape[0]) - 1
887 patch_x_low = max(alignment_point['patch_x_low'], 0)
888 patch_x_high = min(alignment_point['patch_x_high'], image.shape[1]) - 1
889 for y in arange(patch_y_low, patch_y_high):
890 color_image[y, patch_x_low] = [0, int(
891 (255 + color_image[y, patch_x_low][1]) / 2.), 0]
892 color_image[y, patch_x_high] = [0, int(
893 (255 + color_image[y, patch_x_high][1]) / 2.), 0]
894 for x in arange(patch_x_low, patch_x_high):
895 color_image[patch_y_low, x] = [0, int(
896 (255 + color_image[patch_y_low, x][1]) / 2.), 0]
897 color_image[patch_y_high, x] = [0, int(
898 (255 + color_image[patch_y_high, x][1]) / 2.), 0]
899
900 return color_image
901
902
903 if __name__ == "__main__":
904 # Images can either be extracted from a video file or a batch of single photographs. Select
905 # the example for the test run.
906 type = 'video'
907 if type == 'image':
908 names = glob('Images/2012*.tif')
909 # names = glob.glob('Images/Moon_Tile-031*ap85_8b.tif')
910 # names = glob.glob('Images/Example-3*.jpg')
911 else:
912 names = 'Videos/short_video.avi'
913 print(names)
914
915 # Get configuration parameters.
916 configuration = Configuration()
917 configuration.initialize_configuration()
918 try:
919 frames = Frames(configuration, names, type=type)
920 print("Number of images read: " + str(frames.number))
921 print("Image shape: " + str(frames.shape))
922 except Error as e:
923 print("Error: " + e.message)
924 exit()
925
926 # Rank the frames by their overall local contrast.
927 rank_frames = RankFrames(frames, configuration)
928 start = time()
929 rank_frames.frame_score()
930 end = time()
931 print('Elapsed time in ranking images: {}'.format(end - start))
932 print("Index of maximum: " + str(rank_frames.frame_ranks_max_index))
933 print("Frame scores: " + str(rank_frames.frame_ranks))
934 print("Frame scores (sorted): " + str(
935 [rank_frames.frame_ranks[i] for i in rank_frames.quality_sorted_indices]))
936 print("Sorted index list: " + str(rank_frames.quality_sorted_indices))
937
938 # Initialize the frame alignment object.
939 align_frames = AlignFrames(frames, rank_frames, configuration)
940
941 if configuration.align_frames_mode == "Surface":
942 start = time()
943 # Select the local rectangular patch in the image where the L gradient is highest in both x
944 # and y direction. The scale factor specifies how much smaller the patch is compared to the
945 # whole image frame.
946 (y_low_opt, y_high_opt, x_low_opt, x_high_opt) = align_frames.compute_alignment_rect(
947 configuration.align_frames_rectangle_scale_factor)
948 end = time()
949 print('Elapsed time in computing optimal alignment rectangle: {}'.format(end - start))
950 print("optimal alignment rectangle, x_low: " + str(x_low_opt) + ", x_high: " + str(
951 x_high_opt) + ", y_low: " + str(y_low_opt) + ", y_high: " + str(y_high_opt))
952 reference_frame_with_alignment_points = frames.frames_mono(
953 align_frames.frame_ranks_max_index).copy()
954 reference_frame_with_alignment_points[y_low_opt,
955 x_low_opt:x_high_opt] = reference_frame_with_alignment_points[y_high_opt - 1,
956 x_low_opt:x_high_opt] = 255
957 reference_frame_with_alignment_points[y_low_opt:y_high_opt,
958 x_low_opt] = reference_frame_with_alignment_points[y_low_opt:y_high_opt,
959 x_high_opt - 1] = 255
960 # plt.imshow(reference_frame_with_alignment_points, cmap='Greys_r')
961 # plt.show()
962
963 # Align all frames globally relative to the frame with the highest score.
964 start = time()
965 align_frames.align_frames()
966 end = time()
967 print('Elapsed time in aligning all frames: {}'.format(end - start))
968 print("Frame shifts: " + str(align_frames.frame_shifts))
969 print("Intersection: " + str(align_frames.intersection_shape))
970
971 start = time()
972 # Compute the reference frame by averaging the best frames.
973 average = align_frames.average_frame()
974
975 # Initialize the AlignmentPoints object. This includes the computation of the average frame
976 # against which the alignment point shifts are measured.
977
978 alignment_points = AlignmentPoints(configuration, frames, rank_frames, align_frames)
979 end = time()
980 print('Elapsed time in computing reference frame: {}'.format(end - start))
981 print("Reference frame computed from the best " + str(
982 align_frames.average_frame_number) + " frames.")
983 # plt.imshow(align_frames.mean_frame, cmap='Greys_r')
984 # plt.show()
985
986 # Create alignment points, and show alignment point boxes and patches.
987 alignment_points.create_ap_grid()
988 print("Number of alignment points created: " + str(len(alignment_points.alignment_points)) +
989 ", number of dropped aps (dim): " + str(
990 alignment_points.alignment_points_dropped_dim) +
991 ", number of dropped aps (structure): " + str(
992 alignment_points.alignment_points_dropped_structure))
993 color_image = alignment_points.show_alignment_points(average)
994
995 plt.imshow(color_image)
996 plt.show()
997
998 # For each alignment point rank frames by their quality.
999 start = time()
1000 alignment_points.compute_frame_qualities()
1001 end = time()
1002 print('Elapsed time in ranking frames for every alignment point: {}'.format(end - start))
1003
1004 y_low = 490
1005 y_high = 570
1006 x_low = 880
1007 x_high = 960
1008 found_ap_list = alignment_points.find_alignment_points(y_low, y_high, x_low, x_high)
1009 print("Removing alignment points between bounds " + str(y_low) + " <= y <= " + str(y_high) +
1010 ", " + str(x_low) + " <= x <= " + str(x_high) + ":")
1011 for ap in found_ap_list:
1012 print("y: " + str(ap['y']) + ", x: " + str(ap['x']))
1013 alignment_points.remove_alignment_points(found_ap_list)
1014
1015 y_new = 530
1016 x_new = 920
1017 half_box_width_new = 40
1018 half_patch_width_new = 50
1019 num_pixels_y = average.shape[0]
1020 num_pixels_x = average.shape[1]
1021 alignment_points.alignment_points.append(
1022 alignment_points.new_alignment_point(y_new, x_new, False, False, False, False))
1023 print("Added alignment point at y: " + str(y_new) + ", x: " + str(x_new) + ", box size: "
1024 + str(2 * half_box_width_new) + ", patch size: " + str(2 * half_patch_width_new))
1025
1026 # Show updated alignment point boxes and patches.
1027 print("Number of alignment points created: " + str(len(alignment_points.alignment_points)) +
1028 ", number of dropped aps (dim): " + str(alignment_points.alignment_points_dropped_dim) +
1029 ", number of dropped aps (structure): " + str(
1030 alignment_points.alignment_points_dropped_structure))
1031 color_image = alignment_points.show_alignment_points(average)
1032
1033 plt.imshow(color_image)
1034 plt.show()