d2::image::get_*bl(): Always return a single value.
[Ale.git] / d2 / align.h
blob087b2f5fd7738e1c547640cd148cfa754dc9bd5f
1 // Copyright 2002, 2004, 2007 David Hilvert <dhilvert@auricle.dyndns.org>,
2 // <dhilvert@ugcs.caltech.edu>
4 /* This file is part of the Anti-Lamenessing Engine.
6 The Anti-Lamenessing Engine is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 The Anti-Lamenessing Engine is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with the Anti-Lamenessing Engine; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 * align.h: Handle alignment of frames.
25 #ifndef __d2align_h__
26 #define __d2align_h__
28 #include "filter.h"
29 #include "transformation.h"
30 #include "image.h"
31 #include "point.h"
32 #include "render.h"
33 #include "tfile.h"
34 #include "image_rw.h"
36 #define D2_ALIGN_IMPRECISE_COVERAGE 0.3
38 class align {
39 private:
42 * Private data members
45 static ale_pos scale_factor;
48 * Original frame transformation
50 static transformation orig_t;
53 * Keep data older than latest
55 static int _keep;
56 static transformation *kept_t;
57 static int *kept_ok;
60 * Transformation file handlers
63 static tload_t *tload;
64 static tsave_t *tsave;
67 * Control point variables
70 static const point **cp_array;
71 static unsigned int cp_count;
74 * Reference rendering to align against
77 static render *reference;
78 static filter::scaled_filter *interpolant;
79 static const image *reference_image;
80 static const image *reference_defined;
83 * Per-pixel alignment weight map
86 static const image *weight_map;
89 * Frequency-dependent alignment weights
92 static double horiz_freq_cut;
93 static double vert_freq_cut;
94 static double avg_freq_cut;
95 static const char *fw_output;
98 * Algorithmic alignment weighting
101 static const char *wmx_exec;
102 static const char *wmx_file;
103 static const char *wmx_defs;
106 * Non-certainty alignment weights
109 static image *alignment_weights;
112 * Latest transformation.
115 static transformation latest_t;
118 * Flag indicating whether the latest transformation
119 * resulted in a match.
122 static int latest_ok;
125 * Frame number most recently aligned.
128 static int latest;
131 * Exposure registration
133 * 0. Preserve the original exposure of images.
135 * 1. Match exposure between images.
137 * 2. Use only image metadata for registering exposure.
140 static int _exp_register;
143 * Alignment class.
145 * 0. Translation only. Only adjust the x and y position of images.
146 * Do not rotate input images or perform projective transformations.
148 * 1. Euclidean transformations only. Adjust the x and y position
149 * of images and the orientation of the image about the image center.
151 * 2. Perform general projective transformations. See the file gpt.h
152 * for more information about general projective transformations.
155 static int alignment_class;
158 * Default initial alignment type.
160 * 0. Identity transformation.
162 * 1. Most recently accepted frame's final transformation.
165 static int default_initial_alignment_type;
168 * Projective group behavior
170 * 0. Perturb in output coordinates.
172 * 1. Perturb in source coordinates
175 static int perturb_type;
178 * Alignment element
180 * This structure contains variables necessary for handling a
181 * multi-alignment element. The change between the non-default old
182 * initial alignment and old final alignment is used to adjust the
183 * non-default current initial alignment. If either the old or new
184 * initial alignment is a default alignment, the old --follow semantics
185 * are preserved.
188 struct element_t {
189 int is_default, old_is_default;
190 int is_primary;
191 int old_lod;
192 transformation old_initial_alignment;
193 transformation old_final_alignment;
194 transformation default_initial_alignment;
195 const image *input_frame;
197 public:
198 element_t() {
199 is_default = 1;
200 input_frame = NULL;
205 * Alignment for failed frames -- default or optimal?
207 * A frame that does not meet the match threshold can be assigned the
208 * best alignment found, or can be assigned its alignment default.
211 static int is_fail_default;
214 * Alignment code.
216 * 0. Align images with an error contribution from each color channel.
218 * 1. Align images with an error contribution only from the green channel.
219 * Other color channels do not affect alignment.
221 * 2. Align images using a summation of channels. May be useful when dealing
222 * with images that have high frequency color ripples due to color aliasing.
225 static int channel_alignment_type;
228 * Error metric exponent
231 static float metric_exponent;
234 * Match threshold
237 static float match_threshold;
240 * Perturbation lower and upper bounds.
243 static ale_pos perturb_lower;
244 static int perturb_lower_percent;
245 static ale_pos perturb_upper;
246 static int perturb_upper_percent;
249 * Maximum level-of-detail scale factor is 2^lod_max/perturb.
252 static int lod_max;
255 * Maximum rotational perturbation
258 static ale_pos rot_max;
261 * Barrel distortion alignment multiplier
264 static ale_pos bda_mult;
267 * Barrel distortion maximum adjustment rate
270 static ale_pos bda_rate;
273 * Alignment match sum
276 static ale_accum match_sum;
279 * Alignment match count.
282 static int match_count;
285 * Exposure registration and final match precision flag
287 * 0. Do not require precise calculation.
289 * 1. Require precise exposure registration and final match.
292 static int precise_calculation;
295 * Certainty weight flag
297 * 0. Don't use certainty weights for alignment.
299 * 1. Use certainty weights for alignment.
302 static int certainty_weights;
305 * Global search parameter
307 * 0. Local: Local search only.
308 * 1. Inner: Alignment reference image inner region
309 * 2. Outer: Alignment reference image outer region
310 * 3. All: Alignment reference image inner and outer regions.
311 * 4. Central: Inner if possible; else, best of inner and outer.
312 * 5. Points: Align by control points.
315 static int _gs;
318 * Multi-alignment cardinality.
321 static unsigned int _ma_card;
324 * Multi-alignment contiguity.
327 static double _ma_cont;
330 * Minimum overlap for global searches
333 static ale_pos _gs_mo;
334 static int gs_mo_percent;
337 * Exclusion regions
340 static exclusion *ax_parameters;
341 static int ax_count;
344 * Types for scale clusters.
347 struct nl_scale_cluster {
348 const image *accum_max;
349 const image *accum_min;
350 const image *certainty_max;
351 const image *certainty_min;
352 const image *aweight_max;
353 const image *aweight_min;
354 exclusion *ax_parameters;
356 ale_pos input_scale;
357 const image *input_certainty_max;
358 const image *input_certainty_min;
359 const image *input_max;
360 const image *input_min;
363 struct scale_cluster {
364 const image *accum;
365 const image *certainty;
366 const image *aweight;
367 exclusion *ax_parameters;
369 ale_pos input_scale;
370 const image *input_certainty;
371 const image *input;
373 nl_scale_cluster *nl_scale_clusters;
377 * Check for exclusion region coverage in the reference
378 * array.
380 static int ref_excluded(int i, int j, point offset, exclusion *params, int param_count) {
381 for (int idx = 0; idx < param_count; idx++)
382 if (params[idx].type == exclusion::RENDER
383 && i + offset[0] >= params[idx].x[0]
384 && i + offset[0] <= params[idx].x[1]
385 && j + offset[1] >= params[idx].x[2]
386 && j + offset[1] <= params[idx].x[3])
387 return 1;
389 return 0;
393 * Check for exclusion region coverage in the input
394 * array.
396 static int input_excluded(ale_pos ti, ale_pos tj, exclusion *params, int param_count) {
397 for (int idx = 0; idx < param_count; idx++)
398 if (params[idx].type == exclusion::FRAME
399 && ti >= params[idx].x[0]
400 && ti <= params[idx].x[1]
401 && tj >= params[idx].x[2]
402 && tj <= params[idx].x[3])
403 return 1;
405 return 0;
409 * Overlap function. Determines the number of pixels in areas where
410 * the arrays overlap. Uses the reference array's notion of pixel
411 * positions.
413 static unsigned int overlap(struct scale_cluster c, transformation t, int ax_count) {
414 assert (reference_image);
416 unsigned int result = 0;
418 point offset = c.accum->offset();
420 for (unsigned int i = 0; i < c.accum->height(); i++)
421 for (unsigned int j = 0; j < c.accum->width(); j++) {
423 if (ref_excluded(i, j, offset, c.ax_parameters, ax_count))
424 continue;
427 * Transform
430 struct point q;
432 q = (c.input_scale < 1.0 && interpolant == NULL)
433 ? t.scaled_inverse_transform(
434 point(i + offset[0], j + offset[1]))
435 : t.unscaled_inverse_transform(
436 point(i + offset[0], j + offset[1]));
438 ale_pos ti = q[0];
439 ale_pos tj = q[1];
442 * Check that the transformed coordinates are within
443 * the boundaries of array c.input, and check that the
444 * weight value in the accumulated array is nonzero,
445 * unless we know it is nonzero by virtue of the fact
446 * that it falls within the region of the original
447 * frame (e.g. when we're not increasing image
448 * extents). Also check for frame exclusion.
451 if (input_excluded(ti, tj, c.ax_parameters, ax_count))
452 continue;
454 if (ti >= 0
455 && ti <= c.input->height() - 1
456 && tj >= 0
457 && tj <= c.input->width() - 1
458 && c.certainty->get_pixel(i, j)[0] != 0)
459 result++;
462 return result;
466 * Calculate the region associated with the current multi-alignment
467 * element.
469 static void calculate_element_region(transformation *t, scale_cluster si,
470 int local_ax_count) {
472 unsigned int i_max = si.accum->height();
473 unsigned int j_max = si.accum->width();
474 point offset = si.accum->offset();
476 if (si.input_scale < 1.0 && interpolant == NULL)
477 t->begin_calculate_scaled_region(i_max, j_max, offset);
478 else
479 t->begin_calculate_unscaled_region(i_max, j_max, offset);
481 for (unsigned int i = 0; i < i_max; i++)
482 for (unsigned int j = 0; j < j_max; j++) {
484 if (ref_excluded(i, j, offset, si.ax_parameters, local_ax_count))
485 continue;
487 point q;
489 while ((q = t->get_query_point((int) (i + offset[0]),
490 (int) (j + offset[1]))).defined()) {
492 ale_pos ti = q[0];
493 ale_pos tj = q[1];
495 if (input_excluded(ti, tj, si.ax_parameters, ax_count))
496 continue;
498 if (ti >= 0
499 && ti <= si.input->height() - 1
500 && tj >= 0
501 && tj <= si.input->width() - 1
502 && si.certainty->get_pixel(i, j)[0] != 0) {
504 assert(0);
509 t->end_calculate_region();
513 * Monte carlo iteration class.
515 * Monte Carlo alignment has been used for statistical comparisons in
516 * spatial registration, and is now used for tonal registration
517 * and final match calculation.
521 * We use a random process for which the expected number of sampled
522 * pixels is +/- .000003 from the coverage in the range [.005,.995] for
523 * an image with 100,000 pixels. (The actual number may still deviate
524 * from the expected number by more than this amount, however.) The
525 * method is as follows:
527 * We have coverage == USE/ALL, or (expected # pixels to use)/(# total
528 * pixels). We derive from this SKIP/USE.
530 * SKIP/USE == (SKIP/ALL)/(USE/ALL) == (1 - (USE/ALL))/(USE/ALL)
532 * Once we have SKIP/USE, we know the expected number of pixels to skip
533 * in each iteration. We use a random selection process that provides
534 * SKIP/USE close to this calculated value.
536 * If we can draw uniformly to select the number of pixels to skip, we
537 * do. In this case, the maximum number of pixels to skip is twice the
538 * expected number.
540 * If we cannot draw uniformly, we still assign equal probability to
541 * each of the integer values in the interval [0, 2 * (SKIP/USE)], but
542 * assign an unequal amount to the integer value ceil(2 * SKIP/USE) +
543 * 1.
547 * When reseeding the random number generator, we want the same set of
548 * pixels to be used in cases where two alignment options are compared.
549 * If we wanted to avoid bias from repeatedly utilizing the same seed,
550 * we could seed with the number of the frame most recently aligned:
552 * srand(latest);
554 * However, in cursory tests, it seems okay to just use the default
555 * seed of 1, and so we do this, since it is simpler; both of these
556 * approaches to reseeding achieve better results than not reseeding.
557 * (1 is the default seed according to the GNU Manual Page for
558 * rand(3).)
560 * For subdomain calculations, we vary the seed by adding the subdomain
561 * index.
564 class mc_iterate {
565 ale_pos mc_max;
566 unsigned int index;
567 unsigned int index_max;
568 int i_min;
569 int i_max;
570 int j_min;
571 int j_max;
573 rng_t rng;
575 public:
576 mc_iterate(int _i_min, int _i_max, int _j_min, int _j_max, unsigned int subdomain)
577 : rng() {
579 ale_pos coverage;
581 i_min = _i_min;
582 i_max = _i_max;
583 j_min = _j_min;
584 j_max = _j_max;
586 index_max = (i_max - i_min) * (j_max - j_min);
588 if (index_max < 500 || precise_calculation)
589 coverage = 1;
590 else
591 coverage = D2_ALIGN_IMPRECISE_COVERAGE;
593 ale_pos su = (1 - coverage) / coverage;
595 mc_max = (floor(2*su) * (1 + floor(2*su)) + 2*su)
596 / (2 + 2 * floor(2*su) - 2*su);
598 rng.seed(1 + subdomain);
600 index = -1 + (int) ceil((mc_max+1)
601 * ( (1 + ((ale_pos) (rng.get())) )
602 / (1 + ((ale_pos) RAND_MAX)) ));
605 int get_i() {
606 return index / (j_max - j_min) + i_min;
609 int get_j() {
610 return index % (j_max - j_min) + j_min;
613 void operator++(int whats_this_for) {
614 index += (int) ceil((mc_max+1)
615 * ( (1 + ((ale_pos) (rng.get())) )
616 / (1 + ((ale_pos) RAND_MAX)) ));
619 int done() {
620 return (index >= index_max);
625 * Not-quite-symmetric difference function. Determines the difference in areas
626 * where the arrays overlap. Uses the reference array's notion of pixel positions.
628 * For the purposes of determining the difference, this function divides each
629 * pixel value by the corresponding image's average pixel magnitude, unless we
630 * are:
632 * a) Extending the boundaries of the image, or
634 * b) following the previous frame's transform
636 * If we are doing monte-carlo pixel sampling for alignment, we
637 * typically sample a subset of available pixels; otherwise, we sample
638 * all pixels.
642 class diff_stat_t {
644 struct run {
646 transformation offset;
647 ale_pos perturb;
649 ale_accum result;
650 ale_accum divisor;
652 point max, min;
653 ale_accum centroid[2], centroid_divisor;
654 ale_accum de_centroid[2], de_centroid_v, de_sum;
656 void init() {
658 result = 0;
659 divisor = 0;
661 min = point::posinf();
662 max = point::neginf();
664 centroid[0] = 0;
665 centroid[1] = 0;
666 centroid_divisor = 0;
668 de_centroid[0] = 0;
669 de_centroid[1] = 0;
671 de_centroid_v = 0;
673 de_sum = 0;
676 void init(transformation _offset, ale_pos _perturb) {
677 offset = _offset;
678 perturb = _perturb;
679 init();
683 * Required for STL sanity.
685 run() : offset() {
686 init();
689 run(transformation _offset, ale_pos _perturb) : offset() {
690 init(_offset, _perturb);
693 void add(const run &_run) {
694 result += _run.result;
695 divisor += _run.divisor;
697 for (int d = 0; d < 2; d++) {
698 if (min[d] > _run.min[d])
699 min[d] = _run.min[d];
700 if (max[d] < _run.max[d])
701 max[d] = _run.max[d];
702 centroid[d] += _run.centroid[d];
703 de_centroid[d] += _run.de_centroid[d];
706 centroid_divisor += _run.centroid_divisor;
707 de_centroid_v += _run.de_centroid_v;
708 de_sum += _run.de_sum;
711 run(const run &_run) : offset() {
714 * Initialize
716 init(_run.offset, _run.perturb);
719 * Add
721 add(_run);
724 run &operator=(const run &_run) {
727 * Initialize
729 init(_run.offset, _run.perturb);
732 * Add
734 add(_run);
736 return *this;
739 ~run() {
742 ale_accum get_error() const {
743 return pow(result / divisor, 1/metric_exponent);
746 void sample(int f, scale_cluster c, int i, int j, point t, point u,
747 const run &comparison) {
749 pixel pa = c.accum->get_pixel(i, j);
751 ale_accum this_result[2] = { 0, 0 };
752 ale_accum this_divisor[2] = { 0, 0 };
754 pixel p[2];
755 pixel weight[2];
756 weight[0] = pixel(1, 1, 1);
757 weight[1] = pixel(1, 1, 1);
759 if (interpolant != NULL) {
760 interpolant->filtered(i, j, &p[0], &weight[1], 1, f);
761 } else {
762 p[0] = c.input->get_bl(t);
765 if (u.defined()) {
766 p[1] = c.input->get_bl(u);
771 * Handle certainty.
774 if (certainty_weights == 1) {
775 weight[0] *= c.input_certainty->get_bl(t, 1);
776 weight[1] *= c.input_certainty->get_bl(u, 1);
777 weight[0] *= c.certainty->get_pixel(i, j);
778 weight[1] *= c.certainty->get_pixel(i, j);
781 if (c.aweight != NULL) {
782 weight[0] *= c.aweight->get_pixel(i, j);
783 weight[1] *= c.aweight->get_pixel(i, j);
787 * Update sampling area statistics
790 if (min[0] > i)
791 min[0] = i;
792 if (min[1] > j)
793 min[1] = j;
794 if (max[0] < i)
795 max[0] = i;
796 if (max[1] < j)
797 max[1] = j;
799 centroid[0] += (weight[0][0] + weight[0][1] + weight[0][2]) * i;
800 centroid[1] += (weight[0][0] + weight[0][1] + weight[0][2]) * j;
801 centroid_divisor += (weight[0][0] + weight[0][1] + weight[0][2]);
804 * Determine alignment type.
807 for (int m = 0; m < (u.defined() ? 2 : 1); m++)
808 if (channel_alignment_type == 0) {
810 * Align based on all channels.
814 for (int k = 0; k < 3; k++) {
815 ale_real achan = pa[k];
816 ale_real bchan = p[m][k];
818 this_result[m] += weight[m][k] * pow(fabs(achan - bchan), metric_exponent);
819 this_divisor[m] += weight[m][k] * pow(achan > bchan ? achan : bchan, metric_exponent);
821 } else if (channel_alignment_type == 1) {
823 * Align based on the green channel.
826 ale_real achan = pa[1];
827 ale_real bchan = p[m][1];
829 this_result[m] = weight[m][1] * pow(fabs(achan - bchan), metric_exponent);
830 this_divisor[m] = weight[m][1] * pow(achan > bchan ? achan : bchan, metric_exponent);
831 } else if (channel_alignment_type == 2) {
833 * Align based on the sum of all channels.
836 ale_real asum = 0;
837 ale_real bsum = 0;
838 ale_real wsum = 0;
840 for (int k = 0; k < 3; k++) {
841 asum += pa[k];
842 bsum += p[m][k];
843 wsum += weight[m][k] / 3;
846 this_result[m] = wsum * pow(fabs(asum - bsum), metric_exponent);
847 this_divisor[m] = wsum * pow(asum > bsum ? asum : bsum, metric_exponent);
850 if (u.defined()) {
851 // ale_accum de = fabs(this_result[0] / this_divisor[0]
852 // - this_result[1] / this_divisor[1]);
853 ale_accum de = fabs(this_result[0] - this_result[1]);
855 de_centroid[0] += de * i;
856 de_centroid[1] += de * j;
858 de_centroid_v += de * t.lengthto(u);
860 de_sum += de;
863 result += (this_result[0]);
864 divisor += (this_divisor[0]);
867 void rescale(ale_pos scale) {
868 offset.rescale(scale);
870 de_centroid[0] *= scale;
871 de_centroid[1] *= scale;
872 de_centroid_v *= scale;
875 point get_centroid() {
876 point result = point(centroid[0] / centroid_divisor, centroid[1] / centroid_divisor);
878 assert (finite(centroid[0])
879 && finite(centroid[1])
880 && (result.defined() || centroid_divisor == 0));
882 return result;
885 point get_error_centroid() {
886 point result = point(de_centroid[0] / de_sum, de_centroid[1] / de_sum);
887 return result;
891 ale_pos get_error_perturb() {
892 ale_pos result = de_centroid_v / de_sum;
894 return result;
900 * When non-empty, runs.front() is best, runs.back() is
901 * testing.
904 std::vector<run> runs;
907 * old_runs stores the latest available perturbation set for
908 * each multi-alignment element.
911 typedef std::pair<unsigned int, unsigned int> run_index;
912 std::map<run_index, run> old_runs;
914 static void *diff_subdomain(void *args);
916 struct subdomain_args {
917 struct scale_cluster c;
918 std::vector<run> runs;
919 int ax_count;
920 int f;
921 int i_min, i_max, j_min, j_max;
922 int subdomain;
925 int get_current_index() const {
926 assert(runs.size());
927 return runs[0].offset.get_current_index();
930 struct scale_cluster si;
931 int ax_count;
932 int frame;
934 std::vector<ale_pos> perturb_multipliers;
936 public:
937 void diff(struct scale_cluster c, ale_pos perturb,
938 transformation t,
939 int _ax_count, int f) {
941 if (runs.size() == 2)
942 runs.pop_back();
944 runs.push_back(run(t, perturb));
946 si = c;
947 ax_count = _ax_count;
948 frame = f;
950 ui::get()->d2_align_sample_start();
952 if (interpolant != NULL)
953 interpolant->set_parameters(t, c.input, c.accum->offset());
955 int N;
956 #ifdef USE_PTHREAD
957 N = thread::count();
959 pthread_t *threads = (pthread_t *) malloc(sizeof(pthread_t) * N);
960 pthread_attr_t *thread_attr = (pthread_attr_t *) malloc(sizeof(pthread_attr_t) * N);
962 #else
963 N = 1;
964 #endif
966 subdomain_args *args = new subdomain_args[N];
968 for (int ti = 0; ti < N; ti++) {
969 args[ti].c = c;
970 args[ti].runs = runs;
971 args[ti].ax_count = ax_count;
972 args[ti].f = f;
973 args[ti].i_min = (c.accum->height() * ti) / N;
974 args[ti].i_max = (c.accum->height() * (ti + 1)) / N;
975 args[ti].j_min = 0;
976 args[ti].j_max = c.accum->width();
977 args[ti].subdomain = ti;
978 #ifdef USE_PTHREAD
979 pthread_attr_init(&thread_attr[ti]);
980 pthread_attr_setdetachstate(&thread_attr[ti], PTHREAD_CREATE_JOINABLE);
981 pthread_create(&threads[ti], &thread_attr[ti], diff_subdomain, &args[ti]);
982 #else
983 diff_subdomain(&args[ti]);
984 #endif
987 for (int ti = 0; ti < N; ti++) {
988 #ifdef USE_PTHREAD
989 pthread_join(threads[ti], NULL);
990 #endif
991 runs.back().add(args[ti].runs.back());
994 delete[] args;
996 ui::get()->d2_align_sample_stop();
1000 private:
1001 void rediff() {
1002 std::vector<transformation> t_array;
1003 std::vector<ale_pos> p_array;
1005 for (unsigned int r = 0; r < runs.size(); r++) {
1006 t_array.push_back(runs[r].offset);
1007 p_array.push_back(runs[r].perturb);
1010 runs.clear();
1012 for (unsigned int r = 0; r < t_array.size(); r++)
1013 diff(si, p_array[r], t_array[r], ax_count, frame);
1017 public:
1018 int better() {
1019 assert(runs.size() >= 2);
1020 assert(runs[0].offset.scale() == runs[1].offset.scale());
1022 return (runs[1].get_error() < runs[0].get_error()
1023 || (!finite(runs[0].get_error()) && finite(runs[1].get_error())));
1026 diff_stat_t() : runs(), old_runs(), perturb_multipliers() {
1029 run_index get_run_index(unsigned int perturb_index) {
1030 return run_index(get_current_index(), perturb_index);
1033 run &get_run(unsigned int perturb_index) {
1034 run_index index = get_run_index(perturb_index);
1036 assert(old_runs.count(index));
1037 return old_runs[index];
1040 void rescale(ale_pos scale, scale_cluster _si) {
1041 assert(runs.size() == 1);
1043 si = _si;
1045 runs[0].rescale(scale);
1047 rediff();
1050 void push_element() {
1051 assert(runs.size() == 1);
1053 runs[0].offset.push_element();
1055 rediff();
1058 unsigned int get_current_index() {
1059 assert (runs.size() > 0);
1061 return runs[0].offset.get_current_index();
1064 void set_current_index(unsigned int i) {
1065 assert(runs.size() == 1);
1066 runs[0].offset.set_current_index(i);
1067 rediff();
1070 void calculate_element_region() {
1071 assert(runs.size() == 1);
1073 if (get_offset().get_current_index() > 0
1074 && get_offset().is_nontrivial())
1075 align::calculate_element_region(&runs[0].offset, si, ax_count);
1078 ~diff_stat_t() {
1081 diff_stat_t &operator=(const diff_stat_t &dst) {
1083 * Copy run information.
1085 runs = dst.runs;
1086 old_runs = dst.old_runs;
1089 * Copy diff variables
1091 si = dst.si;
1092 ax_count = dst.ax_count;
1093 frame = dst.frame;
1094 perturb_multipliers = dst.perturb_multipliers;
1096 return *this;
1099 diff_stat_t(const diff_stat_t &dst) : runs(), old_runs(),
1100 perturb_multipliers() {
1101 operator=(dst);
1104 ale_accum get_result() {
1105 assert(runs.size() == 1);
1106 return runs[0].result;
1109 ale_accum get_divisor() {
1110 assert(runs.size() == 1);
1111 return runs[0].divisor;
1114 transformation get_offset() {
1115 assert(runs.size() == 1);
1116 return runs[0].offset;
1119 int operator!=(diff_stat_t &param) {
1120 return (get_error() != param.get_error());
1123 int operator==(diff_stat_t &param) {
1124 return !(operator!=(param));
1127 ale_pos get_error_perturb() {
1128 assert(runs.size() == 1);
1129 return runs[0].get_error_perturb();
1132 ale_accum get_error() const {
1133 assert(runs.size() == 1);
1134 return runs[0].get_error();
1137 public:
1139 * Get the set of transformations produced by a given perturbation
1141 void get_perturb_set(std::vector<transformation> *set,
1142 ale_pos adj_p, ale_pos adj_o, ale_pos adj_b,
1143 ale_pos *current_bd, ale_pos *modified_bd,
1144 std::vector<ale_pos> multipliers = std::vector<ale_pos>()) {
1146 assert(runs.size() == 1);
1148 transformation test_t;
1151 * Translational or euclidean transformation
1154 for (unsigned int i = 0; i < 2; i++)
1155 for (unsigned int s = 0; s < 2; s++) {
1157 if (!multipliers.size())
1158 multipliers.push_back(1);
1160 assert(finite(multipliers[0]));
1162 test_t = get_offset();
1164 // test_t.eu_modify(i, (s ? -adj_p : adj_p) * multipliers[0]);
1165 test_t.translate((i ? point(1, 0) : point(0, 1))
1166 * (s ? -adj_p : adj_p)
1167 * multipliers[0]);
1169 test_t.snap(adj_p / 2);
1171 set->push_back(test_t);
1172 multipliers.erase(multipliers.begin());
1176 if (alignment_class > 0)
1177 for (unsigned int s = 0; s < 2; s++) {
1179 if (!multipliers.size())
1180 multipliers.push_back(1);
1182 assert(multipliers.size());
1183 assert(finite(multipliers[0]));
1185 if (!(adj_o * multipliers[0] < rot_max))
1186 return;
1188 ale_pos adj_s = (s ? 1 : -1) * adj_o * multipliers[0];
1190 test_t = get_offset();
1192 run_index ori = get_run_index(set->size());
1193 point centroid = point::undefined();
1195 if (!old_runs.count(ori))
1196 ori = get_run_index(0);
1198 if (!centroid.finite() && old_runs.count(ori)) {
1199 centroid = old_runs[ori].get_error_centroid();
1201 if (!centroid.finite())
1202 centroid = old_runs[ori].get_centroid();
1204 centroid *= test_t.scale()
1205 / old_runs[ori].offset.scale();
1208 if (!centroid.finite() && !test_t.is_projective()) {
1209 test_t.eu_modify(2, adj_s);
1210 } else if (!centroid.finite()) {
1211 centroid = point(si.input->height() / 2,
1212 si.input->width() / 2);
1214 test_t.rotate(centroid + si.accum->offset(),
1215 adj_s);
1216 } else {
1217 test_t.rotate(centroid + si.accum->offset(),
1218 adj_s);
1221 test_t.snap(adj_p / 2);
1223 set->push_back(test_t);
1224 multipliers.erase(multipliers.begin());
1227 if (alignment_class == 2) {
1230 * Projective transformation
1233 for (unsigned int i = 0; i < 4; i++)
1234 for (unsigned int j = 0; j < 2; j++)
1235 for (unsigned int s = 0; s < 2; s++) {
1237 if (!multipliers.size())
1238 multipliers.push_back(1);
1240 assert(multipliers.size());
1241 assert(finite(multipliers[0]));
1243 ale_pos adj_s = (s ? -1 : 1) * adj_p * multipliers [0];
1245 test_t = get_offset();
1247 if (perturb_type == 0)
1248 test_t.gpt_modify(j, i, adj_s);
1249 else if (perturb_type == 1)
1250 test_t.gr_modify(j, i, adj_s);
1251 else
1252 assert(0);
1254 test_t.snap(adj_p / 2);
1256 set->push_back(test_t);
1257 multipliers.erase(multipliers.begin());
1263 * Barrel distortion
1266 if (bda_mult != 0 && adj_b != 0) {
1268 for (unsigned int d = 0; d < get_offset().bd_count(); d++)
1269 for (unsigned int s = 0; s < 2; s++) {
1271 if (!multipliers.size())
1272 multipliers.push_back(1);
1274 assert (multipliers.size());
1275 assert (finite(multipliers[0]));
1277 ale_pos adj_s = (s ? -1 : 1) * adj_b * multipliers[0];
1279 if (bda_rate > 0 && fabs(modified_bd[d] + adj_s - current_bd[d]) > bda_rate)
1280 continue;
1282 transformation test_t = get_offset();
1284 test_t.bd_modify(d, adj_s);
1286 set->push_back(test_t);
1291 void confirm() {
1292 assert(runs.size() == 2);
1293 runs[0] = runs[1];
1294 runs.pop_back();
1297 void discard() {
1298 assert(runs.size() == 2);
1299 runs.pop_back();
1302 void perturb_test(ale_pos perturb, ale_pos adj_p, ale_pos adj_o, ale_pos adj_b,
1303 ale_pos *current_bd, ale_pos *modified_bd, int stable) {
1305 assert(runs.size() == 1);
1307 std::vector<transformation> t_set;
1309 if (perturb_multipliers.size() == 0) {
1310 get_perturb_set(&t_set, adj_p, adj_o, adj_b,
1311 current_bd, modified_bd);
1313 for (unsigned int i = 0; i < t_set.size(); i++) {
1314 diff_stat_t test = *this;
1316 test.diff(si, perturb, t_set[i], ax_count, frame);
1318 test.confirm();
1320 if (finite(adj_p / test.get_error_perturb()))
1321 perturb_multipliers.push_back(adj_p / test.get_error_perturb());
1322 else
1323 perturb_multipliers.push_back(1);
1327 t_set.clear();
1330 get_perturb_set(&t_set, adj_p, adj_o, adj_b, current_bd, modified_bd,
1331 perturb_multipliers);
1333 int found_unreliable = 1;
1334 std::vector<int> tested(t_set.size(), 0);
1336 for (unsigned int i = 0; i < t_set.size(); i++) {
1337 run_index ori = get_run_index(i);
1340 * Check for stability
1342 if (stable
1343 && old_runs.count(ori)
1344 && old_runs[ori].offset == t_set[i])
1345 tested[i] = 1;
1348 std::vector<ale_pos> perturb_multipliers_original = perturb_multipliers;
1350 while (found_unreliable) {
1352 found_unreliable = 0;
1354 for (unsigned int i = 0; i < t_set.size(); i++) {
1356 if (tested[i])
1357 continue;
1359 diff(si, perturb, t_set[i], ax_count, frame);
1361 if (!(i < perturb_multipliers.size())
1362 || !finite(perturb_multipliers[i])) {
1364 perturb_multipliers.resize(i + 1);
1366 perturb_multipliers[i] =
1367 adj_p / runs[1].get_error_perturb();
1369 if (finite(perturb_multipliers[i]))
1370 found_unreliable = 1;
1372 continue;
1375 run_index ori = get_run_index(i);
1377 if (old_runs.count(ori) == 0)
1378 old_runs.insert(std::pair<run_index, run>(ori, runs[1]));
1379 else
1380 old_runs[ori] = runs[1];
1382 perturb_multipliers[i] = perturb_multipliers_original[i]
1383 * adj_p / runs[1].get_error_perturb();
1385 if (!finite(perturb_multipliers[i]))
1386 perturb_multipliers[i] = 1;
1388 tested[i] = 1;
1390 if (better()
1391 && runs[1].get_error() < runs[0].get_error()
1392 && perturb_multipliers[i]
1393 / perturb_multipliers_original[i] < 2) {
1394 runs[0] = runs[1];
1395 runs.pop_back();
1396 return;
1401 if (runs.size() > 1)
1402 runs.pop_back();
1404 if (!found_unreliable)
1405 return;
1410 * Attempt to make the current element non-trivial, by finding a nearby
1411 * alignment admitting a non-empty element region.
1413 void make_element_nontrivial(ale_pos adj_p, ale_pos adj_o) {
1414 assert(runs.size() == 1);
1416 transformation *t = &runs[0].offset;
1418 if (t->is_nontrivial())
1419 return;
1421 calculate_element_region();
1423 if (t->is_nontrivial())
1424 return;
1426 std::vector<transformation> t_set;
1427 get_perturb_set(&t_set, adj_p, adj_o, 0, NULL, NULL);
1429 for (unsigned int i = 0; i < t_set.size(); i++) {
1431 align::calculate_element_region(&t_set[i], si, ax_count);
1433 if (t_set[i].is_nontrivial()) {
1434 *t = t_set[i];
1435 return;
1444 * Adjust exposure for an aligned frame B against reference A.
1446 * Expects full-LOD images.
1448 * Note: This method does not use any weighting, by certainty or
1449 * otherwise, in the first exposure registration pass, as any bias of
1450 * weighting according to color may also bias the exposure registration
1451 * result; it does use weighting, including weighting by certainty
1452 * (even if certainty weighting is not specified), in the second pass,
1453 * under the assumption that weighting by certainty improves handling
1454 * of out-of-range highlights, and that bias of exposure measurements
1455 * according to color may generally be less harmful after spatial
1456 * registration has been performed.
1458 class exposure_ratio_iterate : public thread::decompose_domain {
1459 pixel_accum *asums;
1460 pixel_accum *bsums;
1461 pixel_accum *asum;
1462 pixel_accum *bsum;
1463 struct scale_cluster c;
1464 transformation t;
1465 int ax_count;
1466 int pass_number;
1467 protected:
1468 void prepare_subdomains(unsigned int N) {
1469 asums = new pixel_accum[N];
1470 bsums = new pixel_accum[N];
1472 void subdomain_algorithm(unsigned int thread,
1473 int i_min, int i_max, int j_min, int j_max) {
1475 point offset = c.accum->offset();
1477 for (mc_iterate m(i_min, i_max, j_min, j_max, thread); !m.done(); m++) {
1479 unsigned int i = (unsigned int) m.get_i();
1480 unsigned int j = (unsigned int) m.get_j();
1482 if (ref_excluded(i, j, offset, c.ax_parameters, ax_count))
1483 continue;
1486 * Transform
1489 struct point q;
1491 q = (c.input_scale < 1.0 && interpolant == NULL)
1492 ? t.scaled_inverse_transform(
1493 point(i + offset[0], j + offset[1]))
1494 : t.unscaled_inverse_transform(
1495 point(i + offset[0], j + offset[1]));
1498 * Check that the transformed coordinates are within
1499 * the boundaries of array c.input, that they are not
1500 * subject to exclusion, and that the weight value in
1501 * the accumulated array is nonzero.
1504 if (input_excluded(q[0], q[1], c.ax_parameters, ax_count))
1505 continue;
1507 if (q[0] >= 0
1508 && q[0] <= c.input->height() - 1
1509 && q[1] >= 0
1510 && q[1] <= c.input->width() - 1
1511 && c.certainty->get_pixel(i, j).minabs_norm() != 0) {
1512 pixel a = c.accum->get_pixel(i, j);
1513 pixel b;
1515 b = c.input->get_bl(q);
1517 pixel weight = ((c.aweight && pass_number)
1518 ? c.aweight->get_pixel(i, j)
1519 : pixel(1, 1, 1))
1520 * (pass_number
1521 ? ppow(c.certainty->get_pixel(i, j)
1522 * c.input_certainty->get_bl(q, 1), 0.5)
1523 : pixel(1, 1, 1));
1525 asums[thread] += a * weight;
1526 bsums[thread] += b * weight;
1531 void finish_subdomains(unsigned int N) {
1532 for (unsigned int n = 0; n < N; n++) {
1533 *asum += asums[n];
1534 *bsum += bsums[n];
1536 delete asums;
1537 delete bsums;
1539 public:
1540 exposure_ratio_iterate(pixel_accum *_asum,
1541 pixel_accum *_bsum,
1542 struct scale_cluster _c,
1543 transformation _t,
1544 int _ax_count,
1545 int _pass_number) : decompose_domain(0, _c.accum->height(),
1546 0, _c.accum->width()){
1548 asum = _asum;
1549 bsum = _bsum;
1550 c = _c;
1551 t = _t;
1552 ax_count = _ax_count;
1553 pass_number = _pass_number;
1557 static void set_exposure_ratio(unsigned int m, struct scale_cluster c,
1558 transformation t, int ax_count, int pass_number) {
1560 if (_exp_register == 2) {
1562 * Use metadata only.
1564 ale_real gain_multiplier = image_rw::exp(m).get_gain_multiplier();
1565 pixel multiplier = pixel(gain_multiplier, gain_multiplier, gain_multiplier);
1567 image_rw::exp(m).set_multiplier(multiplier);
1568 ui::get()->exp_multiplier(multiplier[0],
1569 multiplier[1],
1570 multiplier[2]);
1572 return;
1575 pixel_accum asum(0, 0, 0), bsum(0, 0, 0);
1577 exposure_ratio_iterate eri(&asum, &bsum, c, t, ax_count, pass_number);
1578 eri.run();
1580 // std::cerr << (asum / bsum) << " ";
1582 pixel_accum new_multiplier;
1584 new_multiplier = asum / bsum * image_rw::exp(m).get_multiplier();
1586 if (finite(new_multiplier[0])
1587 && finite(new_multiplier[1])
1588 && finite(new_multiplier[2])) {
1589 image_rw::exp(m).set_multiplier(new_multiplier);
1590 ui::get()->exp_multiplier(new_multiplier[0],
1591 new_multiplier[1],
1592 new_multiplier[2]);
1597 * Copy all ax parameters.
1599 static exclusion *copy_ax_parameters(int local_ax_count, exclusion *source) {
1601 exclusion *dest = (exclusion *) malloc(local_ax_count * sizeof(exclusion));
1603 assert (dest);
1605 if (!dest)
1606 ui::get()->memory_error("exclusion regions");
1608 for (int idx = 0; idx < local_ax_count; idx++)
1609 dest[idx] = source[idx];
1611 return dest;
1615 * Copy ax parameters according to frame.
1617 static exclusion *filter_ax_parameters(int frame, int *local_ax_count) {
1619 exclusion *dest = (exclusion *) malloc(ax_count * sizeof(exclusion));
1621 assert (dest);
1623 if (!dest)
1624 ui::get()->memory_error("exclusion regions");
1626 *local_ax_count = 0;
1628 for (int idx = 0; idx < ax_count; idx++) {
1629 if (ax_parameters[idx].x[4] > frame
1630 || ax_parameters[idx].x[5] < frame)
1631 continue;
1633 dest[*local_ax_count] = ax_parameters[idx];
1635 (*local_ax_count)++;
1638 return dest;
1641 static void scale_ax_parameters(int local_ax_count, exclusion *ax_parameters,
1642 ale_pos ref_scale, ale_pos input_scale) {
1643 for (int i = 0; i < local_ax_count; i++) {
1644 ale_pos scale = (ax_parameters[i].type == exclusion::RENDER)
1645 ? ref_scale
1646 : input_scale;
1648 for (int n = 0; n < 6; n++) {
1649 ax_parameters[i].x[n] = ax_parameters[i].x[n] * scale;
1655 * Prepare the next level of detail for ordinary images.
1657 static const image *prepare_lod(const image *current) {
1658 if (current == NULL)
1659 return NULL;
1661 return current->scale_by_half("prepare_lod");
1665 * Prepare the next level of detail for definition maps.
1667 static const image *prepare_lod_def(const image *current) {
1668 if (current == NULL)
1669 return NULL;
1671 return current->defined_scale_by_half("prepare_lod_def");
1675 * Initialize scale cluster data structures.
1678 static void init_nl_cluster(struct scale_cluster *sc) {
1681 static struct scale_cluster *init_clusters(int frame, ale_real scale_factor,
1682 const image *input_frame, unsigned int steps,
1683 int *local_ax_count) {
1686 * Allocate memory for the array.
1689 struct scale_cluster *scale_clusters =
1690 (struct scale_cluster *) malloc(steps * sizeof(struct scale_cluster));
1692 assert (scale_clusters);
1694 if (!scale_clusters)
1695 ui::get()->memory_error("alignment");
1698 * Prepare images and exclusion regions for the highest level
1699 * of detail.
1702 scale_clusters[0].accum = reference_image;
1704 ui::get()->constructing_lod_clusters(0.0);
1705 scale_clusters[0].input_scale = scale_factor;
1706 if (scale_factor < 1.0 && interpolant == NULL)
1707 scale_clusters[0].input = input_frame->scale(scale_factor, "alignment");
1708 else
1709 scale_clusters[0].input = input_frame;
1711 scale_clusters[0].certainty = reference_defined->clone("certainty");
1712 scale_clusters[0].aweight = alignment_weights;
1713 scale_clusters[0].ax_parameters = filter_ax_parameters(frame, local_ax_count);
1716 * Allocate and determine input frame certainty.
1719 if (scale_clusters[0].input->get_bayer() != IMAGE_BAYER_NONE) {
1720 scale_clusters[0].input_certainty = new image_bayer_ale_real(
1721 scale_clusters[0].input->height(),
1722 scale_clusters[0].input->width(),
1723 scale_clusters[0].input->depth(),
1724 scale_clusters[0].input->get_bayer());
1725 } else {
1726 scale_clusters[0].input_certainty = scale_clusters[0].input->clone("certainty");
1729 for (unsigned int i = 0; i < scale_clusters[0].input_certainty->height(); i++)
1730 for (unsigned int j = 0; j < scale_clusters[0].input_certainty->width(); j++)
1731 for (unsigned int k = 0; k < 3; k++)
1732 if (scale_clusters[0].input->get_channels(i, j) & k)
1733 ((image *) scale_clusters[0].input_certainty)->chan(i, j, k) =
1734 scale_clusters[0].input->
1735 exp().confidence(scale_clusters[0].input->get_pixel(i, j))[k];
1737 scale_ax_parameters(*local_ax_count, scale_clusters[0].ax_parameters, scale_factor,
1738 (scale_factor < 1.0 && interpolant == NULL) ? scale_factor : 1);
1740 init_nl_cluster(&(scale_clusters[0]));
1743 * Prepare reduced-detail images and exclusion
1744 * regions.
1747 for (unsigned int step = 1; step < steps; step++) {
1748 ui::get()->constructing_lod_clusters(step);
1749 scale_clusters[step].accum = prepare_lod(scale_clusters[step - 1].accum);
1750 scale_clusters[step].certainty = prepare_lod_def(scale_clusters[step - 1].certainty);
1751 scale_clusters[step].aweight = prepare_lod_def(scale_clusters[step - 1].aweight);
1752 scale_clusters[step].ax_parameters
1753 = copy_ax_parameters(*local_ax_count, scale_clusters[step - 1].ax_parameters);
1755 double sf = scale_clusters[step - 1].input_scale / 2;
1756 scale_clusters[step].input_scale = sf;
1758 if (sf >= 1.0 || interpolant != NULL) {
1759 scale_clusters[step].input = scale_clusters[step - 1].input;
1760 scale_clusters[step].input_certainty = scale_clusters[step - 1].input_certainty;
1761 scale_ax_parameters(*local_ax_count, scale_clusters[step].ax_parameters, 0.5, 1);
1762 } else if (sf > 0.5) {
1763 scale_clusters[step].input = scale_clusters[step - 1].input->scale(sf, "alignment");
1764 scale_clusters[step].input_certainty = scale_clusters[step - 1].input->scale(sf, "alignment", 1);
1765 scale_ax_parameters(*local_ax_count, scale_clusters[step].ax_parameters, 0.5, sf);
1766 } else {
1767 scale_clusters[step].input = scale_clusters[step - 1].input->scale(0.5, "alignment");
1768 scale_clusters[step].input_certainty = scale_clusters[step - 1].input_certainty->scale(0.5, "alignment", 1);
1769 scale_ax_parameters(*local_ax_count, scale_clusters[step].ax_parameters, 0.5, 0.5);
1772 init_nl_cluster(&(scale_clusters[step]));
1775 return scale_clusters;
1779 * Destroy the first element in the scale cluster data structure.
1781 static void final_clusters(struct scale_cluster *scale_clusters, ale_real scale_factor,
1782 unsigned int steps) {
1784 if (scale_clusters[0].input_scale < 1.0)
1785 delete scale_clusters[0].input;
1787 free((void *)scale_clusters[0].ax_parameters);
1789 delete scale_clusters[0].certainty;
1791 for (unsigned int step = 1; step < steps; step++) {
1792 delete scale_clusters[step].accum;
1793 delete scale_clusters[step].certainty;
1794 delete scale_clusters[step].aweight;
1796 if (scale_clusters[step].input_scale < 1.0)
1797 delete scale_clusters[step].input;
1799 free((void *)scale_clusters[step].ax_parameters);
1802 free(scale_clusters);
1806 * Calculate the centroid of a control point for the set of frames
1807 * having index lower than m. Divide by any scaling of the output.
1809 static point unscaled_centroid(unsigned int m, unsigned int p) {
1810 assert(_keep);
1812 point point_sum(0, 0);
1813 ale_accum divisor = 0;
1815 for(unsigned int j = 0; j < m; j++) {
1816 point pp = cp_array[p][j];
1818 if (pp.defined()) {
1819 point_sum += kept_t[j].transform_unscaled(pp)
1820 / kept_t[j].scale();
1821 divisor += 1;
1825 if (divisor == 0)
1826 return point::undefined();
1828 return point_sum / divisor;
1832 * Calculate centroid of this frame, and of all previous frames,
1833 * from points common to both sets.
1835 static void centroids(unsigned int m, point *current, point *previous) {
1837 * Calculate the translation
1839 point other_centroid(0, 0);
1840 point this_centroid(0, 0);
1841 ale_pos divisor = 0;
1843 for (unsigned int i = 0; i < cp_count; i++) {
1844 point other_c = unscaled_centroid(m, i);
1845 point this_c = cp_array[i][m];
1847 if (!other_c.defined() || !this_c.defined())
1848 continue;
1850 other_centroid += other_c;
1851 this_centroid += this_c;
1852 divisor += 1;
1856 if (divisor == 0) {
1857 *current = point::undefined();
1858 *previous = point::undefined();
1859 return;
1862 *current = this_centroid / divisor;
1863 *previous = other_centroid / divisor;
1867 * Calculate the RMS error of control points for frame m, with
1868 * transformation t, against control points for earlier frames.
1870 static ale_accum cp_rms_error(unsigned int m, transformation t) {
1871 assert (_keep);
1873 ale_accum err = 0;
1874 ale_accum divisor = 0;
1876 for (unsigned int i = 0; i < cp_count; i++)
1877 for (unsigned int j = 0; j < m; j++) {
1878 const point *p = cp_array[i];
1879 point p_ref = kept_t[j].transform_unscaled(p[j]);
1880 point p_cur = t.transform_unscaled(p[m]);
1882 if (!p_ref.defined() || !p_cur.defined())
1883 continue;
1885 err += p_ref.lengthtosq(p_cur);
1886 divisor += 1;
1889 return sqrt(err / divisor);
1893 * Implement new delta --follow semantics.
1895 * If we have a transformation T such that
1897 * prev_final == T(prev_init)
1899 * Then we also have
1901 * current_init_follow == T(current_init)
1903 * We can calculate T as follows:
1905 * T == prev_final(prev_init^-1)
1907 * Where ^-1 is the inverse operator.
1909 static transformation follow(element_t *element, transformation offset, int lod) {
1911 transformation new_offset = offset;
1914 * Criteria for using following.
1917 if (!element->old_is_default && !element->is_default &&
1918 default_initial_alignment_type == 1) {
1920 * Ensure that the lod for the old initial and final
1921 * alignments are equal to the lod for the new initial
1922 * alignment.
1925 ui::get()->following();
1927 element->old_final_alignment.rescale (1 / pow(2, lod));
1928 element->old_initial_alignment.rescale(1 / pow(2, lod - element->old_lod));
1930 for (offset.set_current_index(0),
1931 element->old_initial_alignment.set_current_index(0),
1932 element->old_final_alignment.set_current_index(0),
1933 new_offset.set_current_index(0);
1935 offset.get_current_index() < _ma_card;
1937 offset.push_element(),
1938 new_offset.push_element()) {
1940 if (alignment_class == 0) {
1942 * Translational transformations
1945 ale_pos t0 = -element->old_initial_alignment.eu_get(0)
1946 + element->old_final_alignment.eu_get(0);
1947 ale_pos t1 = -element->old_initial_alignment.eu_get(1)
1948 + element->old_final_alignment.eu_get(1);
1950 new_offset.eu_modify(0, t0);
1951 new_offset.eu_modify(1, t1);
1953 } else if (alignment_class == 1) {
1955 * Euclidean transformations
1958 ale_pos t2 = -element->old_initial_alignment.eu_get(2)
1959 + element->old_final_alignment.eu_get(2);
1961 new_offset.eu_modify(2, t2);
1963 point p( offset.scaled_height()/2 + offset.eu_get(0) - element->old_initial_alignment.eu_get(0),
1964 offset.scaled_width()/2 + offset.eu_get(1) - element->old_initial_alignment.eu_get(1) );
1966 p = element->old_final_alignment.transform_scaled(p);
1968 new_offset.eu_modify(0, p[0] - offset.scaled_height()/2 - offset.eu_get(0));
1969 new_offset.eu_modify(1, p[1] - offset.scaled_width()/2 - offset.eu_get(1));
1971 } else if (alignment_class == 2) {
1973 * Projective transformations
1976 point p[4];
1978 p[0] = element->old_final_alignment.transform_scaled(element->old_initial_alignment
1979 . scaled_inverse_transform(offset.get_current_element().transform_scaled(point( 0 , 0 ))));
1980 p[1] = element->old_final_alignment.transform_scaled(element->old_initial_alignment
1981 . scaled_inverse_transform(offset.get_current_element().transform_scaled(point(offset.scaled_height(), 0 ))));
1982 p[2] = element->old_final_alignment.transform_scaled(element->old_initial_alignment
1983 . scaled_inverse_transform(offset.get_current_element().transform_scaled(point(offset.scaled_height(), offset.scaled_width()))));
1984 p[3] = element->old_final_alignment.transform_scaled(element->old_initial_alignment
1985 . scaled_inverse_transform(offset.get_current_element().transform_scaled(point( 0 , offset.scaled_width()))));
1987 new_offset.gpt_set(p);
1991 ui::get()->set_offset(offset);
1994 return new_offset;
1997 static void test_global(diff_stat_t *here, scale_cluster si, transformation t,
1998 int local_ax_count, int m, ale_pos local_gs_mo, ale_pos perturb) {
2000 diff_stat_t test(*here);
2002 test.diff(si, perturb, t, local_ax_count, m);
2004 unsigned int ovl = overlap(si, t, local_ax_count);
2006 if (ovl >= local_gs_mo && test.better()) {
2007 test.confirm();
2008 *here = test;
2009 ui::get()->set_match(here->get_error());
2010 ui::get()->set_offset(here->get_offset());
2011 } else {
2012 test.discard();
2018 * Get the set of global transformations for a given density
2020 static void test_globals(diff_stat_t *here,
2021 scale_cluster si, transformation t, int local_gs, ale_pos adj_p,
2022 int local_ax_count, int m, ale_pos local_gs_mo, ale_pos perturb) {
2024 transformation offset = t;
2026 point min, max;
2028 transformation offset_p = offset;
2030 if (!offset_p.is_projective())
2031 offset_p.eu_to_gpt();
2033 min = max = offset_p.gpt_get(0);
2034 for (int p_index = 1; p_index < 4; p_index++) {
2035 point p = offset_p.gpt_get(p_index);
2036 if (p[0] < min[0])
2037 min[0] = p[0];
2038 if (p[1] < min[1])
2039 min[1] = p[1];
2040 if (p[0] > max[0])
2041 max[0] = p[0];
2042 if (p[1] > max[1])
2043 max[1] = p[1];
2046 point inner_min_t = -min;
2047 point inner_max_t = -max + point(si.accum->height(), si.accum->width());
2048 point outer_min_t = -max + point(adj_p - 1, adj_p - 1);
2049 point outer_max_t = point(si.accum->height(), si.accum->width()) - point(adj_p, adj_p);
2051 if (local_gs == 1 || local_gs == 3 || local_gs == 4 || local_gs == 6) {
2054 * Inner
2057 for (ale_pos i = inner_min_t[0]; i <= inner_max_t[0]; i += adj_p)
2058 for (ale_pos j = inner_min_t[1]; j <= inner_max_t[1]; j += adj_p) {
2059 transformation test_t = offset;
2060 test_t.translate(point(i, j));
2061 test_global(here, si, test_t, local_ax_count, m, local_gs_mo, perturb);
2065 if (local_gs == 2 || local_gs == 3 || local_gs == -1 || local_gs == 6) {
2068 * Outer
2071 for (ale_pos i = outer_min_t[0]; i <= outer_max_t[0]; i += adj_p)
2072 for (ale_pos j = outer_min_t[1]; j < inner_min_t[1]; j += adj_p) {
2073 transformation test_t = offset;
2074 test_t.translate(point(i, j));
2075 test_global(here, si, test_t, local_ax_count, m, local_gs_mo, perturb);
2077 for (ale_pos i = outer_min_t[0]; i <= outer_max_t[0]; i += adj_p)
2078 for (ale_pos j = outer_max_t[1]; j > inner_max_t[1]; j -= adj_p) {
2079 transformation test_t = offset;
2080 test_t.translate(point(i, j));
2081 test_global(here, si, test_t, local_ax_count, m, local_gs_mo, perturb);
2083 for (ale_pos i = outer_min_t[0]; i < inner_min_t[0]; i += adj_p)
2084 for (ale_pos j = outer_min_t[1]; j <= outer_max_t[1]; j += adj_p) {
2085 transformation test_t = offset;
2086 test_t.translate(point(i, j));
2087 test_global(here, si, test_t, local_ax_count, m, local_gs_mo, perturb);
2089 for (ale_pos i = outer_max_t[0]; i > inner_max_t[0]; i -= adj_p)
2090 for (ale_pos j = outer_min_t[1]; j <= outer_max_t[1]; j += adj_p) {
2091 transformation test_t = offset;
2092 test_t.translate(point(i, j));
2093 test_global(here, si, test_t, local_ax_count, m, local_gs_mo, perturb);
2098 static void get_translational_set(std::vector<transformation> *set,
2099 transformation t, ale_pos adj_p) {
2101 ale_pos adj_s;
2103 transformation offset = t;
2104 transformation test_t;
2106 for (int i = 0; i < 2; i++)
2107 for (adj_s = -adj_p; adj_s <= adj_p; adj_s += 2 * adj_p) {
2109 test_t = offset;
2111 test_t.translate(i ? point(adj_s, 0) : point(0, adj_s));
2113 set->push_back(test_t);
2117 static int threshold_ok(ale_accum error) {
2118 if ((1 - error) * 100 >= match_threshold)
2119 return 1;
2121 if (!(match_threshold >= 0))
2122 return 1;
2124 return 0;
2128 * Align frame m against the reference.
2130 * XXX: the transformation class currently combines ordinary
2131 * transformations with scaling. This is somewhat convenient for
2132 * some things, but can also be confusing. This method, _align(), is
2133 * one case where special care must be taken to ensure that the scale
2134 * is always set correctly (by using the 'rescale' method).
2136 static diff_stat_t _align(int m, int local_gs, element_t *element) {
2138 const image *input_frame = element->input_frame;
2141 * Local upper/lower data, possibly dependent on image
2142 * dimensions.
2145 ale_pos local_lower, local_upper, local_gs_mo;
2148 * Select the minimum dimension as the reference.
2151 ale_pos reference_size = input_frame->height();
2152 if (input_frame->width() < reference_size)
2153 reference_size = input_frame->width();
2154 ale_pos reference_area = input_frame->height()
2155 * input_frame->width();
2157 if (perturb_lower_percent)
2158 local_lower = perturb_lower
2159 * reference_size
2160 * 0.01
2161 * scale_factor;
2162 else
2163 local_lower = perturb_lower;
2165 if (perturb_upper_percent)
2166 local_upper = perturb_upper
2167 * reference_size
2168 * 0.01
2169 * scale_factor;
2170 else
2171 local_upper = perturb_upper;
2173 local_upper = pow(2, floor(log(local_upper) / log(2)));
2175 if (gs_mo_percent)
2176 local_gs_mo = _gs_mo
2177 * reference_area
2178 * 0.01
2179 * scale_factor;
2180 else
2181 local_gs_mo = _gs_mo;
2184 * Logarithms aren't exact, so we divide repeatedly to discover
2185 * how many steps will occur, and pass this information to the
2186 * user interface.
2189 int step_count = 0;
2190 double step_variable = local_upper;
2191 while (step_variable >= local_lower) {
2192 step_variable /= 2;
2193 step_count++;
2196 ui::get()->set_steps(step_count);
2198 ale_pos perturb = local_upper;
2199 int lod;
2201 if (_keep) {
2202 kept_t[latest] = latest_t;
2203 kept_ok[latest] = latest_ok;
2207 * Maximum level-of-detail. Use a level of detail at most
2208 * 2^lod_diff finer than the adjustment resolution. lod_diff
2209 * is a synonym for lod_max.
2212 const int lod_diff = lod_max;
2215 * Determine how many levels of detail should be prepared.
2219 * Plain (unsigned int) casting seems to be broken in some cases.
2222 unsigned int steps = (perturb > pow(2, lod_max))
2223 ? (unsigned int) lrint(log(perturb) / log(2)) - lod_max + 1 : 1;
2226 * Prepare multiple levels of detail.
2229 int local_ax_count;
2230 struct scale_cluster *scale_clusters = init_clusters(m,
2231 scale_factor, input_frame, steps,
2232 &local_ax_count);
2235 * Initialize variables used in the main loop.
2238 lod = (steps - 1);
2241 * Initialize the default initial transform
2244 if (default_initial_alignment_type == 0) {
2247 * Follow the transformation of the original frame,
2248 * setting new image dimensions.
2251 // element->default_initial_alignment = orig_t;
2252 element->default_initial_alignment.set_current_element(orig_t.get_element(0));
2253 element->default_initial_alignment.set_dimensions(input_frame);
2255 } else if (default_initial_alignment_type == 1)
2258 * Follow previous transformation, setting new image
2259 * dimensions.
2262 element->default_initial_alignment.set_dimensions(input_frame);
2264 else
2265 assert(0);
2267 element->old_is_default = element->is_default;
2270 * Scale default initial transform for lod
2273 element->default_initial_alignment.rescale(1 / pow(2, lod));
2276 * Set the default transformation.
2279 transformation offset = element->default_initial_alignment;
2282 * Load any file-specified transformations
2285 for (offset.set_current_index(0);
2286 offset.get_current_index() < _ma_card;
2287 offset.push_element()) {
2289 offset = tload_next(tload, alignment_class == 2,
2290 offset,
2291 &element->is_default,
2292 offset.get_current_index() == 0);
2296 offset.set_current_index(0);
2298 ui::get()->set_offset(offset);
2300 if (perturb > 0) {
2303 * Apply following logic
2306 transformation new_offset = follow(element, offset, lod);
2308 new_offset.set_current_index(0);
2310 element->old_initial_alignment = offset;
2311 element->old_lod = lod;
2312 offset = new_offset;
2314 } else {
2315 element->old_initial_alignment = offset;
2316 element->old_lod = lod;
2319 struct scale_cluster si = scale_clusters[lod];
2322 * Projective adjustment value
2325 ale_pos adj_p = (perturb >= pow(2, lod_diff))
2326 ? pow(2, lod_diff) : (double) perturb;
2329 * Orientational adjustment value in degrees.
2331 * Since rotational perturbation is now specified as an
2332 * arclength, we have to convert.
2335 ale_pos adj_o = 2 * perturb
2336 / sqrt(pow(scale_clusters[0].input->height(), 2)
2337 + pow(scale_clusters[0].input->width(), 2))
2338 * 180
2339 / M_PI;
2342 * Barrel distortion adjustment value
2345 ale_pos adj_b = perturb * bda_mult;
2348 * Global search overlap requirements.
2351 local_gs_mo /= pow(pow(2, lod), 2);
2354 * Pre-alignment exposure adjustment
2357 if (_exp_register) {
2358 ui::get()->exposure_1();
2359 transformation o = offset;
2360 for (int k = lod; k > 0; k--)
2361 o.rescale(2);
2362 set_exposure_ratio(m, scale_clusters[0], o, local_ax_count, 0);
2366 * Alignment statistics.
2369 diff_stat_t here;
2372 * Current difference (error) value
2375 ui::get()->prematching();
2376 here.diff(si, perturb, offset, local_ax_count, m);
2377 ui::get()->set_match(here.get_error());
2380 * Current and modified barrel distortion parameters
2383 ale_pos current_bd[BARREL_DEGREE];
2384 ale_pos modified_bd[BARREL_DEGREE];
2385 offset.bd_get(current_bd);
2386 offset.bd_get(modified_bd);
2389 * Translational global search step
2392 if (perturb >= local_lower && local_gs != 0 && local_gs != 5
2393 && (local_gs != 6 || element->is_default)) {
2395 ui::get()->global_alignment(perturb, lod);
2396 ui::get()->gs_mo(local_gs_mo);
2398 test_globals(&here, si, here.get_offset(), local_gs, adj_p,
2399 local_ax_count, m, local_gs_mo, perturb);
2401 ui::get()->set_match(here.get_error());
2402 ui::get()->set_offset(here.get_offset());
2406 * Control point alignment
2409 if (local_gs == 5) {
2411 transformation o = here.get_offset();
2413 for (int k = lod; k > 0; k--)
2414 o.rescale(2);
2417 * Determine centroid data
2420 point current, previous;
2421 centroids(m, &current, &previous);
2423 if (current.defined() && previous.defined()) {
2424 o = orig_t;
2425 o.set_dimensions(input_frame);
2426 o.translate((previous - current) * o.scale());
2427 current = previous;
2431 * Determine rotation for alignment classes other than translation.
2434 ale_accum lowest_error = cp_rms_error(m, o);
2436 ale_pos rot_lower = 2 * local_lower
2437 / sqrt(pow(scale_clusters[0].input->height(), 2)
2438 + pow(scale_clusters[0].input->width(), 2))
2439 * 180
2440 / M_PI;
2442 if (alignment_class > 0)
2443 for (ale_pos rot = 30; rot > rot_lower; rot /= 2)
2444 for (ale_pos srot = -rot; srot < rot * 1.5; srot += rot * 2) {
2445 int is_improved = 1;
2446 while (is_improved) {
2447 is_improved = 0;
2448 transformation test_t = o;
2450 * XXX: is this right?
2452 test_t.rotate(current * o.scale(), srot);
2453 ale_pos test_v = cp_rms_error(m, test_t);
2455 if (test_v < lowest_error) {
2456 lowest_error = test_v;
2457 o = test_t;
2458 srot += 3 * rot;
2459 is_improved = 1;
2465 * Determine projective parameters through a local
2466 * minimum search.
2469 if (alignment_class == 2) {
2470 ale_accum adj_p = lowest_error;
2472 if (adj_p < local_lower)
2473 adj_p = local_lower;
2475 while (adj_p >= local_lower) {
2476 transformation test_t = o;
2477 int is_improved = 1;
2478 ale_accum test_v;
2479 ale_accum adj_s;
2481 while (is_improved) {
2482 is_improved = 0;
2484 for (int i = 0; i < 4; i++)
2485 for (int j = 0; j < 2; j++)
2486 for (adj_s = -adj_p; adj_s <= adj_p; adj_s += 2 * adj_p) {
2488 test_t = o;
2490 if (perturb_type == 0)
2491 test_t.gpt_modify(j, i, adj_s);
2492 else if (perturb_type == 1)
2493 test_t.gr_modify(j, i, adj_s);
2494 else
2495 assert(0);
2497 test_v = cp_rms_error(m, test_t);
2499 if (test_v < lowest_error) {
2500 lowest_error = test_v;
2501 o = test_t;
2502 adj_s += 3 * adj_p;
2503 is_improved = 1;
2507 adj_p /= 2;
2511 if (_exp_register)
2512 set_exposure_ratio(m, scale_clusters[0], o, local_ax_count, 0);
2514 for (int k = lod; k > 0; k--)
2515 o.rescale(0.5);
2517 here.diff(si, perturb, o, local_ax_count, m);
2518 here.confirm();
2519 ui::get()->set_match(here.get_error());
2520 ui::get()->set_offset(here.get_offset());
2524 * Announce perturbation size
2527 ui::get()->aligning(perturb, lod);
2530 * Run initial tests to get perturbation multipliers and error
2531 * centroids.
2534 std::vector<transformation> t_set;
2536 here.get_perturb_set(&t_set, adj_p, adj_o, adj_b, current_bd, modified_bd);
2539 * Perturbation adjustment loop.
2542 int stable_count = 0;
2544 while (perturb >= local_lower) {
2547 * Orientational adjustment value in degrees.
2549 * Since rotational perturbation is now specified as an
2550 * arclength, we have to convert.
2553 ale_pos adj_o = 2 * perturb
2554 / sqrt(pow(scale_clusters[0].input->height(), 2)
2555 + pow(scale_clusters[0].input->width(), 2))
2556 * 180
2557 / M_PI;
2560 * Barrel distortion adjustment value
2563 ale_pos adj_b = perturb * bda_mult;
2565 diff_stat_t old_here = here;
2567 here.perturb_test(perturb, adj_p, adj_o, adj_b, current_bd, modified_bd,
2568 stable_count);
2570 if (here.get_offset() == old_here.get_offset())
2571 stable_count++;
2572 else
2573 stable_count = 0;
2575 if (stable_count == 3) {
2577 stable_count = 0;
2579 here.calculate_element_region();
2581 if (here.get_current_index() + 1 < _ma_card) {
2582 here.push_element();
2583 here.make_element_nontrivial(adj_p, adj_o);
2584 element->is_primary = 0;
2585 } else {
2587 here.set_current_index(0);
2589 element->is_primary = 1;
2591 perturb *= 0.5;
2593 if (lod > 0) {
2596 * Work with images twice as large
2599 lod--;
2600 si = scale_clusters[lod];
2603 * Rescale the transforms.
2606 here.rescale(2, si);
2607 element->default_initial_alignment.rescale(2);
2609 } else {
2610 adj_p = perturb;
2614 * Announce changes
2617 ui::get()->alignment_perturbation_level(perturb, lod);
2622 ui::get()->set_match(here.get_error());
2623 ui::get()->set_offset(here.get_offset());
2626 here.set_current_index(0);
2628 offset = here.get_offset();
2630 if (lod > 0) {
2631 here.rescale(pow(2, lod), scale_clusters[0]);
2632 element->default_initial_alignment.rescale(pow(2, lod));
2636 * Post-alignment exposure adjustment
2639 if (_exp_register == 1) {
2640 ui::get()->exposure_2();
2641 set_exposure_ratio(m, scale_clusters[0], offset, local_ax_count, 1);
2645 * Recalculate error
2648 ui::get()->postmatching();
2649 offset.use_full_support();
2650 here.diff(scale_clusters[0], perturb, offset, local_ax_count, m);
2651 here.confirm();
2652 offset.use_restricted_support();
2653 ui::get()->set_match(here.get_error());
2656 * Free the level-of-detail structures
2659 final_clusters(scale_clusters, scale_factor, steps);
2662 * Ensure that the match meets the threshold.
2665 if (threshold_ok(here.get_error())) {
2667 * Update alignment variables
2669 latest_ok = 1;
2670 element->default_initial_alignment = offset;
2671 element->old_final_alignment = offset;
2672 ui::get()->alignment_match_ok();
2673 } else if (local_gs == 4) {
2676 * Align with outer starting points.
2680 * XXX: This probably isn't exactly the right thing to do,
2681 * since variables like old_initial_value have been overwritten.
2684 diff_stat_t nested_result = _align(m, -1, element);
2686 if (threshold_ok(nested_result.get_error())) {
2687 return nested_result;
2688 } else if (nested_result.get_error() < here.get_error()) {
2689 here = nested_result;
2692 if (is_fail_default)
2693 offset = element->default_initial_alignment;
2695 ui::get()->set_match(here.get_error());
2696 ui::get()->alignment_no_match();
2698 } else if (local_gs == -1) {
2700 latest_ok = 0;
2701 latest_t = offset;
2702 return here;
2704 } else {
2705 if (is_fail_default)
2706 offset = element->default_initial_alignment;
2707 latest_ok = 0;
2708 ui::get()->alignment_no_match();
2712 * Write the tonal registration multiplier as a comment.
2715 pixel trm = image_rw::exp(m).get_multiplier();
2716 tsave_trm(tsave, trm[0], trm[1], trm[2]);
2719 * Save the transformation information
2722 for (offset.set_current_index(0);
2723 offset.get_current_index() < _ma_card;
2724 offset.push_element()) {
2726 tsave_next(tsave, offset, alignment_class == 2,
2727 offset.get_current_index() == 0);
2730 offset.set_current_index(0);
2732 latest_t = offset;
2735 * Update match statistics.
2738 match_sum += (1 - here.get_error()) * 100;
2739 match_count++;
2740 latest = m;
2742 return here;
2745 #ifdef USE_FFTW
2747 * High-pass filter for frequency weights
2749 static void hipass(int rows, int cols, fftw_complex *inout) {
2750 for (int i = 0; i < rows * vert_freq_cut; i++)
2751 for (int j = 0; j < cols; j++)
2752 for (int k = 0; k < 2; k++)
2753 inout[i * cols + j][k] = 0;
2754 for (int i = 0; i < rows; i++)
2755 for (int j = 0; j < cols * horiz_freq_cut; j++)
2756 for (int k = 0; k < 2; k++)
2757 inout[i * cols + j][k] = 0;
2758 for (int i = 0; i < rows; i++)
2759 for (int j = 0; j < cols; j++)
2760 for (int k = 0; k < 2; k++)
2761 if (i / (double) rows + j / (double) cols < 2 * avg_freq_cut)
2762 inout[i * cols + j][k] = 0;
2764 #endif
2768 * Reset alignment weights
2770 static void reset_weights() {
2771 if (alignment_weights != NULL)
2772 delete alignment_weights;
2774 alignment_weights = NULL;
2778 * Initialize alignment weights
2780 static void init_weights() {
2781 if (alignment_weights != NULL)
2782 return;
2784 int rows = reference_image->height();
2785 int cols = reference_image->width();
2786 int colors = reference_image->depth();
2788 alignment_weights = new image_ale_real(rows, cols,
2789 colors, "alignment_weights");
2791 assert (alignment_weights);
2793 for (int i = 0; i < rows; i++)
2794 for (int j = 0; j < cols; j++)
2795 alignment_weights->set_pixel(i, j, pixel(1, 1, 1));
2799 * Update alignment weights with weight map
2801 static void map_update() {
2803 if (weight_map == NULL)
2804 return;
2806 init_weights();
2808 point map_offset = reference_image->offset() - weight_map->offset();
2810 int rows = reference_image->height();
2811 int cols = reference_image->width();
2813 for (int i = 0; i < rows; i++)
2814 for (int j = 0; j < cols; j++) {
2815 point map_weight_position = map_offset + point(i, j);
2816 if (map_weight_position[0] >= 0
2817 && map_weight_position[1] >= 0
2818 && map_weight_position[0] <= weight_map->height() - 1
2819 && map_weight_position[1] <= weight_map->width() - 1)
2820 alignment_weights->pix(i, j) *= weight_map->get_bl(map_weight_position);
2825 * Update alignment weights with algorithmic weights
2827 static void wmx_update() {
2828 #ifdef USE_UNIX
2830 static exposure *exp_def = new exposure_default();
2831 static exposure *exp_bool = new exposure_boolean();
2833 if (wmx_file == NULL || wmx_exec == NULL || wmx_defs == NULL)
2834 return;
2836 unsigned int rows = reference_image->height();
2837 unsigned int cols = reference_image->width();
2839 image_rw::write_image(wmx_file, reference_image);
2840 image_rw::write_image(wmx_defs, reference_defined, exp_bool);
2842 /* execute ... */
2843 int exit_status = 1;
2844 if (!fork()) {
2845 execlp(wmx_exec, wmx_exec, wmx_file, wmx_defs, NULL);
2846 ui::get()->exec_failure(wmx_exec, wmx_file, wmx_defs);
2849 wait(&exit_status);
2851 if (exit_status)
2852 ui::get()->fork_failure("d2::align");
2854 image *wmx_weights = image_rw::read_image(wmx_file, exp_def);
2856 if (wmx_weights->height() != rows || wmx_weights->width() != cols)
2857 ui::get()->error("algorithmic weighting must not change image size");
2859 if (alignment_weights == NULL)
2860 alignment_weights = wmx_weights;
2861 else
2862 for (unsigned int i = 0; i < rows; i++)
2863 for (unsigned int j = 0; j < cols; j++)
2864 alignment_weights->pix(i, j) *= wmx_weights->pix(i, j);
2865 #endif
2869 * Update alignment weights with frequency weights
2871 static void fw_update() {
2872 #ifdef USE_FFTW
2873 if (horiz_freq_cut == 0
2874 && vert_freq_cut == 0
2875 && avg_freq_cut == 0)
2876 return;
2879 * Required for correct operation of --fwshow
2882 assert (alignment_weights == NULL);
2884 int rows = reference_image->height();
2885 int cols = reference_image->width();
2886 int colors = reference_image->depth();
2888 alignment_weights = new image_ale_real(rows, cols,
2889 colors, "alignment_weights");
2891 fftw_complex *inout = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * rows * cols);
2893 assert (inout);
2895 fftw_plan pf = fftw_plan_dft_2d(rows, cols,
2896 inout, inout,
2897 FFTW_FORWARD, FFTW_ESTIMATE);
2899 fftw_plan pb = fftw_plan_dft_2d(rows, cols,
2900 inout, inout,
2901 FFTW_BACKWARD, FFTW_ESTIMATE);
2903 for (int k = 0; k < colors; k++) {
2904 for (int i = 0; i < rows * cols; i++) {
2905 inout[i][0] = reference_image->get_pixel(i / cols, i % cols)[k];
2906 inout[i][1] = 0;
2909 fftw_execute(pf);
2910 hipass(rows, cols, inout);
2911 fftw_execute(pb);
2913 for (int i = 0; i < rows * cols; i++) {
2914 #if 0
2915 alignment_weights->pix(i / cols, i % cols)[k] = fabs(inout[i][0] / (rows * cols));
2916 #else
2917 alignment_weights->pix(i / cols, i % cols)[k] =
2918 sqrt(pow(inout[i][0] / (rows * cols), 2)
2919 + pow(inout[i][1] / (rows * cols), 2));
2920 #endif
2924 fftw_destroy_plan(pf);
2925 fftw_destroy_plan(pb);
2926 fftw_free(inout);
2928 if (fw_output != NULL)
2929 image_rw::write_image(fw_output, alignment_weights);
2930 #endif
2934 * Update alignment to frame N.
2936 static void update_to(int n) {
2938 assert (n <= latest + 1);
2939 assert (n >= 0);
2941 static std::vector<element_t> elements;
2943 if (latest < 0) {
2945 elements.resize(1);
2948 * Handle the initial frame
2951 elements[0].input_frame = image_rw::open(n);
2953 const image *i = elements[0].input_frame;
2954 int is_default;
2955 transformation result = alignment_class == 2
2956 ? transformation::gpt_identity(i, scale_factor)
2957 : transformation::eu_identity(i, scale_factor);
2958 result = tload_first(tload, alignment_class == 2, result, &is_default);
2959 tsave_first(tsave, result, alignment_class == 2);
2961 if (_keep > 0) {
2962 kept_t = new transformation[image_rw::count()];
2963 kept_ok = (int *) malloc(image_rw::count()
2964 * sizeof(int));
2965 assert (kept_t);
2966 assert (kept_ok);
2968 if (!kept_t || !kept_ok)
2969 ui::get()->memory_error("alignment");
2971 kept_ok[0] = 1;
2972 kept_t[0] = result;
2975 latest = 0;
2976 latest_ok = 1;
2977 latest_t = result;
2979 elements[0].default_initial_alignment = result;
2980 orig_t = result;
2982 image_rw::close(n);
2985 for (int i = latest + 1; i <= n; i++) {
2986 int j = 0;
2989 * Handle supplemental frames.
2992 assert (reference != NULL);
2994 ui::get()->set_arender_current();
2995 reference->sync(i - 1);
2996 ui::get()->clear_arender_current();
2997 reference_image = reference->get_image();
2998 reference_defined = reference->get_defined();
3000 reset_weights();
3001 fw_update();
3002 wmx_update();
3003 map_update();
3005 assert (reference_image != NULL);
3006 assert (reference_defined != NULL);
3008 elements[j].input_frame = image_rw::open(i);
3009 elements[j].is_primary = 1;
3011 _align(i, _gs, &elements[j]);
3013 image_rw::close(n);
3016 if (elements.size() > _ma_card)
3017 elements.resize(_ma_card);
3020 public:
3023 * Set the control point count
3025 static void set_cp_count(unsigned int n) {
3026 assert (cp_array == NULL);
3028 cp_count = n;
3029 cp_array = (const point **) malloc(n * sizeof(const point *));
3033 * Set control points.
3035 static void set_cp(unsigned int i, const point *p) {
3036 cp_array[i] = p;
3040 * Register exposure
3042 static void exp_register() {
3043 _exp_register = 1;
3047 * Register exposure only based on metadata
3049 static void exp_meta_only() {
3050 _exp_register = 2;
3054 * Don't register exposure
3056 static void exp_noregister() {
3057 _exp_register = 0;
3061 * Set alignment class to translation only. Only adjust the x and y
3062 * position of images. Do not rotate input images or perform
3063 * projective transformations.
3065 static void class_translation() {
3066 alignment_class = 0;
3070 * Set alignment class to Euclidean transformations only. Adjust the x
3071 * and y position of images and the orientation of the image about the
3072 * image center.
3074 static void class_euclidean() {
3075 alignment_class = 1;
3079 * Set alignment class to perform general projective transformations.
3080 * See the file gpt.h for more information about general projective
3081 * transformations.
3083 static void class_projective() {
3084 alignment_class = 2;
3088 * Set the default initial alignment to the identity transformation.
3090 static void initial_default_identity() {
3091 default_initial_alignment_type = 0;
3095 * Set the default initial alignment to the most recently matched
3096 * frame's final transformation.
3098 static void initial_default_follow() {
3099 default_initial_alignment_type = 1;
3103 * Perturb output coordinates.
3105 static void perturb_output() {
3106 perturb_type = 0;
3110 * Perturb source coordinates.
3112 static void perturb_source() {
3113 perturb_type = 1;
3117 * Frames under threshold align optimally
3119 static void fail_optimal() {
3120 is_fail_default = 0;
3124 * Frames under threshold keep their default alignments.
3126 static void fail_default() {
3127 is_fail_default = 1;
3131 * Align images with an error contribution from each color channel.
3133 static void all() {
3134 channel_alignment_type = 0;
3138 * Align images with an error contribution only from the green channel.
3139 * Other color channels do not affect alignment.
3141 static void green() {
3142 channel_alignment_type = 1;
3146 * Align images using a summation of channels. May be useful when
3147 * dealing with images that have high frequency color ripples due to
3148 * color aliasing.
3150 static void sum() {
3151 channel_alignment_type = 2;
3155 * Error metric exponent
3158 static void set_metric_exponent(float me) {
3159 metric_exponent = me;
3163 * Match threshold
3166 static void set_match_threshold(float mt) {
3167 match_threshold = mt;
3171 * Perturbation lower and upper bounds.
3174 static void set_perturb_lower(ale_pos pl, int plp) {
3175 perturb_lower = pl;
3176 perturb_lower_percent = plp;
3179 static void set_perturb_upper(ale_pos pu, int pup) {
3180 perturb_upper = pu;
3181 perturb_upper_percent = pup;
3185 * Maximum rotational perturbation.
3188 static void set_rot_max(int rm) {
3191 * Obtain the largest power of two not larger than rm.
3194 rot_max = pow(2, floor(log(rm) / log(2)));
3198 * Barrel distortion adjustment multiplier
3201 static void set_bda_mult(ale_pos m) {
3202 bda_mult = m;
3206 * Barrel distortion maximum rate of change
3209 static void set_bda_rate(ale_pos m) {
3210 bda_rate = m;
3214 * Level-of-detail
3217 static void set_lod_max(int lm) {
3218 lod_max = lm;
3222 * Set the scale factor
3224 static void set_scale(ale_pos s) {
3225 scale_factor = s;
3229 * Set reference rendering to align against
3231 static void set_reference(render *r) {
3232 reference = r;
3236 * Set the interpolant
3238 static void set_interpolant(filter::scaled_filter *f) {
3239 interpolant = f;
3243 * Set alignment weights image
3245 static void set_weight_map(const image *i) {
3246 weight_map = i;
3250 * Set frequency cuts
3252 static void set_frequency_cut(double h, double v, double a) {
3253 horiz_freq_cut = h;
3254 vert_freq_cut = v;
3255 avg_freq_cut = a;
3259 * Set algorithmic alignment weighting
3261 static void set_wmx(const char *e, const char *f, const char *d) {
3262 wmx_exec = e;
3263 wmx_file = f;
3264 wmx_defs = d;
3268 * Show frequency weights
3270 static void set_fl_show(const char *filename) {
3271 fw_output = filename;
3275 * Set transformation file loader.
3277 static void set_tload(tload_t *tl) {
3278 tload = tl;
3282 * Set transformation file saver.
3284 static void set_tsave(tsave_t *ts) {
3285 tsave = ts;
3289 * Get match statistics for frame N.
3291 static int match(int n) {
3292 update_to(n);
3294 if (n == latest)
3295 return latest_ok;
3296 else if (_keep)
3297 return kept_ok[n];
3298 else {
3299 assert(0);
3300 exit(1);
3305 * Message that old alignment data should be kept.
3307 static void keep() {
3308 assert (latest == -1);
3309 _keep = 1;
3313 * Get alignment for frame N.
3315 static transformation of(int n) {
3316 update_to(n);
3317 if (n == latest)
3318 return latest_t;
3319 else if (_keep)
3320 return kept_t[n];
3321 else {
3322 assert(0);
3323 exit(1);
3328 * Set calculation precision
3330 static void set_precise(int p) {
3331 precise_calculation = p;
3335 * Set the certainty-weighted flag.
3337 static void certainty_weighted(int flag) {
3338 certainty_weights = flag;
3342 * Set the global search type.
3344 static void gs(const char *type) {
3345 if (!strcmp(type, "local")) {
3346 _gs = 0;
3347 } else if (!strcmp(type, "inner")) {
3348 _gs = 1;
3349 } else if (!strcmp(type, "outer")) {
3350 _gs = 2;
3351 } else if (!strcmp(type, "all")) {
3352 _gs = 3;
3353 } else if (!strcmp(type, "central")) {
3354 _gs = 4;
3355 } else if (!strcmp(type, "defaults")) {
3356 _gs = 6;
3357 } else if (!strcmp(type, "points")) {
3358 _gs = 5;
3359 keep();
3360 } else {
3361 ui::get()->error("bad global search type");
3366 * Multi-alignment contiguity
3368 static void ma_cont(double value) {
3369 _ma_cont = value;
3373 * Multi-alignment cardinality
3375 static void ma_card(unsigned int value) {
3376 assert (value >= 1);
3377 _ma_card = value;
3381 * Set the minimum overlap for global searching
3383 static void gs_mo(ale_pos value, int _gs_mo_percent) {
3384 _gs_mo = value;
3385 gs_mo_percent = _gs_mo_percent;
3389 * Set alignment exclusion regions
3391 static void set_exclusion(exclusion *_ax_parameters, int _ax_count) {
3392 ax_count = _ax_count;
3393 ax_parameters = _ax_parameters;
3397 * Get match summary statistics.
3399 static ale_accum match_summary() {
3400 return match_sum / match_count;
3404 #endif