Debian Codegraph @

planetary_system_stacker/miscellaneous.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 datetime import datetime
24 from os import unlink
25 from sys import stdout
26 from time import time, sleep
27
28 from cv2 import CV_32F, Laplacian, VideoWriter_fourcc, VideoWriter, FONT_HERSHEY_SIMPLEX, LINE_AA, \
29 putText, GaussianBlur, cvtColor, COLOR_BGR2HSV, COLOR_HSV2BGR, BORDER_DEFAULT, meanStdDev,\
30 resize, matchTemplate, minMaxLoc, TM_CCORR_NORMED, bilateralFilter, INTER_CUBIC
31 from numpy import abs as np_abs
32 from numpy import diff, average, hypot, sqrt, unravel_index, argmax, zeros, arange, array, matmul, \
33 empty, argmin, stack, sin, uint8, float32, uint16, full
34 from math import exp
35 from numpy import min as np_min
36 from numpy.fft import fft2, ifft2
37 from numpy.linalg import solve
38 from scipy.ndimage import sobel
39
40 from exceptions import DivideByZeroError, ArgumentError, Error
41
42
43 class Miscellaneous(object):
44 """
45 This class provides static methods for various auxiliary purposes.
46
47 """
48
49 @staticmethod
50 def quality_measure(frame):
51 """
52 Measure the amount of structure in a rectangular frame in both coordinate directions and
53 return the minimum value.
54
55 :param frame: 2D image
56 :return: Measure for amount of local structure in the image (scalar)
57 """
58
59 # Compute for each point the local gradient in both coordinate directions.
60 dx = diff(frame)
61 dy = diff(frame, axis=0)
62
63 # Compute the sharpness per coordinate direction as the 1-norm of point values.
64 sharpness_x = average(np_abs(dx))
65 sharpness_y = average(np_abs(dy))
66
67 # Return the sharpness in the direction where it is minimal.
68 return min(sharpness_x, sharpness_y)
69
70 @staticmethod
71 def quality_measure_threshold(frame, black_threshold=40.):
72 """
73 This is an alternative method for computing the amount of local structure. Here the
74 summation only takes into account points where the luminosity exceeds a certain
75 threshold.
76
77 :param frame: 2D image
78 :param black_threshold: Threshold for points to be considered
79 :return:
80 """
81
82 sum_horizontal = abs((frame[:, 2:] - frame[:, :-2])[frame[:, 1:-1] > black_threshold]).sum()
83 sum_vertical = abs((frame[2:, :] - frame[:-2, :])[frame[1:-1, :] > black_threshold]).sum()
84
85 return min(sum_horizontal, sum_vertical)
86
87 @staticmethod
88 def quality_measure_threshold_weighted(frame, stride=2, black_threshold=40., min_fraction=0.7):
89 """
90 This is an alternative method for computing the amount of local structure. Here the
91 summation only takes into account points where the luminosity exceeds a certain
92 threshold. Additionally, if not too many points are discarded, the reduced sampling size is
93 compensated.
94
95 :param frame: 2D image
96 :param stride: Stride for gradient computation. For blurry images increase this value.
97 :param black_threshold: Threshold for points to be considered.
98 :param min_fraction: Minimum fraction of points to pass the threshold.
99 :return:
100 """
101
102 frame_size = frame.shape[0] * frame.shape[1]
103 stride_2 = 2 * stride
104
105 # Compute a mask for all pixels which are bright enough (to avoid background noise).
106 mask = frame > black_threshold
107 mask_fraction = mask.sum() / frame_size
108
109 # If most pixels are bright enough, compensate for different pixel counts.
110 if mask_fraction > min_fraction:
111 sum_horizontal = abs((frame[:, stride_2:] - frame[:, :-stride_2])[mask[:, stride:-stride]]).sum() / mask_fraction
112 sum_vertical = abs((frame[stride_2:, :] - frame[:-stride_2, :])[mask[stride:-stride, :]]).sum() / mask_fraction
113 # If many pixels are too dim, penalize this patch by not compensating for pixel count.
114 else:
115 sum_horizontal = abs((frame[:, stride_2:] - frame[:, :-stride_2])[mask[:, stride:-stride]]).sum()
116 sum_vertical = abs((frame[stride_2:, :] - frame[:-stride_2, :])[mask[stride:-stride, :]]).sum()
117
118 return min(sum_horizontal, sum_vertical)
119
120 @staticmethod
121 def local_contrast_laplace(frame, stride):
122 """
123 Measure the amount of structure in a rectangular frame in both coordinate directions and
124 return the minimum value. The discrete variance of the Laplacian is computed.
125
126 :param frame: 2D image
127 :param stride: Factor for down-sampling
128 :return: Measure for amount of local structure in the image (scalar)
129 """
130
131 # sharpness = sum(laplace(frame[::stride, ::stride])**2)
132 return meanStdDev(Laplacian(frame[::stride, ::stride], CV_32F))[1][0][0]
133
134 @staticmethod
135 def local_contrast_sobel(frame, stride):
136 """
137 Compute a measure for local contrast in an image using the Sobel method.
138
139 :param frame: 2D image
140 :param stride: Factor for down-sampling
141 :return: Overall sharpness measure (scalar)
142 """
143
144 frame_int32 = frame[::stride, ::stride].astype('int32')
145 dx = sobel(frame_int32, 0) # vertical derivative
146 dy = sobel(frame_int32, 1) # horizontal derivative
147 mag = hypot(dx, dy) # magnitude
148
149 return mag.sum(axis=0)
150
151 @staticmethod
152 def local_contrast(frame, stride):
153 """
154 Compute a measure for local contrast in an image based on local gradients. Down-sample the
155 image by factor "stride" before measuring the contrast.
156
157 :param frame: 2D image
158 :param stride: Factor for down-sampling
159 :return: Overall measure for local contrast (scalar)
160 """
161 frame_strided = frame[::stride, ::stride]
162
163 # Remove a row or column, respectively, to make the dx and dy arrays of the same shape.
164 dx = diff(frame_strided)[1:, :] # remove the first row
165 dy = diff(frame_strided, axis=0)[:, 1:] # remove the first column
166 dnorm = hypot(dx, dy)
167
168 return average(dnorm)
169
170 @staticmethod
171 def translation(frame_0, frame_1, shape):
172 """
173 Compute the translation vector of frame_1 relative to frame_0 using phase correlation.
174
175 :param frame_0: Reference frame
176 :param frame_1: Frame shifted slightly relative to frame_0
177 :param shape: Shape of frames
178 :return: [shift in y, shift in x] of frame_1 relative to frame_0. More precisely:
179 frame_1 must be shifted by this amount to register with frame_0.
180 """
181
182 # Compute the fast Fourier transforms of both frames.
183 f0 = fft2(frame_0)
184 f1 = fft2(frame_1)
185
186 # Compute the phase correlation. The resulting image has a bright peak at the pixel location
187 # which corresponds to the shift vector.
188 ir = abs(ifft2((f0 * f1.conjugate()) / (abs(f0) * abs(f1))))
189
190 # Compute the pixel coordinates of the image maximum.
191 ty, tx = unravel_index(argmax(ir), shape)
192
193 # Bring the shift values as close as possible to the coordinate origin.
194 if ty > shape[0] // 2:
195 ty -= shape[0]
196 if tx > shape[1] // 2:
197 tx -= shape[1]
198
199 return [ty, tx]
200
201 @staticmethod
202 def multilevel_correlation(reference_box_first_phase, frame_mono_blurred,
203 blurr_strength_first_phase, reference_box_second_phase,
204 y_low, y_high, x_low, x_high, search_width,
205 weight_matrix_first_phase=None, subpixel_solve=False):
206 """
207 Determine the local warp shift at an alignment point using a multi-level approach based on
208 normalized cross correlation. The first level uses a pixel grid which is coarser by a factor
209 of two in both coordinate directions. The second level uses the original pixel grid.
210 An additional noise reduction is applied on the first level as chosen by the corresponding
211 blurring parameter.
212
213 The global search width is split between the two phases: A fixed search width of 4 is used
214 in the second phase (only for local corrections). Therefore, a width of (search_width-4)
215 in each coordinate direction remains for the first phase.
216
217 In both phases it is determined if the optimum is attained on the border of the search
218 area. If so, the correlation is regarded as unsuccessful (because the real optimum may be
219 outside of the search area).
220
221 :param reference_box_first_phase: Image box with stride 2 around alignment point in the
222 locally sharpest frame. A Gaussian filter with strength
223 "blurr_strength_first_phase" has been applied.
224 :param frame_mono_blurred: Given frame (stride 1) for which the local shift at the alignment
225 point is to be computed. This is the Gaussian blurred version of
226 the monochrome frame as computed in class "frames".
227 :param blurr_strength_first_phase: Additional Gaussian blur strength to be applied to
228 images in the first phase.
229 :param reference_box_second_phase: Image box with stride 1 around alignment point in the
230 locally sharpest frame.
231
232 :param y_low: Lower y coordinate limit of box in given frame, taking into account the
233 global shift and the different sizes of the mean frame and the original
234 frames.
235 :param y_high: Upper y coordinate limit.
236 :param x_low: Lower x coordinate limit.
237 :param x_high: Upper x coordinate limit.
238 :param search_width: Maximum distance in y and x from origin of the search area. (See the
239 comment in the explanatory text above.)
240 :param weight_matrix_first_phase: This parameter (if not None) may give a weighting array
241 by which the cross correlation results are multiplied
242 before the maximum value is determined. The size of this
243 2D array in each coordinate direction is that of the
244 reference_box_first_phase plus two times the first phase
245 search width (see below).
246 :param subpixel_solve: If True, in the second phase the optimum is computed with
247 sub-pixel accuracy (i.e. the returned shifts are not integer).
248 If False, shifts are computed as integer values.
249
250 :return: (shift_y_local_first_phase, shift_x_local_first_phase, success_first_phase,
251 shift_y_local_second_phase, shift_x_local_second_phase, success_second_phase)
252 with:
253 shift_y_local_first_phase: Local y warp shift determined in first phase
254 (expressed in terms of the original pixel grid).
255 shift_x_local_first_phase: Local x warp shift determined in first phase.
256 success_first_phase: "True" if the optimum was attained in the interior of the
257 search domain. "False" otherwise.
258 shift_y_local_second_phase: Local y warp shift determined in second phase.
259 shift_x_local_second_phase: Local x warp shift determined in second phase.
260 success_second_phase: "True" if the optimum was attained in the interior of the
261 search domain. "False" otherwise.
262 """
263
264 # The optimization in the second phase is only meant for local fine grid adjustments.
265 search_width_second_phase = 4
266
267 # In the first phase the largest part of the local warp is detected. Divide the search
268 # width by two because the first phase uses a coarser pixel grid.
269 search_width_first_phase = int((search_width - search_width_second_phase) / 2)
270
271 # Define a window around the alignment point box. Extend the window in each coordinate
272 # direction. This defines the search space for the template matching. Coarsen the grid
273 # by a factor of two and apply an additional Gaussian blur.
274 index_extension = search_width_first_phase * 2
275 frame_window_first_phase = GaussianBlur(frame_mono_blurred[
276 y_low - index_extension:y_high + index_extension:2,
277 x_low - index_extension:x_high + index_extension:2],
278 (blurr_strength_first_phase,
279 blurr_strength_first_phase), 0)
280
281 # Compute the normalized cross correlation.
282 result = matchTemplate((frame_window_first_phase).astype(float32),
283 reference_box_first_phase.astype(float32), TM_CCORR_NORMED)
284
285 # Determine the position of the maximum correlation and compute the corresponding warp
286 # shift. The factor of 2 transforms the shift to the fine pixel grid. If a non-trivial
287 # weight matrix is specified, multiply the results before looking for the maximum position.
288 if weight_matrix_first_phase is not None:
289 minVal, maxVal, minLoc, maxLoc = minMaxLoc(result * weight_matrix_first_phase)
290 else:
291 minVal, maxVal, minLoc, maxLoc = minMaxLoc(result)
292 shift_y_local_first_phase = (search_width_first_phase - maxLoc[1]) * 2
293 shift_x_local_first_phase = (search_width_first_phase - maxLoc[0]) * 2
294
295 # The first phase is regarded as successful if the maximum correlation was attained in the
296 # interior of the search space.
297 success_first_phase = abs(shift_y_local_first_phase) != index_extension and abs(
298 shift_x_local_first_phase) != index_extension
299
300 # If the first phase was successful, add a second phase with a local search on the finest
301 # (original) pixel grid.
302 if success_first_phase:
303
304 # Define the search window for the second phase. Apply the shift found in the
305 # first phase.
306 y_lo = y_low - shift_y_local_first_phase - search_width_second_phase
307 y_hi = y_high - shift_y_local_first_phase + search_width_second_phase
308 x_lo = x_low - shift_x_local_first_phase - search_width_second_phase
309 x_hi = x_high - shift_x_local_first_phase + search_width_second_phase
310
311 # Cut out the frame window for the second phase (fine grid) correlation.
312 frame_window_second_phase = frame_mono_blurred[y_lo:y_hi, x_lo:x_hi]
313
314 # Perform the template matching on the fine grid, again using normalized cross
315 # correlation.
316 result = matchTemplate(frame_window_second_phase.astype(float32),
317 reference_box_second_phase, TM_CCORR_NORMED)
318
319 # Find the position of the local optimum and compute the corresponding shift values.
320 minVal, maxVal, minLoc, maxLoc = minMaxLoc(result)
321 shift_y_local_second_phase = search_width_second_phase - maxLoc[1]
322 shift_x_local_second_phase = search_width_second_phase - maxLoc[0]
323
324 # Again, the second phase is deemed successful only if the optimum was attained in the
325 # interior of the search space.
326 success_second_phase = abs(
327 shift_y_local_second_phase) != search_width_second_phase and abs(
328 shift_x_local_second_phase) != search_width_second_phase
329
330 # If the second phase was not successful, set the corresponding shifts to zero.
331 if not success_second_phase:
332 shift_y_local_second_phase = shift_x_local_second_phase = 0
333 # The following code computes the sub-pixel shift correction to be used in drizzling.
334 elif subpixel_solve:
335 # Cut a 3x3 window around the optimum from the matching results.
336 surroundings = result[maxLoc[1]-1:maxLoc[1]+2, maxLoc[0]-1:maxLoc[0]+2]
337 try:
338 # Compute the correction to the center position. Only if the found sub-pixel
339 # correction is within the 3x3 box, it is trusted (and used).
340 y_corr, x_corr = Miscellaneous.sub_pixel_solve(surroundings)
341 if abs(y_corr) <= 1. and abs(x_corr) <= 1.:
342 shift_y_local_second_phase -= y_corr
343 shift_x_local_second_phase -= x_corr
344 except:
345 # print ("Subpixel solve not successful")
346 pass
347
348 # If the first phase was unsuccessful, drop the second phase and set all warp shifts to 0.
349 else:
350 success_second_phase = False
351 shift_y_local_first_phase = shift_x_local_first_phase = shift_y_local_second_phase = \
352 shift_x_local_second_phase = 0
353
354 return shift_y_local_first_phase, shift_x_local_first_phase, success_first_phase, \
355 shift_y_local_second_phase, shift_x_local_second_phase, success_second_phase
356
357 @staticmethod
358 def search_local_match(reference_box, frame, y_low, y_high, x_low, x_high, search_width,
359 sampling_stride, sub_pixel=True):
360 """
361 Try shifts in y, x between the box around the alignment point in the mean frame and the
362 corresponding box in the given frame. Start with shifts [0, 0] and move out in a circular
363 fashion, until the radius "search_width" is reached. The global frame shift is accounted for
364 beforehand already.
365
366 :param reference_box: Image box around alignment point in mean frame.
367 :param frame: Given frame for which the local shift at the alignment point is to be
368 computed.
369 :param y_low: Lower y coordinate limit of box in given frame, taking into account the
370 global shift and the different sizes of the mean frame and the original
371 frames.
372 :param y_high: Upper y coordinate limit
373 :param x_low: Lower x coordinate limit
374 :param x_high: Upper x coordinate limit
375 :param search_width: Maximum radius of the search spiral
376 :param sampling_stride: Stride in both coordinate directions used in computing deviations
377 :param sub_pixel: If True, compute local shifts with sub-pixel accuracy
378 :return: ([shift_y, shift_x], [min_r]) with:
379 shift_y, shift_x: shift values of minimum or [0, 0] if no optimum could be found.
380 [dev_r]: list of minimum deviations for radius r=0 ... r_max, where r_max is the
381 widest search radius tested.
382 """
383
384 # Initialize the global optimum with an impossibly large value.
385 deviation_min = 1.e30
386 dy_min = None
387 dx_min = None
388
389 # Initialize list of minimum deviations for each search radius and field of deviations.
390 dev_r = []
391 deviations = zeros((2 * search_width + 1, 2 * search_width + 1))
392
393 # Start with shift [0, 0] and proceed in a circular pattern.
394 for r in arange(search_width + 1):
395
396 # Create an enumerator which produces shift values [dy, dx] in a circular pattern
397 # with radius "r".
398 circle_r = Miscellaneous.circle_around(0, 0, r)
399
400 # Initialize the optimum for radius "r" to an impossibly large value,
401 # and the corresponding shifts to None.
402 deviation_min_r, dy_min_r, dx_min_r = 1.e30, None, None
403
404 # Go through the circle with radius "r" and compute the difference (deviation)
405 # between the shifted frame and the corresponding box in the mean frame. Find the
406 # minimum "deviation_min_r" for radius "r".
407 if sampling_stride != 1:
408 for (dy, dx) in circle_r:
409 deviation = abs(
410 reference_box[::sampling_stride, ::sampling_stride] - frame[
411 y_low - dy:y_high - dy:sampling_stride,
412 x_low - dx:x_high - dx:sampling_stride]).sum()
413 # deviation = sqrt(square(
414 # reference_box - frame[y_low - dy:y_high - dy, x_low - dx:x_high - dx]).sum())
415 if deviation < deviation_min_r:
416 deviation_min_r, dy_min_r, dx_min_r = deviation, dy, dx
417 deviations[dy + search_width, dx + search_width] = deviation
418 else:
419 for (dy, dx) in circle_r:
420 deviation = abs(
421 reference_box - frame[y_low - dy:y_high - dy, x_low - dx:x_high - dx]).sum()
422 if deviation < deviation_min_r:
423 deviation_min_r, dy_min_r, dx_min_r = deviation, dy, dx
424 deviations[dy + search_width, dx + search_width] = deviation
425
426 # Append the minimal deviation for radius r to list of minima.
427 dev_r.append(deviation_min_r)
428
429 # If for the current radius there is no improvement compared to the previous radius,
430 # the optimum is reached.
431 if deviation_min_r >= deviation_min:
432
433 # For sub-pixel accuracy, find local minimum of fitting paraboloid.
434 if sub_pixel:
435 try:
436 y_correction, x_correction = Miscellaneous.sub_pixel_solve(deviations[
437 dy_min + search_width - 1: dy_min + search_width + 2,
438 dx_min + search_width - 1: dx_min + search_width + 2])
439 except DivideByZeroError as ex:
440 print(ex.message)
441 x_correction = y_correction = 0.
442
443 # Add the sub-pixel correction to the local shift. If the correction is above
444 # one pixel, something went wrong.
445 if abs(y_correction) < 1. and abs(x_correction) < 1.:
446 dy_min += y_correction
447 dx_min += x_correction
448 # else:
449 # print ("y_correction: " + str(y_correction) + ", x_correction: " +
450 # str(x_correction))
451
452 return [dy_min, dx_min], dev_r
453
454 # Otherwise, update the current optimum and continue.
455 else:
456 deviation_min, dy_min, dx_min = deviation_min_r, dy_min_r, dx_min_r
457
458 # If within the maximum search radius no optimum could be found, return [0, 0].
459 return [0, 0], dev_r
460
461 # Define the matrix used in method "sub_pixel_solve" to solve the normal equations. It is
462 # computed once and for all as "inv(a_transpose * a) * a_transpose". Using this matrix, the
463 # solution of the normal equations is reduced to a simple matrix multiplication.
464 sub_pixel_solve_matrix = [
465 [0.16666667, -0.33333333, 0.16666667, 0.16666667, -0.33333333, 0.16666667, 0.16666667,
466 -0.33333333, 0.16666667],
467 [0.16666667, 0.16666667, 0.16666667, -0.33333333, -0.33333333, -0.33333333, 0.16666667,
468 0.16666667, 0.16666667], [0.25, 0., -0.25, 0., 0., 0., -0.25, 0., 0.25],
469 [-0.16666667, 0., 0.16666667, -0.16666667, 0., 0.16666667, -0.16666667, 0., 0.16666667],
470 [-0.16666667, -0.16666667, -0.16666667, 0., 0., 0., 0.16666667, 0.16666667, 0.16666667],
471 [-0.11111111, 0.22222222, -0.11111111, 0.22222222, 0.55555556, 0.22222222, -0.11111111,
472 0.22222222, -0.11111111]]
473
474 @staticmethod
475 def sub_pixel_solve(function_values):
476 """
477 Compute the sub-pixel correction for method "search_local_match".
478
479 :param function_values: Matching differences at (3 x 3) pixels around the minimum / maximum
480 found
481 :return: Corrections in y and x to the center position for local minimum / maximum
482 """
483
484 # If the functions are not yet reduced to 1D, do it now.
485 function_values_1d = function_values.reshape((9,))
486
487 # Solve for parameters of the fitting function:
488 # f = a_f * x ** 2 + b_f * y ** 2 + c_f * x * y + d_f * x + e_f * y + g_f
489 # using normal equations. The problem is reduced to a matrix multiplication with the fixed
490 # system matrix defined above.
491 a_f, b_f, c_f, d_f, e_f, g_f = matmul(Miscellaneous.sub_pixel_solve_matrix, function_values_1d)
492 # print("\nSolve, coeffs: " + str((a_f, b_f, c_f, d_f, e_f, g_f)))
493
494 # The corrected pixel values of the minimum result from setting the first derivatives of
495 # the fitting funtion in y and x direction to zero, and solving for y and x.
496 denominator_y = c_f ** 2 - 4. * a_f * b_f
497 if abs(denominator_y) > 1.e-10 and abs(a_f) > 1.e-10:
498 y_correction = (2. * a_f * e_f - c_f * d_f) / denominator_y
499 x_correction = (- c_f * y_correction - d_f) / (2. * a_f)
500 elif abs(denominator_y) > 1.e-10 and abs(c_f) > 1.e-10:
501 y_correction = (2. * a_f * e_f - c_f * d_f) / denominator_y
502 x_correction = (-2. * b_f * y_correction - e_f) / c_f
503 else:
504 raise DivideByZeroError("Sub-pixel shift cannot be computed, set to zero")
505
506 return y_correction, x_correction
507
508 @staticmethod
509 def sub_pixel_solve_old(function_values):
510 """
511 Compute the sub-pixel correction for method "search_local_match".
512
513 :param function_values: Matching differences at (3 x 3) pixels around the minimum found
514 :return: Corrections in y and x to the center position for local minimum
515 """
516
517 # If the functions are not yet reduced to 1D, do it now.
518 function_values_1d = function_values.reshape((9,))
519
520 # There are nine equations for six unknowns. Use normal equations to solve for optimum.
521 a_transpose = array(
522 [[1., 0., 1., 1., 0., 1., 1., 0., 1.], [1., 1., 1., 0., 0., 0., 1., 1., 1.],
523 [1., -0., -1., -0., 0., 0., -1., 0., 1.], [-1., 0., 1., -1., 0., 1., -1., 0., 1.],
524 [-1., -1., -1., 0., 0., 0., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1.]])
525 a_transpose_a = array(
526 [[6., 4., 0., 0., 0., 6.], [4., 6., 0., 0., 0., 6.], [0., 0., 4., 0., 0., 0.],
527 [0., 0., 0., 6., 0., 0.], [0., 0., 0., 0., 6., 0.], [6., 6., 0., 0., 0., 9.]])
528
529 # Right hand side is "a transposed times input vector".
530 rhs = matmul(a_transpose, function_values_1d)
531
532 # Solve for parameters of the fitting function
533 # f = a_f * x ** 2 + b_f * y ** 2 + c_f * x * y + d_f * x + e_f * y + g_f
534 a_f, b_f, c_f, d_f, e_f, g_f = solve(a_transpose_a, rhs)
535
536 # The corrected pixel values of the minimum result from setting the first derivatives of
537 # the fitting funtion in y and x direction to zero, and solving for y and x.
538 denominator_y = c_f ** 2 - 4. * a_f * b_f
539 if abs(denominator_y) > 1.e-10 and abs(a_f) > 1.e-10:
540 y_correction = (2. * a_f * e_f - c_f * d_f) / denominator_y
541 x_correction = (- c_f * y_correction - d_f) / (2. * a_f)
542 elif abs(denominator_y) > 1.e-10 and abs(c_f) > 1.e-10:
543 y_correction = (2. * a_f * e_f - c_f * d_f) / denominator_y
544 x_correction = (-2. * b_f * y_correction - e_f) / c_f
545 else:
546 raise DivideByZeroError("Sub-pixel shift cannot be computed, set to zero")
547
548 return y_correction, x_correction
549
550 @staticmethod
551 def search_local_match_init(reference_frame, y_low, y_high, x_low, x_high, search_width):
552 """
553 As an alternative to the method "search_local_match" above there is a split version
554 consisting of this initialization method and the execution method. For a given alignment
555 point the initialization has to be called once only. The data structures allocated during
556 initialization are re-used with each frame for which the shift against the reference frame
557 is to be computed. The individual frame shift is computed with the execution method below.
558
559 The split version can be better suited for execution on a graphic accelerator. The biggest
560 part of the data does not change between frame executions, so it has to be copied to the
561 graphics memory only once. The executions for individual frames only need little additional
562 data, and they can be performed in parallel.
563
564 The split version is not available with subpixel accuracy.
565
566 :param reference_frame: Reference frame, against which the current frame shift is to be
567 computed (note: The full frame, not the alignment box)
568 :param y_low: Lower y coordinate limit of alignment box in reference frame
569 :param y_high: Upper y coordinate limit of alignment box in reference frame
570 :param x_low: Lower x coordinate limit of alignment box in reference frame
571 :param x_high: Upper x coordinate limit of alignment box in reference frame
572 :param search_width: Maximum radius of the search spiral
573 :return: (reference_stack, displacements, radius_start) witn
574 reference_stack: Stack of shifted reference frame alignment boxes
575 displacements: List of [dy, dx] displacements for all stack elements
576 radius_start: Start indices into "reference_stack" and "displacements" for each
577 radius (from 0 to search_width)
578 """
579 # Compute the maximal number of shifts to be tested.
580 search_dim = (2*search_width+1)**2
581
582 # Allocate permanent data structures.
583 window_height = y_high - y_low
584 window_width = x_high - x_low
585 reference_stack = empty([search_dim, window_height, window_width],
586 dtype=reference_frame.dtype)
587 displacements = []
588 radius_start = [0]
589
590 # Create the reference_stack containing shifted windows into the reference frame.
591 index = 0
592 for r in range(search_width + 1):
593 # Create an enumerator which produces shift values [dy, dx] in a circular pattern
594 # with radius "r".
595 for (dy, dx) in Miscellaneous.circle_around(0, 0, r):
596 reference_stack[index, :, :] = reference_frame[y_low + dy:y_high + dy,
597 x_low + dx:x_high + dx]
598 displacements.append([dy, dx])
599 index += 1
600 radius_start.append(index)
601 return (reference_stack, displacements, radius_start)
602
603 @staticmethod
604 def search_local_match_execute(frame_window, reference_stack, displacements, radius_start):
605 """
606 The "execute" method of the split version of "search_local_match". This method is executed
607 for each frame, potentially in parallel for all frames.
608
609 :param frame_window: Window into the current frame of the same shape as specified for the
610 reference window in the init method. Be careful: the current frame and
611 the reference frame have different shapes.
612 :param reference_stack: Permanent object allocated by init routing (see above)
613 :param displacements: Permanent object allocated by init routing (see above)
614 :param radius_start: Permanent object allocated by init routing (see above)
615 :return: ([shift_y, shift_x], [min_r]) with:
616 shift_y, shift_x: shift values of minimum or [0, 0] if no optimum could be found.
617 [dev_r]: list of minimum deviations for radius r=0 ... r_max, where r_max is the
618 widest search radius tested.
619 """
620
621 search_width_plus_1 = len(radius_start)
622 # Initialize the global optimum with an impossibly large value.
623 deviation_min = 1.e30
624 index_min = None
625
626 # Initialize list of minimum deviations for each search radius and field of deviations.
627 dev_r = []
628
629 # Compare frame_window with a stack of shifted reference frame windows stored for radius r.
630 for r in arange(search_width_plus_1):
631 temp_vec = abs(
632 reference_stack[radius_start[r]:radius_start[r + 1], :, :] - frame_window).sum(
633 axis=(1, 2))
634 deviation_min_r = np_min(temp_vec)
635 index_min_r = argmin(temp_vec) + radius_start[r]
636
637 # The same in loop notation:
638 #
639 # deviation_min_r, index_min_r = 1.e30, None
640 # for index in arange(radius_start[r], radius_start[r+1]):
641 # deviation = abs(reference_stack[index, :,:] - frame_window).sum()
642 # if deviation < deviation_min_r:
643 # deviation_min_r = deviation
644 # index_min_r = index
645
646 # Append the minimal deviation for radius r to list of minima.
647 dev_r.append(deviation_min_r)
648
649 if deviation_min_r >= deviation_min:
650 return displacements[index_min], dev_r
651
652 # Otherwise, update the current optimum and continue.
653 else:
654 deviation_min = deviation_min_r
655 index_min = index_min_r
656
657 # If within the maximum search radius no optimum could be found, return [0, 0].
658 return [0, 0], dev_r
659
660 @staticmethod
661 def search_local_match_gradient(reference_box, frame, y_low, y_high, x_low, x_high, search_width,
662 sampling_stride, dev_table):
663 """
664 Try shifts in y, x between the box around the alignment point in the mean frame and the
665 corresponding box in the given frame. Start with shifts [0, 0] and move out in steps until
666 a local optimum is reached. In each step try all positions with distance 1 in y and/or x
667 from the optimum found in the previous step (steepest descent). The global frame shift is
668 accounted for beforehand already.
669
670 :param reference_box: Image box around alignment point in mean frame.
671 :param frame: Given frame for which the local shift at the alignment point is to be
672 computed.
673 :param y_low: Lower y coordinate limit of box in given frame, taking into account the
674 global shift and the different sizes of the mean frame and the original
675 frames.
676 :param y_high: Upper y coordinate limit
677 :param x_low: Lower x coordinate limit
678 :param x_high: Upper x coordinate limit
679 :param search_width: Maximum distance in y and x from origin of the search area
680 :param sampling_stride: Stride in both coordinate directions used in computing deviations
681 :param dev_table: Scratch table to be used internally for storing intermediate results,
682 size: [2*search_width, 2*search_width], dtype=float32.
683 :return: ([shift_y, shift_x], [min_r]) with:
684 shift_y, shift_x: shift values of minimum or [0, 0] if no optimum could be found.
685 [dev_r]: list of minimum deviations for all steps until a local minimum is found.
686 """
687
688 # Set up a table which keeps deviation values from earlier iteration steps. This way,
689 # deviation evaluations can be avoided at coordinates which have been visited before.
690 # Initialize deviations with an impossibly high value.
691 dev_table[:, :] = 1.e30
692
693 # Initialize the global optimum with the value at dy=dx=0.
694 if sampling_stride != 1:
695 deviation_min = abs(reference_box[::sampling_stride, ::sampling_stride] - frame[
696 y_low:y_high:sampling_stride,
697 x_low:x_high:sampling_stride]).sum()
698 else:
699 deviation_min = abs(reference_box - frame[y_low:y_high, x_low:x_high]).sum()
700 dev_table[0, 0] = deviation_min
701 dy_min = 0
702 dx_min = 0
703
704 counter_new = 0
705 counter_reused = 0
706
707 # Initialize list of minimum deviations for each search radius.
708 dev_r = [deviation_min]
709
710 # Start with shift [0, 0]. Stop when a circle with radius 1 around the current optimum
711 # reaches beyond the search area.
712 while max(abs(dy_min), abs(dx_min)) < search_width-1:
713
714 # Create an enumerator which produces shift values [dy, dx] in a circular pattern
715 # with radius 1 around the current optimum [dy_min, dx_min].
716 circle_1 = Miscellaneous.circle_around(dy_min, dx_min, 1)
717
718 # Initialize the optimum for the new circle to an impossibly large value,
719 # and the corresponding shifts to None.
720 deviation_min_1, dy_min_1, dx_min_1 = 1.e30, None, None
721
722 # Go through the circle with radius 1 and compute the difference (deviation)
723 # between the shifted frame and the corresponding box in the mean frame. Find the
724 # minimum "deviation_min_1".
725 if sampling_stride != 1:
726 for (dy, dx) in circle_1:
727 deviation = dev_table[dy, dx]
728 if deviation > 1.e29:
729 counter_new += 1
730 deviation = abs(reference_box[::sampling_stride, ::sampling_stride] - frame[
731 y_low - dy:y_high - dy:sampling_stride,
732 x_low - dx:x_high - dx:sampling_stride]).sum()
733 dev_table[dy, dx] = deviation
734 else:
735 counter_reused += 1
736 if deviation < deviation_min_1:
737 deviation_min_1, dy_min_1, dx_min_1 = deviation, dy, dx
738
739 # deviation = abs(reference_box[::sampling_stride, ::sampling_stride] - frame[
740 # y_low - dy:y_high - dy:sampling_stride,
741 # x_low - dx:x_high - dx:sampling_stride]).sum()
742 # if deviation < deviation_min_1:
743 # deviation_min_1, dy_min_1, dx_min_1 = deviation, dy, dx
744 else:
745 for (dy, dx) in circle_1:
746 deviation = dev_table[dy, dx]
747 if deviation > 1.e29:
748 deviation = abs(
749 reference_box - frame[y_low - dy:y_high - dy,
750 x_low - dx:x_high - dx]).sum()
751 dev_table[dy, dx] = deviation
752 if deviation < deviation_min_1:
753 deviation_min_1, dy_min_1, dx_min_1 = deviation, dy, dx
754
755 # Append the minimal deviation found in this step to list of minima.
756 dev_r.append(deviation_min_1)
757
758 # If for the current center the match is better than for all neighboring points, a
759 # local optimum is found.
760 if deviation_min_1 >= deviation_min:
761 # print ("new: " + str(counter_new) + ", reused: " + str(counter_reused))
762 return [dy_min, dx_min], dev_r
763
764 # Otherwise, update the current optimum and continue.
765 else:
766 deviation_min, dy_min, dx_min = deviation_min_1, dy_min_1, dx_min_1
767
768 # If within the maximum search radius no optimum could be found, return [0, 0].
769 return [0, 0], dev_r
770
771 @staticmethod
772 def search_local_match_full(reference_box, frame, y_low, y_high, x_low, x_high,
773 search_width,
774 sampling_stride, dev_table):
775 """
776 For all shifts with -search_width < shift < search_width in y, x between the box around the
777 alignment point in the mean frame and the corresponding box in the given frame compute the
778 deviation. Return the y and x offsets where the deviation is smallest. The global frame
779 shift is accounted for beforehand already.
780
781 :param reference_box: Image box around alignment point in mean frame.
782 :param frame: Given frame for which the local shift at the alignment point is to be
783 computed.
784 :param y_low: Lower y coordinate limit of box in given frame, taking into account the
785 global shift and the different sizes of the mean frame and the original
786 frames.
787 :param y_high: Upper y coordinate limit
788 :param x_low: Lower x coordinate limit
789 :param x_high: Upper x coordinate limit
790 :param search_width: Maximum distance in y and x from origin of the search area
791 :param sampling_stride: Stride in both coordinate directions used in computing deviations
792 :param dev_table: Scratch table to be used internally for storing intermediate results,
793 size: [2*search_width+1, 2*search_width+1], dtype=float32.
794 :return: ([shift_y, shift_x], [min_r]) with:
795 shift_y, shift_x: shift values of minimum or [0, 0] if no optimum could be found.
796 [dev_r]: list of minimum deviations for all steps until a local minimum is found.
797 """
798
799 # Set up a table which keeps deviation values from earlier iteration steps. This way,
800 # deviation evaluations can be avoided at coordinates which have been visited before.
801 # Initialize deviations with an impossibly high value.
802 dev_table[:, :] = 1.e30
803
804 if sampling_stride != 1:
805 for dy in range(-search_width, search_width + 1):
806 for dx in range(-search_width, search_width + 1):
807 dev_table[search_width + dy, search_width + dx] = abs(
808 reference_box[::sampling_stride, ::sampling_stride] - frame[
809 y_low - dy:y_high - dy:sampling_stride,
810 x_low - dx:x_high - dx:sampling_stride]).sum()
811 else:
812 for dy in range(-search_width, search_width + 1):
813 for dx in range(-search_width, search_width + 1):
814 dev_table[search_width + dy, search_width + dx] = abs(
815 reference_box - frame[y_low - dy:y_high - dy, x_low - dx:x_high - dx]).sum()
816
817 dy, dx = unravel_index(argmin(dev_table, axis=None), dev_table.shape)
818
819 # Return the coordinate shifts for the minimum position and the value at that position.
820 return [dy-search_width, dx-search_width], dev_table[dy, dx]
821
822 @staticmethod
823 def auto_rgb_align(input_image, max_shift, interpolation_factor=1, reduce_output=True,
824 blur_strength=None):
825 """
826 Align the three color channels of an RGB image automatically. For sub-pixel resolution the
827 image can be interpolated before the shift is measured. Optionally, a Gaussian blur can be
828 added to suppress noise.
829
830 If no matching shift can be found within the range given by "max_shift", an Exception of
831 type Error is thrown.
832
833 :param input_image: Three-channel RGB image.
834 :param max_shift: Maximal displacement between channels.
835 :param interpolation_factor: Scaling factor (integer) for subpixel measurements.
836 :param reduce_output: If True, the corrected image is reduced to the input resolution.
837 If False, it stays at the interpolated resolution. In this case the
838 output values for correction_red and correction_blue are in terms of
839 the interpolated resolution as well.
840 :param blur_strength: Optional blur strength, must be an uneven integer > 0.
841 :return: (corrected_image, correction_red, correction_blue) with:
842 corrected_image: The corrected image with the same datatype as the input image.
843 Please note that the size may be reduced because of channel
844 mismatch at the borders.
845 correction_red: Tuple (shift_y, shift_x) with coordinate shifts in y and x
846 applied to the red channel of input_image to produce the
847 corrected_image.
848 correction_blue: Tuple (shift_y, shift_x) with coordinate shifts in y and x
849 applied to the blue channel of input_image to produce the
850 corrected_image.
851 """
852
853 # sleep(2.)
854 # Immediately return for monochrome input.
855 if len(input_image.shape) != 3:
856 return input_image
857
858 # If subpixel resolution is asked for, interpolate the input image first.
859 if interpolation_factor != 1:
860 input_interpolated = Miscellaneous.shift_colors(input_image, (0, 0), (0, 0),
861 interpolate_input=interpolation_factor)
862 else:
863 input_interpolated = input_image
864
865 # Measure the shifts of the red and blue channels, respectively, with respect to the green
866 # channel.
867 channel_green = 1
868 channel_red = 0
869 shift_red = Miscellaneous.measure_rgb_shift(input_interpolated, channel_red,
870 channel_green, max_shift * interpolation_factor,
871 blur_strength=blur_strength)
872 channel_blue = 2
873 shift_blue = Miscellaneous.measure_rgb_shift(input_interpolated, channel_blue,
874 channel_green, max_shift*interpolation_factor,
875 blur_strength=blur_strength)
876
877 # Reverse the shift measured in the input image.
878 if reduce_output:
879 factor = interpolation_factor
880 else:
881 factor = 1
882 return Miscellaneous.shift_colors(input_interpolated, (-shift_red[0], -shift_red[1]),
883 (-shift_blue[0], -shift_blue[1]), reduce_output=factor), \
884 (-shift_red[0]/factor, -shift_red[1]/factor), \
885 (-shift_blue[0]/factor, -shift_blue[1]/factor)
886
887
888 @staticmethod
889 def shift_colors(input_image, shift_red, shift_blue, interpolate_input=1, reduce_output=1):
890 """
891 Shift the red and blue channel of a color image in y and x direction, and leave the green
892 channel unchanged. The shift is sub-pixel accurate if the input is interpolated. Optionally
893 the resulting image is reduced in size by a given factor.
894
895 :param input_image: Three-channel RGB image.
896 :param shift_red: Tuple (shift_y, shift_x) with shifts in y and x direction for the red
897 channel. After multiplication with the interpolate_input factor (if given)
898 the shifts are rounded to the next integer value. This enables sub-pixel
899 shifts at the original image scale.
900 :param shift_blue: Tuple (shift_y, shift_x) with shifts in y and x direction for the blue
901 channel.
902 :param interpolate_input: If set, it must be an integer >= 1. The input image is
903 interpolated in both directions by this factor before the shift is
904 applied.
905 :param reduce_output: If set, it must be an integer >= 1. The intermediate image is reduced
906 in size by this factor. Please note that interpolate_input =
907 reduce_output assures that the input and output images are the same
908 size.
909 :return: Three-channel RGB image with the color shifts applied.
910 """
911
912 # sleep(1.)
913 # Immediately return for monochrome input.
914 if len(input_image.shape) != 3:
915 return input_image
916
917 # If all shifts are zero, nothing is to be done except interpolation / reduction.
918 if not (shift_red[0] or shift_red[1] or shift_blue[0] or shift_blue[1]):
919 # If the factors for interpolation and reduction are the same, nothing is to be done.
920 if not (interpolate_input - reduce_output) or not reduce_output:
921 return input_image
922 # Simple resizing. reduce_output is not zero (see above)!
923 else:
924 scale_factor = float(interpolate_input) / float(reduce_output)
925 return resize(input_image, (round(input_image.shape[1] * scale_factor),
926 round(input_image.shape[0] * scale_factor)),
927 interpolation=INTER_CUBIC)
928
929 # If interpolation is requested, resize the input image and multiply the shift values.
930 if interpolate_input != 1:
931 dim_y = input_image.shape[0] * interpolate_input
932 dim_x = input_image.shape[1] * interpolate_input
933 interp_image = resize(input_image, (dim_x, dim_y), interpolation=INTER_CUBIC)
934 s_red_y = round(interpolate_input * shift_red[0])
935 s_red_x = round(interpolate_input * shift_red[1])
936 s_blue_y = round(interpolate_input * shift_blue[0])
937 s_blue_x = round(interpolate_input * shift_blue[1])
938 else:
939 dim_y = input_image.shape[0]
940 dim_x = input_image.shape[1]
941 interp_image = input_image
942 s_red_y = round(shift_red[0])
943 s_red_x = round(shift_red[1])
944 s_blue_y = round(shift_blue[0])
945 s_blue_x = round(shift_blue[1])
946
947 # Remember the data type of the input image. The output image will be of the same type.
948 type = input_image.dtype
949
950 # In the following, for both the red and blue channels the index areas are computed for
951 # which no shift is beyond the image dimensions. First treat the y coordinate.
952 y_low_source_r = -s_red_y
953 y_high_source_r = dim_y - s_red_y
954 y_low_target_r = 0
955 # If the shift reaches beyond the frame, reduce the copy area.
956 if y_low_source_r < 0:
957 y_low_target_r = -y_low_source_r
958 y_low_source_r = 0
959 if y_high_source_r > dim_y:
960 y_high_source_r = dim_y
961 y_high_target_r = y_low_target_r + y_high_source_r - y_low_source_r
962
963 y_low_source_b = -s_blue_y
964 y_high_source_b = dim_y - s_blue_y
965 y_low_target_b = 0
966 # If the shift reaches beyond the frame, reduce the copy area.
967 if y_low_source_b < 0:
968 y_low_target_b = -y_low_source_b
969 y_low_source_b = 0
970 if y_high_source_b > dim_y:
971 y_high_source_b = dim_y
972 y_high_target_b = y_low_target_b + y_high_source_b - y_low_source_b
973
974 # The same for the x coordinate.
975 x_low_source_r = -s_red_x
976 x_high_source_r = dim_x - s_red_x
977 x_low_target_r = 0
978 # If the shift reaches beyond the frame, reduce the copy area.
979 if x_low_source_r < 0:
980 x_low_target_r = -x_low_source_r
981 x_low_source_r = 0
982 if x_high_source_r > dim_x:
983 x_high_source_r = dim_x
984 x_high_target_r = x_low_target_r + x_high_source_r - x_low_source_r
985
986 x_low_source_b = -s_blue_x
987 x_high_source_b = dim_x - s_blue_x
988 x_low_target_b = 0
989 # If the shift reaches beyond the frame, reduce the copy area.
990 if x_low_source_b < 0:
991 x_low_target_b = -x_low_source_b
992 x_low_source_b = 0
993 if x_high_source_b > dim_x:
994 x_high_source_b = dim_x
995 x_high_target_b = x_low_target_b + x_high_source_b - x_low_source_b
996
997 # Now the coordinate bounds can be computed for which the output image has entries in all
998 # three channels. The green channel is not shifted and can just be copied in place.
999 min_y_g = max(y_low_target_r, y_low_target_b)
1000 max_y_g = min(y_high_target_r, y_high_target_b)
1001 min_x_g = max(x_low_target_r, x_low_target_b)
1002 max_x_g = min(x_high_target_r, x_high_target_b)
1003
1004 # Allocate space for the output image (still not reduced in size), and copy the three color
1005 # channels with the appropriate shifts applied.
1006 output_image_interp = empty((max_y_g - min_y_g, max_x_g - min_x_g, 3), dtype=type)
1007 output_image_interp[:, :, 0] = interp_image[min_y_g - s_red_y:max_y_g - s_red_y,
1008 min_x_g - s_red_x:max_x_g - s_red_x, 0]
1009 output_image_interp[:, :, 1] = interp_image[min_y_g:max_y_g, min_x_g:max_x_g, 1]
1010 output_image_interp[:, :, 2] = interp_image[min_y_g - s_blue_y:max_y_g - s_blue_y,
1011 min_x_g - s_blue_x:max_x_g - s_blue_x, 2]
1012
1013 # If output size reduction is specified, resize the intermediate image.
1014 if reduce_output != 1:
1015 output_image = resize(output_image_interp,
1016 (round(output_image_interp.shape[1] / reduce_output),
1017 round(output_image_interp.shape[0] / reduce_output)),
1018 interpolation=INTER_CUBIC)
1019 else:
1020 output_image = output_image_interp
1021
1022 return output_image
1023
1024 @staticmethod
1025 def measure_rgb_shift(image, channel_id, reference_id, max_shift, blur_strength=None):
1026 """
1027 Measure the shift between two color channels of a three-color RGB image. Before measuring
1028 the shift with cross correlation, a Gaussian blur can be applied to both channels to reduce
1029 noise.
1030
1031 :param image: Input image (3 channel RGB).
1032 :param channel_id: Index of the channel, the shift of which is to be measured against the
1033 reference channel.
1034 :param reference_id: Index of the reference channel, usually 1 for "green".
1035 :param max_shift: Maximal search space radius in pixels.
1036 :param blur_strength: Strength of the Gaussian blur to be applied first.
1037 :return: Tuple (shift_y, shift_x) with coordinate shifts in y and x.
1038 """
1039
1040 # Test for invalid channel ids.
1041 if not (0 <= channel_id <= 2):
1042 raise ArgumentError("Invalid color channel id: " + str(channel_id))
1043 if not (0 <= reference_id <= 2):
1044 raise ArgumentError("Invalid reference channel id: " + str(reference_id))
1045
1046 # Reduce the size of the window for which the correlation will be computed to make space for
1047 # the search space around it.
1048 channel_window = image[max_shift:-max_shift, max_shift:-max_shift, channel_id]
1049 channel_reference = image[:, :, reference_id]
1050
1051 # Apply Gaussian blur if requested.
1052 if blur_strength:
1053 channel_blurred = GaussianBlur(channel_window, (blur_strength, blur_strength), 0)
1054 channel_reference_blurred = GaussianBlur(channel_reference,
1055 (blur_strength, blur_strength), 0)
1056 else:
1057 channel_blurred = channel_window
1058 channel_reference_blurred = channel_reference
1059
1060 # Compute the normalized cross correlation.
1061 result = matchTemplate((channel_reference_blurred).astype(float32),
1062 channel_blurred.astype(float32), TM_CCORR_NORMED)
1063
1064 # Determine the position of the maximum correlation, and compute the corresponding shifts.
1065 minVal, maxVal, minLoc, maxLoc = minMaxLoc(result)
1066 shift_y = max_shift - maxLoc[1]
1067 shift_x = max_shift - maxLoc[0]
1068 if abs(shift_y) != max_shift and abs(shift_x) != max_shift:
1069 return (shift_y, shift_x)
1070 else:
1071 raise Error ("No matching shift found within given range")
1072
1073 @staticmethod
1074 def insert_cross(frame, y_center, x_center, cross_half_len, color):
1075 """
1076 Insert a colored cross into an image at a given location.
1077
1078 :param frame: Image into which the cross is to be inserted
1079 :param y_center: y pixel coordinate of the center of the cross
1080 :param x_center: x pixel coordinate of the center of the cross
1081 :param cross_half_len: Extension of the cross from center in all four directions
1082 :param color: Color, one out of "white", "red", "green" and "blue"
1083 :return: -
1084 """
1085
1086 shape_y, shape_x = frame.shape[0:2]
1087
1088 if color == 'white':
1089 rgb = [255, 255, 255]
1090 elif color == 'red':
1091 rgb = [255, 0, 0]
1092 elif color == 'green':
1093 rgb = [0, 255, 0]
1094 elif color == 'blue':
1095 rgb = [0, 0, 255]
1096 elif color == 'cyan':
1097 rgb = [0, 255, 255]
1098 else:
1099 rgb = [255, 255, 255]
1100
1101 # Be sure not to draw beyond frame boundaries.
1102 if 0 <= x_center < shape_x:
1103 for y in range(y_center - cross_half_len, y_center + cross_half_len + 1):
1104 if 0 <= y < shape_y:
1105 frame[y, x_center] = rgb
1106 if 0 <= y_center < shape_y:
1107 for x in range(x_center - cross_half_len, x_center + cross_half_len + 1):
1108 if 0 <= x < shape_x:
1109 frame[y_center, x] = rgb
1110
1111 @staticmethod
1112 def compose_image(image_list, scale_factor=1, border=5):
1113 """
1114 Arrange a list of monochrome images horizontally in a single image, with constant gaps in
1115 between. If images are of different size, center-align them vertically. Optionally, the
1116 resulting image can be re-scaled with the same factor in x and y directions.
1117
1118 :param image_list: List containing images (all of the same dtype)
1119 :param scale_factor: Scaling factor for the resulting composite image
1120 :param border: Width of black border and gaps between images
1121 :return: Composite image of the same dtype as the image_list items
1122 """
1123
1124 shapes_y = [image.shape[0] for image in image_list]
1125 shapes_x = [image.shape[1] for image in image_list]
1126 max_shape_y = max(shapes_y)
1127 sum_shape_x = sum(shapes_x)
1128
1129 # Check if all images of the list are of the same type.
1130 type = image_list[0].dtype
1131 for image in image_list[1:]:
1132 if image.dtype != type:
1133 raise ArgumentError("Trying to compose images of different types")
1134
1135 # Compute the dimensions of the composite image. The border and the gaps between images are
1136 # 5 pixels wide.
1137 composite_dim_y = max_shape_y + 2 * border
1138 composite_dim_x = sum_shape_x + border * (len(image_list) + 1)
1139
1140 # Allocate the composite image.
1141 composite = full((composite_dim_y, composite_dim_x), 0, dtype=type)
1142
1143 # Copy the images into the composite image.
1144 x_pos = border
1145 for index, image in enumerate(image_list):
1146 y_pos = int((composite_dim_y - shapes_y[index]) / 2)
1147 composite[y_pos: y_pos + shapes_y[index], x_pos: x_pos + shapes_x[index]] = image
1148 x_pos += shapes_x[index] + border
1149
1150 # Return the resized composite image.
1151 return resize(composite, None, fx=float(scale_factor), fy=float(scale_factor))
1152
1153 @staticmethod
1154 def circle_around(y, x, r):
1155 """
1156 Create an iterator which returns y, x pixel coordinates around a given position in an
1157 image. Successive elements describe a circle around y, x with distance r (in the 1-norm).
1158 The iterator ends when the full circle is traversed.
1159
1160 :param x: x coordinate of the center location
1161 :param y: y coordinate of the center location
1162 :param r: distance of the iterator items from position (y, x) (1-norm, in pixels)
1163 :return: -
1164 """
1165
1166 # Special case 0: The only iterator element is the center point itself.
1167 if r == 0:
1168 yield (y, x)
1169
1170 # For the general case, set the first element and circle around (y, x) counter-clockwise.
1171 j, i = y - r, x - r
1172 while i < x + r:
1173 i += 1
1174 yield (j, i)
1175 while j < y + r:
1176 j += 1
1177 yield (j, i)
1178 while i > x - r:
1179 i -= 1
1180 yield (j, i)
1181 while j > y - r:
1182 j -= 1
1183 yield (j, i)
1184
1185 @staticmethod
1186 def write_video(name, frame_list, annotations, fps, depth=8):
1187 """
1188 Create a video file from a list of frames.
1189
1190 :param name: File name of the video output
1191 :param frame_list: List of frames to be written
1192 :param annotations: List of text strings to be written into the corresponding frame
1193 :param fps: Frames per second of video
1194 :param depth: Bit depth of the image "frame", either 8 or 16.
1195 :return: -
1196 """
1197
1198 # Delete the output file if it exists.
1199 try:
1200 unlink(name)
1201 except:
1202 pass
1203
1204 # Compute video frame size.
1205 frame_height = frame_list[0].shape[0]
1206 frame_width = frame_list[0].shape[1]
1207
1208 # Define the codec and create VideoWriter object
1209 fourcc = VideoWriter_fourcc('D', 'I', 'V', 'X')
1210 out = VideoWriter(name, fourcc, fps, (frame_width, frame_height))
1211
1212 # Define font for annotations.
1213 font = FONT_HERSHEY_SIMPLEX
1214 bottomLeftCornerOfText = (20, 50)
1215 fontScale = 1
1216 fontColor = (255, 255, 255)
1217 fontThickness = 1
1218 lineType = LINE_AA
1219
1220 # For each frame: If monochrome, convert it to three-channel color mode. insert annotation
1221 # and write the frame.
1222 for index, frame in enumerate(frame_list):
1223 # If the frames are 16bit, convert them to 8bit.
1224 if depth == 8:
1225 frame_8b = frame
1226 else:
1227 frame_8b = (frame / 255.).astype(uint8)
1228
1229 if len(frame.shape) == 2:
1230 rgb_frame = stack((frame_8b,) * 3, -1)
1231 else:
1232 rgb_frame = frame_8b
1233 putText(rgb_frame, annotations[index],
1234 bottomLeftCornerOfText,
1235 font,
1236 fontScale,
1237 fontColor,
1238 fontThickness,
1239 lineType)
1240 out.write(rgb_frame)
1241 out.release()
1242
1243 @staticmethod
1244 def post_process(image, layers):
1245 """
1246 Apply all postprocessing layers to the input image "image". If the image is in color mode,
1247 the postprocessing is computed either in BGR mode or on the luminance channel only. All
1248 computations are performed in 32bit floating point mode.
1249
1250 :param image: Input image, either BGR or Grayscale (16bit uint).
1251 :param layers: postprocessing layers with all parameters.
1252 :return: Processed image in the same 16bit uint format as the input image.
1253 """
1254
1255 # Check if the original image is selected (version 0). In this case nothing is to be done.
1256 if not layers:
1257 return image.astype(uint16)
1258
1259 # Convert the image to 32bit floating point format.
1260 input_image = image.astype(float32)
1261
1262 color = len(image.shape) == 3
1263
1264 # If the luminance channel is to be processed only, extract the luminance channel.
1265 if color and layers[0].luminance_only:
1266 input_image_hsv = cvtColor(input_image, COLOR_BGR2HSV)
1267 layer_input = input_image_hsv[:, :, 2]
1268 else:
1269 layer_input = input_image
1270
1271 # Go through all layers and apply the sharpening filters.
1272 for layer_index, layer in enumerate(layers):
1273
1274 # Bilateral filter is needed:
1275 if abs(layer.bi_fraction) > 1.e-5:
1276 layer_bilateral = bilateralFilter(layer_input, 0, layer.bi_range * 256.,
1277 layer.radius / 3., borderType=BORDER_DEFAULT)
1278 # Gaussian filter is needed:
1279 if abs(layer.bi_fraction - 1.) > 1.e-5:
1280 layer_gauss = GaussianBlur(layer_input, (0, 0), layer.radius / 3.,
1281 borderType=BORDER_DEFAULT)
1282
1283 # Compute the input for the next layer. First case: bilateral only.
1284 if abs(layer.bi_fraction - 1.) <= 1.e-5:
1285 next_layer_input = layer_bilateral
1286 # Case Gaussian only.
1287 elif abs(layer.bi_fraction) <= 1.e-5:
1288 next_layer_input = layer_gauss
1289 # Mixed case.
1290 else:
1291 next_layer_input = layer_bilateral * layer.bi_fraction + \
1292 layer_gauss * (1. - layer.bi_fraction)
1293
1294 layer_component_before_denoise = layer_input - next_layer_input
1295
1296 # If denoising is chosen for this layer, apply a Gaussian filter.
1297 if layer.denoise > 1.e-5:
1298 layer_component = GaussianBlur(layer_component_before_denoise, (0, 0),
1299 layer.radius / 3., borderType=BORDER_DEFAULT) * layer.denoise + \
1300 layer_component_before_denoise * (1. - layer.denoise)
1301 else:
1302 layer_component = layer_component_before_denoise
1303
1304 # Accumulate the contributions from all layers. On the first layer initialize the
1305 # summation buffer.
1306 if layer_index:
1307 components_accumulated += layer_component * layer.amount
1308 else:
1309 components_accumulated = layer_component * layer.amount
1310
1311 layer_input = next_layer_input
1312
1313 # After all layers are accumulated, finally add the maximally blurred image.
1314 components_accumulated += next_layer_input
1315
1316 # Reduce the value range so that they fit into 16bit uint, and convert to uint16. In case
1317 # the luminance channel was processed only, insert the processed luminance channel into the
1318 # HSV representation of the original image, and convert back to BGR.
1319 if color and layers[0].luminance_only:
1320 input_image_hsv[:, :, 2] = components_accumulated
1321 return cvtColor(input_image_hsv.clip(min=0., max=65535.), COLOR_HSV2BGR).astype(uint16)
1322 else:
1323 return components_accumulated.clip(min=0., max=65535.).astype(uint16)
1324
1325 @staticmethod
1326 def gaussian_sharpen(input_image, amount, radius, luminance_only=False):
1327 """
1328 Sharpen an image with a Gaussian kernel. The input image can be B/W or color.
1329
1330 :param input_image: Input image, type uint16
1331 :param amount: Amount of sharpening
1332 :param radius: Radius of Gaussian kernel (in pixels)
1333 :param luminance_only: True, if only the luminance channel of a color image is to be
1334 sharpened. Default is False.
1335 :return: The sharpened image (B/W or color, as input), type uint16
1336 """
1337
1338 color = len(input_image.shape) == 3
1339
1340 # Translate the kernel radius into standard deviation.
1341 sigma = radius / 3
1342
1343 # Convert the image to floating point format.
1344 image = input_image.astype(float32)
1345
1346 # Special case: Only sharpen the luminance channel of a color image.
1347 if color and luminance_only:
1348 hsv = cvtColor(image, COLOR_BGR2HSV)
1349 luminance = hsv[:, :, 2]
1350
1351 # Apply a Gaussian blur filter, subtract it from the original image, and add a multiple
1352 # of this correction to the original image. Clip values out of range.
1353 luminance_blurred = GaussianBlur(luminance, (0, 0), sigma, borderType=BORDER_DEFAULT)
1354 hsv[:, :, 2] = (luminance + amount * (luminance - luminance_blurred)).clip(min=0.,
1355 max=65535.)
1356 # Convert the image back to uint16.
1357 return cvtColor(hsv, COLOR_HSV2BGR).astype(uint16)
1358 # General case: Treat the entire image (B/W or color 16bit mode).
1359 else:
1360 image_blurred = GaussianBlur(image, (0, 0), sigma, borderType=BORDER_DEFAULT)
1361 return (image + amount * (image - image_blurred)).clip(min=0., max=65535.).astype(
1362 uint16)
1363
1364 @staticmethod
1365 def gaussian_blur(input_image, amount, radius, luminance_only=False):
1366 """
1367 Soften an image with a Gaussian kernel. The input image can be B/W or color.
1368
1369 :param input_image: Input image, type uint16
1370 :param amount: Amount of blurring, between 0. and 1.
1371 :param radius: Radius of Gaussian kernel (in pixels)
1372 :param luminance_only: True, if only the luminance channel of a color image is to be
1373 blurred. Default is False.
1374 :return: The blurred image (B/W or color, as input), type uint16
1375 """
1376
1377 color = len(input_image.shape) == 3
1378
1379 # Translate the kernel radius into standard deviation.
1380 sigma = radius / 3
1381
1382 # Convert the image to floating point format.
1383 image = input_image.astype(float32)
1384
1385 # Special case: Only blur the luminance channel of a color image.
1386 if color and luminance_only:
1387 hsv = cvtColor(image, COLOR_BGR2HSV)
1388 luminance = hsv[:, :, 2]
1389
1390 # Apply a Gaussian blur filter, subtract it from the original image, and add a multiple
1391 # of this correction to the original image. Clip values out of range.
1392 luminance_blurred = GaussianBlur(luminance, (0, 0), sigma, borderType=BORDER_DEFAULT)
1393 hsv[:, :, 2] = (luminance_blurred*amount + luminance*(1.-amount)).clip(min=0.,
1394 max=65535.)
1395 # Convert the image back to uint16.
1396 return cvtColor(hsv, COLOR_HSV2BGR).astype(uint16)
1397 # General case: Treat the entire image (B/W or color 16bit mode).
1398 else:
1399 image_blurred = GaussianBlur(image, (0, 0), sigma, borderType=BORDER_DEFAULT)
1400 return (image_blurred*amount + image*(1.-amount)).clip(min=0., max=65535.).astype(
1401 uint16)
1402
1403 @staticmethod
1404 def wavelet_sharpen(input_image, amount, radius):
1405 """
1406 Sharpen a B/W or color image with wavelets. The underlying algorithm was taken from the
1407 Gimp wavelet plugin, originally written in C and published under the GPLv2+ license at:
1408 https://github.com/mrossini-ethz/gimp-wavelet-sharpen/blob/master/src/wavelet.c
1409
1410 :param input_image: Input image (B/W or color), type uint16
1411 :param amount: Amount of sharpening
1412 :param radius: Radius in pixels
1413 :return: Sharpened image, same format as input image
1414 """
1415
1416 height, width = input_image.shape[:2]
1417 color = len(input_image.shape) == 3
1418
1419 # Allocate workspace: Three complete images, plus 1D object with length max(row, column).
1420 if color:
1421 fimg = empty((3, height, width, 3), dtype=float32)
1422 temp = zeros((max(width, height), 3), dtype=float32)
1423 else:
1424 fimg = empty((3, height, width), dtype=float32)
1425 temp = zeros(max(width, height), dtype=float32)
1426
1427 # Convert input image to floats.
1428 fimg[0] = input_image / 65535
1429
1430 # Start with level 0. Store its Laplacian on level 1. The operator is separated in a
1431 # column and a row operator.
1432 hpass = 0
1433 for lev in range(5):
1434 # Highpass and lowpass levels use image indices 1 and 2 in alternating mode to save
1435 # space.
1436 lpass = ((lev & 1) + 1)
1437
1438 if color:
1439 for row in range(height):
1440 Miscellaneous.mexican_hat_color(temp, fimg[hpass][row, :, :], width, 1 << lev)
1441 fimg[lpass][row, :, :] = temp[:width, :] * 0.25
1442 for col in range(width):
1443 Miscellaneous.mexican_hat_color(temp, fimg[lpass][:, col, :], height, 1 << lev)
1444 fimg[lpass][:, col, :] = temp[:height, :] * 0.25
1445 else:
1446 for row in range(height):
1447 Miscellaneous.mexican_hat(temp, fimg[hpass][row, :], width, 1 << lev)
1448 fimg[lpass][row, :] = temp[:width] * 0.25
1449 for col in range(width):
1450 Miscellaneous.mexican_hat(temp, fimg[lpass][:, col], height, 1 << lev)
1451 fimg[lpass][:, col] = temp[:height] * 0.25
1452
1453 # Compute the amount of the correction at the current level.
1454 amt = amount * exp(-(lev - radius) * (lev - radius) / 1.5) + 1.
1455
1456 fimg[hpass] -= fimg[lpass]
1457 fimg[hpass] *= amt
1458
1459 # Accumulate all corrections in the first workspace image.
1460 if hpass:
1461 fimg[0] += fimg[hpass]
1462
1463 hpass = lpass
1464
1465 # At the end add the coarsest level and convert back to 16bit integer format.
1466 fimg[0] = ((fimg[0] + fimg[lpass]) * 65535.).clip(min=0., max=65535.)
1467 return fimg[0].astype(uint16)
1468
1469 @staticmethod
1470 def mexican_hat(temp, base, size, sc):
1471 """
1472 Apply a 1D strided second derivative to a row or column of a B/W image. Store the result
1473 in the temporary workspace "temp".
1474
1475 :param temp: Workspace (type float32), length at least "size" elements
1476 :param base: Input image (B/W), Type float32
1477 :param size: Length of image row / column
1478 :param sc: Stride (power of 2) of operator
1479 :return: -
1480 """
1481
1482 # Special case at begin of row/column. Full operator not applicable.
1483 temp[:sc] = 2 * base[:sc] + base[sc:0:-1] + base[sc:2 * sc]
1484 # Apply the full operator.
1485 temp[sc:size - sc] = 2 * base[sc:size - sc] + base[:size - 2 * sc] + base[2 * sc:size]
1486 # Special case at end of row/column. The full operator is not applicable.
1487 temp[size - sc:size] = 2 * base[size - sc:size] + base[size - 2 * sc:size - sc] + \
1488 base[size - 2:size - 2 - sc:-1]
1489
1490 @staticmethod
1491 def mexican_hat_color(temp, base, size, sc):
1492 """
1493 Apply a 1D strided second derivative to a row or column of a color image. Store the result
1494 in the temporary workspace "temp".
1495
1496 :param temp: Workspace (type float32), length at least "size" elements (first dimension)
1497 times 3 colors (second dimension).
1498 :param base: Input image (color), Type float32
1499 :param size: Length of image row / column
1500 :param sc: Stride (power of 2) of operator
1501 :return: -
1502 """
1503
1504 # Special case at begin of row/column. Full operator not applicable.
1505 temp[:sc, :] = 2 * base[:sc, :] + base[sc:0:-1, :] + base[sc:2 * sc, :]
1506 # Apply the full operator.
1507 temp[sc:size - sc, :] = 2 * base[sc:size - sc, :] + base[:size - 2 * sc, :] + base[
1508 2 * sc:size, :]
1509 # Special case at end of row/column. The full operator is not applicable.
1510 temp[size - sc:size, :] = 2 * base[size - sc:size, :] + base[size - 2 * sc:size - sc, :] + \
1511 base[size - 2:size - 2 - sc:-1, :]
1512
1513 @staticmethod
1514 def protocol(string, logfile, precede_with_timestamp=True):
1515 """
1516 Print a message (optionally plus time stamp) to standard output. If it is requested to store
1517 a logfile with the stacked image, write the string to that file as well.
1518
1519 :param string: Message to be printed after the time stamp
1520 :param logfile: logfile or None (no logging)
1521 :return: -
1522 """
1523
1524 # Precede the text with a time stamp and print it to stdout. Note that stdout may be
1525 # redirected to a file.
1526 if precede_with_timestamp:
1527 output_string = '{0} {1}'.format(datetime.now().strftime("%H-%M-%S.%f")[:-5], string)
1528 else:
1529 output_string = string
1530 print(output_string)
1531 stdout.flush()
1532
1533 # If a logfile per stacked image was requested, write the string to that file as well.
1534 if logfile:
1535 logfile.write(output_string + "\n")
1536
1537 @staticmethod
1538 def print_stacking_parameters(configuration, logfile):
1539 """
1540 Print a table with all stacking parameters.
1541
1542 :param configuration: Object holding all configuration parameters.
1543 :param logfile: logfile or None (no logging)
1544 :return: -
1545 """
1546
1547 # Compile all parameters and their values to be printed.
1548
1549 if configuration.global_parameters_maximum_memory_active:
1550 parameters = [["RAM limit set explicitly (GBytes)",
1551 str(configuration.global_parameters_maximum_memory_amount)]]
1552 else:
1553 parameters = [["RAM limit set explicitly", "False"]]
1554 if configuration.global_parameters_buffering_level == -1:
1555 parameters += [["Buffering level", "auto"]]
1556 else:
1557 parameters += [["Buffering level set explicitly",
1558 str(configuration.global_parameters_buffering_level)]]
1559
1560 parameters += [["Debayering default", configuration.frames_debayering_default],
1561 ["Debayering method", configuration.frames_debayering_method],
1562 ["Noise level (add Gaussian blur)", str(configuration.frames_gauss_width)],
1563 ["Frame stabilization mode", configuration.align_frames_mode]]
1564
1565 # The following parameters are only active in "Surface" mode.
1566 if configuration.align_frames_mode == "Surface":
1567 parameters += [
1568 ["Automatic frame stabilization", str(configuration.align_frames_automation)],
1569 ["Stabilization patch size (% of frame size)",
1570 str(int(round(100. / configuration.align_frames_rectangle_scale_factor)))],
1571 ["Stabilization search width (pixels)",
1572 str(configuration.align_frames_search_width)]]
1573
1574 # Continue with general parameters.
1575 parameters += [["Percentage of best frames for reference frame computation",
1576 str(configuration.align_frames_average_frame_percent)],
1577 ["Object is changing fast (e.g. Jupiter, Sun)",
1578 str(configuration.align_frames_fast_changing_object)],
1579 ["Alignment box width (pixels)",
1580 str(2 * configuration.alignment_points_half_box_width)],
1581 ["Max. alignment search width (pixels)",
1582 str(configuration.alignment_points_search_width)], ["Minimum structure",
1583 str(configuration.alignment_points_structure_threshold)],
1584 ["Minimum brightness",
1585 str(configuration.alignment_points_brightness_threshold)]]
1586
1587 # The stack size is defined either as frame number or percentage.
1588 if configuration.alignment_points_frame_percent > 0:
1589 parameters += [["Percentage of best frames to be stacked",
1590 str(configuration.alignment_points_frame_percent)],
1591 ["Normalize frame brightness", str(configuration.frames_normalization)]]
1592 else:
1593 parameters += [["Number of best frames to be stacked",
1594 str(configuration.alignment_points_frame_number)],
1595 ["Normalize frame brightness", str(configuration.frames_normalization)]]
1596
1597 # If brightness normalization is checked, add the black cut-off value.
1598 if configuration.frames_normalization:
1599 parameters += [
1600 ["Normalization black cut-off", str(configuration.frames_normalization_threshold)]]
1601
1602 # If drizzling is active, add the factor.
1603 if configuration.stack_frames_drizzle_factor_string != "Off":
1604 parameters += [["Drizzle factor in stacking",
1605 str(configuration.stack_frames_drizzle_factor_string)]]
1606
1607 output_string = "\n Stacking parameters: " \
1608 " | Value |\n" \
1609 " " \
1610 "---------------------------------------------------------------------------------------------" \
1611 "\n "
1612
1613 # Extend the output string with a line for every parameter to be printed.
1614 for line in parameters:
1615 output_string += " {0:60s} | {1:29s}|\n ".format(line[0], line[1])
1616
1617 # Write the complete table.
1618 Miscellaneous.protocol(output_string, logfile, precede_with_timestamp=False)
1619
1620 @staticmethod
1621 def print_postproc_parameters(postproc_version, logfile):
1622 """
1623 Print a table with postprocessing layer info for the selected postprocessing version.
1624
1625 :param postproc_version: Object holding postprocessing parameters for the selected version.
1626 :param logfile: logfile or None (no logging)
1627 :return: -
1628 """
1629
1630 # Test if an RGB correction has been applied.
1631 if postproc_version.shift_red != (0., 0.) or postproc_version.shift_blue != (0., 0.):
1632 # Find out if the RGB correction was done automatically.
1633 if postproc_version.rgb_automatic:
1634 intro = " Automatic RGB correction, "
1635 else:
1636 intro = " Manual RGB correction, "
1637 (shift_red_y, shift_red_x) = postproc_version.shift_red
1638 (shift_blue_y, shift_blue_x) = postproc_version.shift_blue
1639
1640 n_digits = [0, 1, 2][postproc_version.rgb_resolution_index]
1641 if shift_red_y >= 0.:
1642 dir_red_y = " pixels down"
1643 else:
1644 dir_red_y = " pixels up"
1645 if shift_red_x >= 0.:
1646 dir_red_x = " pixels right"
1647 else:
1648 dir_red_x = " pixels left"
1649 if shift_blue_y >= 0.:
1650 dir_blue_y = " pixels down"
1651 else:
1652 dir_blue_y = " pixels up"
1653 if shift_blue_x >= 0.:
1654 dir_blue_x = " pixels right"
1655 else:
1656 dir_blue_x = " pixels left"
1657
1658 # Special case 0 digits: In this case the number of digits must be omitted.
1659 # If the round function is called with "n_digits=0", the result still has one digit
1660 # after the decimal point.
1661 if n_digits:
1662 Miscellaneous.protocol(
1663 intro + "red channel shifted " +
1664 str(round(abs(shift_red_y), n_digits)) + dir_red_y + ", " +
1665 str(round(abs(shift_red_x), n_digits)) + dir_red_x + ", blue channel shifted " +
1666 str(round(abs(shift_blue_y), n_digits)) + dir_blue_y + ", " +
1667 str(round(abs(shift_blue_x), n_digits)) + dir_blue_x + ".",
1668 logfile, precede_with_timestamp=False)
1669 else:
1670 Miscellaneous.protocol(
1671 intro + "red channel shifted " +
1672 str(round(abs(shift_red_y))) + dir_red_y + ", " +
1673 str(round(abs(shift_red_x))) + dir_red_x + ", blue channel shifted " +
1674 str(round(abs(shift_blue_y))) + dir_blue_y + ", " +
1675 str(round(abs(shift_blue_x))) + dir_blue_x + ".",
1676 logfile, precede_with_timestamp=False)
1677
1678 if postproc_version.layers:
1679 output_string = " Postprocessing method: " + postproc_version.layers[0].postproc_method + "\n\n" + \
1680 " Layer | Radius | Amount | Bi fraction (%) | Bi range | Denoise (%) | Luminance only |\n" \
1681 " ------------------------------------------------------------------------------------------------------------------" \
1682 "\n "
1683
1684 # Extend the three table lines up to the max index.
1685 for index, layer in enumerate(postproc_version.layers):
1686 output_string += " {0:3d} | {1:5.2f} | {2:6.2f} | {3:4.0f} | {4:5.1f} | {5:4.0f} | {6:8s} |" \
1687 "\n ".format(index + 1, layer.radius, layer.amount, layer.bi_fraction*100., layer.bi_range, layer.denoise*100., str(layer.luminance_only))
1688
1689 Miscellaneous.protocol(output_string, logfile, precede_with_timestamp=False)
1690
1691
1692 if __name__ == "__main__":
1693
1694 # Test program for routine search_local_match
1695
1696 # Set the size of the image frame.
1697 frame_height = 960
1698 frame_width = 1280
1699
1700 # Initialize the frame with a wave-like pattern in x and y directions.
1701 x_max = 30.
1702 x_vec = arange(0., x_max, x_max / frame_width)
1703 y_max = 25.
1704 y_vec = arange(0., y_max, y_max / frame_height)
1705 frame = empty((frame_height, frame_width))
1706 for y_j, y in enumerate(y_vec):
1707 for x_i, x in enumerate(x_vec):
1708 frame[y_j, x_i] = sin(y) * sin(x)
1709
1710 # Set the size and location of the reference frame window and cut it out from the frame.
1711 window_height = 40
1712 window_width = 50
1713 reference_y_low = 400
1714 reference_x_low = 500
1715 reference_box = frame[reference_y_low:reference_y_low + window_height,
1716 reference_x_low:reference_x_low + window_width]
1717
1718 # Set the true displacement vector to be checked against the result of the search function.
1719 displacement_y = 1
1720 displacement_x = -2
1721
1722 # The start point for the local search is offset from the true matching point.
1723 y_low = reference_y_low + displacement_y
1724 y_high = y_low + window_height
1725 x_low = reference_x_low + displacement_x
1726 x_high = x_low + window_width
1727
1728 # Set the radius of the search area.
1729 search_width = 20
1730 sampling_stride = 1
1731
1732 dev_table = empty((2 * search_width + 1, 2 * search_width + 1), dtype=float32)
1733
1734 # First try the standard method "search_local_match". Compute the displacement vector, and
1735 # print a comparison of the true and computed values.
1736 start = time()
1737 rep_count = 1
1738 for iter in range(rep_count):
1739 [dy, dx], dev_r = Miscellaneous.search_local_match(reference_box, frame, y_low, y_high,
1740 x_low, x_high, search_width,
1741 sampling_stride, sub_pixel=False)
1742 end = time()
1743 print("Standard method, true displacements: " + str([displacement_y, displacement_x]) +
1744 ", computed: " + str([dy, dx]) + ", execution time (s): " + str((end - start) / rep_count))
1745
1746 # As a comparison, do the same using the steepest descent method.
1747 start = time()
1748 for iter in range(rep_count):
1749 [dy, dx], dev_r = Miscellaneous.search_local_match_gradient(reference_box, frame,
1750 y_low, y_high,
1751 x_low, x_high, search_width,
1752 sampling_stride, dev_table)
1753 end = time()
1754 print("steepest descent, true displacements: " + str([displacement_y, displacement_x]) +
1755 ", computed: " + str([dy, dx]) + ", execution time (s): " + str((end - start) / rep_count))
1756
1757 # Now test the alternative method in comparison to the straight-forward one. First,
1758 # compute the reference frame box stack. The initialization has to be performed only once for
1759 # each alignment point. It can be reused for all frames containing the AP.
1760 start = time()
1761 for iter in range(rep_count):
1762 reference_stack, displacements, radius_start = \
1763 Miscellaneous.search_local_match_init(frame, reference_y_low,
1764 reference_y_low + window_height, reference_x_low,
1765 reference_x_low + window_width, search_width)
1766 end = time()
1767 print("Match initialization time (s): " + str((end - start) / rep_count))
1768
1769 # Compute the displacement. The result should be the same as above.
1770 start = time()
1771 for iter in range(rep_count):
1772 [dy, dx], dev_r = Miscellaneous.search_local_match_execute(
1773 frame[y_low:y_high, x_low:x_high], reference_stack, displacements,
1774 radius_start)
1775 end = time()
1776 print("Match execution, true displacements: " + str(
1777 [displacement_y, displacement_x]) + ", computed: " + str(
1778 [dy, dx]) + ", execution time (s): " + str((end - start) / rep_count))