Restore option --mc, replacing --{no-,}precise.
[Ale.git] / d2 / align.h
bloba5295d14ec90e01f326e4a87927f1cd7c2c09249
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 class align {
37 private:
40 * Private data members
43 static ale_pos scale_factor;
46 * Original frame transformation
48 static transformation orig_t;
51 * Keep data older than latest
53 static int _keep;
54 static transformation *kept_t;
55 static int *kept_ok;
58 * Transformation file handlers
61 static tload_t *tload;
62 static tsave_t *tsave;
65 * Control point variables
68 static const point **cp_array;
69 static unsigned int cp_count;
72 * Reference rendering to align against
75 static render *reference;
76 static filter::scaled_filter *interpolant;
77 static const image *reference_image;
78 static const image *reference_defined;
81 * Per-pixel alignment weight map
84 static const image *weight_map;
87 * Frequency-dependent alignment weights
90 static double horiz_freq_cut;
91 static double vert_freq_cut;
92 static double avg_freq_cut;
93 static const char *fw_output;
96 * Algorithmic alignment weighting
99 static const char *wmx_exec;
100 static const char *wmx_file;
101 static const char *wmx_defs;
104 * Non-certainty alignment weights
107 static image *alignment_weights;
110 * Latest transformation.
113 static transformation latest_t;
116 * Flag indicating whether the latest transformation
117 * resulted in a match.
120 static int latest_ok;
123 * Frame number most recently aligned.
126 static int latest;
129 * Exposure registration
131 * 0. Preserve the original exposure of images.
133 * 1. Match exposure between images.
135 * 2. Use only image metadata for registering exposure.
138 static int _exp_register;
141 * Alignment class.
143 * 0. Translation only. Only adjust the x and y position of images.
144 * Do not rotate input images or perform projective transformations.
146 * 1. Euclidean transformations only. Adjust the x and y position
147 * of images and the orientation of the image about the image center.
149 * 2. Perform general projective transformations. See the file gpt.h
150 * for more information about general projective transformations.
153 static int alignment_class;
156 * Default initial alignment type.
158 * 0. Identity transformation.
160 * 1. Most recently accepted frame's final transformation.
163 static int default_initial_alignment_type;
166 * Projective group behavior
168 * 0. Perturb in output coordinates.
170 * 1. Perturb in source coordinates
173 static int perturb_type;
176 * Alignment element
178 * This structure contains variables necessary for handling a
179 * multi-alignment element. The change between the non-default old
180 * initial alignment and old final alignment is used to adjust the
181 * non-default current initial alignment. If either the old or new
182 * initial alignment is a default alignment, the old --follow semantics
183 * are preserved.
186 struct element_t {
187 int is_default, old_is_default;
188 int is_primary;
189 int old_lod;
190 transformation old_initial_alignment;
191 transformation old_final_alignment;
192 transformation default_initial_alignment;
193 const image *input_frame;
195 public:
196 element_t() {
197 is_default = 1;
198 input_frame = NULL;
203 * Alignment for failed frames -- default or optimal?
205 * A frame that does not meet the match threshold can be assigned the
206 * best alignment found, or can be assigned its alignment default.
209 static int is_fail_default;
212 * Alignment code.
214 * 0. Align images with an error contribution from each color channel.
216 * 1. Align images with an error contribution only from the green channel.
217 * Other color channels do not affect alignment.
219 * 2. Align images using a summation of channels. May be useful when dealing
220 * with images that have high frequency color ripples due to color aliasing.
223 static int channel_alignment_type;
226 * Error metric exponent
229 static float metric_exponent;
232 * Match threshold
235 static float match_threshold;
238 * Perturbation lower and upper bounds.
241 static ale_pos perturb_lower;
242 static int perturb_lower_percent;
243 static ale_pos perturb_upper;
244 static int perturb_upper_percent;
247 * Maximum level-of-detail scale factor is 2^lod_max/perturb.
250 static int lod_max;
253 * Maximum rotational perturbation
256 static ale_pos rot_max;
259 * Barrel distortion alignment multiplier
262 static ale_pos bda_mult;
265 * Barrel distortion maximum adjustment rate
268 static ale_pos bda_rate;
271 * Alignment match sum
274 static ale_accum match_sum;
277 * Alignment match count.
280 static int match_count;
283 * Monte Carlo parameter
286 static ale_pos _mc;
289 * Certainty weight flag
291 * 0. Don't use certainty weights for alignment.
293 * 1. Use certainty weights for alignment.
296 static int certainty_weights;
299 * Global search parameter
301 * 0. Local: Local search only.
302 * 1. Inner: Alignment reference image inner region
303 * 2. Outer: Alignment reference image outer region
304 * 3. All: Alignment reference image inner and outer regions.
305 * 4. Central: Inner if possible; else, best of inner and outer.
306 * 5. Points: Align by control points.
309 static int _gs;
312 * Multi-alignment cardinality.
315 static unsigned int _ma_card;
318 * Multi-alignment contiguity.
321 static double _ma_cont;
324 * Minimum overlap for global searches
327 static ale_pos _gs_mo;
328 static int gs_mo_percent;
331 * Exclusion regions
334 static exclusion *ax_parameters;
335 static int ax_count;
338 * Types for scale clusters.
341 struct nl_scale_cluster {
342 const image *accum_max;
343 const image *accum_min;
344 const image *certainty_max;
345 const image *certainty_min;
346 const image *aweight_max;
347 const image *aweight_min;
348 exclusion *ax_parameters;
350 ale_pos input_scale;
351 const image *input_certainty_max;
352 const image *input_certainty_min;
353 const image *input_max;
354 const image *input_min;
357 struct scale_cluster {
358 const image *accum;
359 const image *certainty;
360 const image *aweight;
361 exclusion *ax_parameters;
363 ale_pos input_scale;
364 const image *input_certainty;
365 const image *input;
367 nl_scale_cluster *nl_scale_clusters;
371 * Check for exclusion region coverage in the reference
372 * array.
374 static int ref_excluded(int i, int j, point offset, exclusion *params, int param_count) {
375 for (int idx = 0; idx < param_count; idx++)
376 if (params[idx].type == exclusion::RENDER
377 && i + offset[0] >= params[idx].x[0]
378 && i + offset[0] <= params[idx].x[1]
379 && j + offset[1] >= params[idx].x[2]
380 && j + offset[1] <= params[idx].x[3])
381 return 1;
383 return 0;
387 * Check for exclusion region coverage in the input
388 * array.
390 static int input_excluded(ale_pos ti, ale_pos tj, exclusion *params, int param_count) {
391 for (int idx = 0; idx < param_count; idx++)
392 if (params[idx].type == exclusion::FRAME
393 && ti >= params[idx].x[0]
394 && ti <= params[idx].x[1]
395 && tj >= params[idx].x[2]
396 && tj <= params[idx].x[3])
397 return 1;
399 return 0;
403 * Overlap function. Determines the number of pixels in areas where
404 * the arrays overlap. Uses the reference array's notion of pixel
405 * positions.
407 static unsigned int overlap(struct scale_cluster c, transformation t, int ax_count) {
408 assert (reference_image);
410 unsigned int result = 0;
412 point offset = c.accum->offset();
414 for (unsigned int i = 0; i < c.accum->height(); i++)
415 for (unsigned int j = 0; j < c.accum->width(); j++) {
417 if (ref_excluded(i, j, offset, c.ax_parameters, ax_count))
418 continue;
421 * Transform
424 struct point q;
426 q = (c.input_scale < 1.0 && interpolant == NULL)
427 ? t.scaled_inverse_transform(
428 point(i + offset[0], j + offset[1]))
429 : t.unscaled_inverse_transform(
430 point(i + offset[0], j + offset[1]));
432 ale_pos ti = q[0];
433 ale_pos tj = q[1];
436 * Check that the transformed coordinates are within
437 * the boundaries of array c.input, and check that the
438 * weight value in the accumulated array is nonzero,
439 * unless we know it is nonzero by virtue of the fact
440 * that it falls within the region of the original
441 * frame (e.g. when we're not increasing image
442 * extents). Also check for frame exclusion.
445 if (input_excluded(ti, tj, c.ax_parameters, ax_count))
446 continue;
448 if (ti >= 0
449 && ti <= c.input->height() - 1
450 && tj >= 0
451 && tj <= c.input->width() - 1
452 && c.certainty->get_pixel(i, j)[0] != 0)
453 result++;
456 return result;
460 * Calculate the region associated with the current multi-alignment
461 * element.
463 static void calculate_element_region(transformation *t, scale_cluster si,
464 int local_ax_count) {
466 unsigned int i_max = si.accum->height();
467 unsigned int j_max = si.accum->width();
468 point offset = si.accum->offset();
470 if (si.input_scale < 1.0 && interpolant == NULL)
471 t->begin_calculate_scaled_region(i_max, j_max, offset);
472 else
473 t->begin_calculate_unscaled_region(i_max, j_max, offset);
475 for (unsigned int i = 0; i < i_max; i++)
476 for (unsigned int j = 0; j < j_max; j++) {
478 if (ref_excluded(i, j, offset, si.ax_parameters, local_ax_count))
479 continue;
481 point q;
483 while ((q = t->get_query_point((int) (i + offset[0]),
484 (int) (j + offset[1]))).defined()) {
486 ale_pos ti = q[0];
487 ale_pos tj = q[1];
489 if (input_excluded(ti, tj, si.ax_parameters, ax_count))
490 continue;
492 if (ti >= 0
493 && ti <= si.input->height() - 1
494 && tj >= 0
495 && tj <= si.input->width() - 1
496 && si.certainty->get_pixel(i, j)[0] != 0) {
498 assert(0);
503 t->end_calculate_region();
507 * Monte carlo iteration class.
509 * Monte Carlo alignment has been used for statistical comparisons in
510 * spatial registration, and is now used for tonal registration
511 * and final match calculation.
515 * We use a random process for which the expected number of sampled
516 * pixels is +/- .000003 from the coverage in the range [.005,.995] for
517 * an image with 100,000 pixels. (The actual number may still deviate
518 * from the expected number by more than this amount, however.) The
519 * method is as follows:
521 * We have coverage == USE/ALL, or (expected # pixels to use)/(# total
522 * pixels). We derive from this SKIP/USE.
524 * SKIP/USE == (SKIP/ALL)/(USE/ALL) == (1 - (USE/ALL))/(USE/ALL)
526 * Once we have SKIP/USE, we know the expected number of pixels to skip
527 * in each iteration. We use a random selection process that provides
528 * SKIP/USE close to this calculated value.
530 * If we can draw uniformly to select the number of pixels to skip, we
531 * do. In this case, the maximum number of pixels to skip is twice the
532 * expected number.
534 * If we cannot draw uniformly, we still assign equal probability to
535 * each of the integer values in the interval [0, 2 * (SKIP/USE)], but
536 * assign an unequal amount to the integer value ceil(2 * SKIP/USE) +
537 * 1.
541 * When reseeding the random number generator, we want the same set of
542 * pixels to be used in cases where two alignment options are compared.
543 * If we wanted to avoid bias from repeatedly utilizing the same seed,
544 * we could seed with the number of the frame most recently aligned:
546 * srand(latest);
548 * However, in cursory tests, it seems okay to just use the default
549 * seed of 1, and so we do this, since it is simpler; both of these
550 * approaches to reseeding achieve better results than not reseeding.
551 * (1 is the default seed according to the GNU Manual Page for
552 * rand(3).)
554 * For subdomain calculations, we vary the seed by adding the subdomain
555 * index.
558 class mc_iterate {
559 ale_pos mc_max;
560 unsigned int index;
561 unsigned int index_max;
562 int i_min;
563 int i_max;
564 int j_min;
565 int j_max;
567 rng_t rng;
569 public:
570 mc_iterate(int _i_min, int _i_max, int _j_min, int _j_max, unsigned int subdomain)
571 : rng() {
573 ale_pos coverage;
575 i_min = _i_min;
576 i_max = _i_max;
577 j_min = _j_min;
578 j_max = _j_max;
580 index_max = (i_max - i_min) * (j_max - j_min);
582 if (index_max < 500 || _mc > 100 || _mc <= 0)
583 coverage = 1;
584 else
585 coverage = _mc / 100;
587 ale_pos su = (1 - coverage) / coverage;
589 mc_max = (floor(2*su) * (1 + floor(2*su)) + 2*su)
590 / (2 + 2 * floor(2*su) - 2*su);
592 rng.seed(1 + subdomain);
594 index = -1 + (int) ceil((mc_max+1)
595 * ( (1 + ((ale_pos) (rng.get())) )
596 / (1 + ((ale_pos) RAND_MAX)) ));
599 int get_i() {
600 return index / (j_max - j_min) + i_min;
603 int get_j() {
604 return index % (j_max - j_min) + j_min;
607 void operator++(int whats_this_for) {
608 index += (int) ceil((mc_max+1)
609 * ( (1 + ((ale_pos) (rng.get())) )
610 / (1 + ((ale_pos) RAND_MAX)) ));
613 int done() {
614 return (index >= index_max);
619 * Not-quite-symmetric difference function. Determines the difference in areas
620 * where the arrays overlap. Uses the reference array's notion of pixel positions.
622 * For the purposes of determining the difference, this function divides each
623 * pixel value by the corresponding image's average pixel magnitude, unless we
624 * are:
626 * a) Extending the boundaries of the image, or
628 * b) following the previous frame's transform
630 * If we are doing monte-carlo pixel sampling for alignment, we
631 * typically sample a subset of available pixels; otherwise, we sample
632 * all pixels.
636 class diff_stat_t {
638 struct run {
640 transformation offset;
641 ale_pos perturb;
643 ale_accum result;
644 ale_accum divisor;
646 point max, min;
647 ale_accum centroid[2], centroid_divisor;
648 ale_accum de_centroid[2], de_centroid_v, de_sum;
650 void init() {
652 result = 0;
653 divisor = 0;
655 min = point::posinf();
656 max = point::neginf();
658 centroid[0] = 0;
659 centroid[1] = 0;
660 centroid_divisor = 0;
662 de_centroid[0] = 0;
663 de_centroid[1] = 0;
665 de_centroid_v = 0;
667 de_sum = 0;
670 void init(transformation _offset, ale_pos _perturb) {
671 offset = _offset;
672 perturb = _perturb;
673 init();
677 * Required for STL sanity.
679 run() : offset() {
680 init();
683 run(transformation _offset, ale_pos _perturb) : offset() {
684 init(_offset, _perturb);
687 void add(const run &_run) {
688 result += _run.result;
689 divisor += _run.divisor;
691 for (int d = 0; d < 2; d++) {
692 if (min[d] > _run.min[d])
693 min[d] = _run.min[d];
694 if (max[d] < _run.max[d])
695 max[d] = _run.max[d];
696 centroid[d] += _run.centroid[d];
697 de_centroid[d] += _run.de_centroid[d];
700 centroid_divisor += _run.centroid_divisor;
701 de_centroid_v += _run.de_centroid_v;
702 de_sum += _run.de_sum;
705 run(const run &_run) : offset() {
708 * Initialize
710 init(_run.offset, _run.perturb);
713 * Add
715 add(_run);
718 run &operator=(const run &_run) {
721 * Initialize
723 init(_run.offset, _run.perturb);
726 * Add
728 add(_run);
730 return *this;
733 ~run() {
736 ale_accum get_error() const {
737 return pow(result / divisor, 1/metric_exponent);
740 void sample(int f, scale_cluster c, int i, int j, point t, point u,
741 const run &comparison) {
743 pixel pa = c.accum->get_pixel(i, j);
745 ale_accum this_result[2] = { 0, 0 };
746 ale_accum this_divisor[2] = { 0, 0 };
748 pixel p[2];
749 pixel weight[2];
750 weight[0] = pixel(1, 1, 1);
751 weight[1] = pixel(1, 1, 1);
753 if (interpolant != NULL) {
754 interpolant->filtered(i, j, &p[0], &weight[1], 1, f);
755 } else {
756 p[0] = c.input->get_bl(t);
759 if (u.defined()) {
760 p[1] = c.input->get_bl(u);
765 * Handle certainty.
768 if (certainty_weights == 1) {
771 * For speed, use arithmetic interpolation (get_bl(.))
772 * instead of geometric (get_bl(., 1))
775 weight[0] *= c.input_certainty->get_bl(t);
776 if (u.defined())
777 weight[1] *= c.input_certainty->get_bl(u);
778 weight[0] *= c.certainty->get_pixel(i, j);
779 weight[1] *= c.certainty->get_pixel(i, j);
782 if (c.aweight != NULL) {
783 weight[0] *= c.aweight->get_pixel(i, j);
784 weight[1] *= c.aweight->get_pixel(i, j);
788 * Update sampling area statistics
791 if (min[0] > i)
792 min[0] = i;
793 if (min[1] > j)
794 min[1] = j;
795 if (max[0] < i)
796 max[0] = i;
797 if (max[1] < j)
798 max[1] = j;
800 centroid[0] += (weight[0][0] + weight[0][1] + weight[0][2]) * i;
801 centroid[1] += (weight[0][0] + weight[0][1] + weight[0][2]) * j;
802 centroid_divisor += (weight[0][0] + weight[0][1] + weight[0][2]);
805 * Determine alignment type.
808 for (int m = 0; m < (u.defined() ? 2 : 1); m++)
809 if (channel_alignment_type == 0) {
811 * Align based on all channels.
815 for (int k = 0; k < 3; k++) {
816 ale_real achan = pa[k];
817 ale_real bchan = p[m][k];
819 this_result[m] += weight[m][k] * pow(fabs(achan - bchan), metric_exponent);
820 this_divisor[m] += weight[m][k] * pow(achan > bchan ? achan : bchan, metric_exponent);
822 } else if (channel_alignment_type == 1) {
824 * Align based on the green channel.
827 ale_real achan = pa[1];
828 ale_real bchan = p[m][1];
830 this_result[m] = weight[m][1] * pow(fabs(achan - bchan), metric_exponent);
831 this_divisor[m] = weight[m][1] * pow(achan > bchan ? achan : bchan, metric_exponent);
832 } else if (channel_alignment_type == 2) {
834 * Align based on the sum of all channels.
837 ale_real asum = 0;
838 ale_real bsum = 0;
839 ale_real wsum = 0;
841 for (int k = 0; k < 3; k++) {
842 asum += pa[k];
843 bsum += p[m][k];
844 wsum += weight[m][k] / 3;
847 this_result[m] = wsum * pow(fabs(asum - bsum), metric_exponent);
848 this_divisor[m] = wsum * pow(asum > bsum ? asum : bsum, metric_exponent);
851 if (u.defined()) {
852 // ale_accum de = fabs(this_result[0] / this_divisor[0]
853 // - this_result[1] / this_divisor[1]);
854 ale_accum de = fabs(this_result[0] - this_result[1]);
856 de_centroid[0] += de * i;
857 de_centroid[1] += de * j;
859 de_centroid_v += de * t.lengthto(u);
861 de_sum += de;
864 result += (this_result[0]);
865 divisor += (this_divisor[0]);
868 void rescale(ale_pos scale) {
869 offset.rescale(scale);
871 de_centroid[0] *= scale;
872 de_centroid[1] *= scale;
873 de_centroid_v *= scale;
876 point get_centroid() {
877 point result = point(centroid[0] / centroid_divisor, centroid[1] / centroid_divisor);
879 assert (finite(centroid[0])
880 && finite(centroid[1])
881 && (result.defined() || centroid_divisor == 0));
883 return result;
886 point get_error_centroid() {
887 point result = point(de_centroid[0] / de_sum, de_centroid[1] / de_sum);
888 return result;
892 ale_pos get_error_perturb() {
893 ale_pos result = de_centroid_v / de_sum;
895 return result;
901 * When non-empty, runs.front() is best, runs.back() is
902 * testing.
905 std::vector<run> runs;
908 * old_runs stores the latest available perturbation set for
909 * each multi-alignment element.
912 typedef std::pair<unsigned int, unsigned int> run_index;
913 std::map<run_index, run> old_runs;
915 static void *diff_subdomain(void *args);
917 struct subdomain_args {
918 struct scale_cluster c;
919 std::vector<run> runs;
920 int ax_count;
921 int f;
922 int i_min, i_max, j_min, j_max;
923 int subdomain;
926 int get_current_index() const {
927 assert(runs.size());
928 return runs[0].offset.get_current_index();
931 struct scale_cluster si;
932 int ax_count;
933 int frame;
935 std::vector<ale_pos> perturb_multipliers;
937 public:
938 void diff(struct scale_cluster c, ale_pos perturb,
939 transformation t,
940 int _ax_count, int f) {
942 if (runs.size() == 2)
943 runs.pop_back();
945 runs.push_back(run(t, perturb));
947 si = c;
948 ax_count = _ax_count;
949 frame = f;
951 ui::get()->d2_align_sample_start();
953 if (interpolant != NULL)
954 interpolant->set_parameters(t, c.input, c.accum->offset());
956 int N;
957 #ifdef USE_PTHREAD
958 N = thread::count();
960 pthread_t *threads = (pthread_t *) malloc(sizeof(pthread_t) * N);
961 pthread_attr_t *thread_attr = (pthread_attr_t *) malloc(sizeof(pthread_attr_t) * N);
963 #else
964 N = 1;
965 #endif
967 subdomain_args *args = new subdomain_args[N];
969 for (int ti = 0; ti < N; ti++) {
970 args[ti].c = c;
971 args[ti].runs = runs;
972 args[ti].ax_count = ax_count;
973 args[ti].f = f;
974 args[ti].i_min = (c.accum->height() * ti) / N;
975 args[ti].i_max = (c.accum->height() * (ti + 1)) / N;
976 args[ti].j_min = 0;
977 args[ti].j_max = c.accum->width();
978 args[ti].subdomain = ti;
979 #ifdef USE_PTHREAD
980 pthread_attr_init(&thread_attr[ti]);
981 pthread_attr_setdetachstate(&thread_attr[ti], PTHREAD_CREATE_JOINABLE);
982 pthread_create(&threads[ti], &thread_attr[ti], diff_subdomain, &args[ti]);
983 #else
984 diff_subdomain(&args[ti]);
985 #endif
988 for (int ti = 0; ti < N; ti++) {
989 #ifdef USE_PTHREAD
990 pthread_join(threads[ti], NULL);
991 #endif
992 runs.back().add(args[ti].runs.back());
995 delete[] args;
997 ui::get()->d2_align_sample_stop();
1001 private:
1002 void rediff() {
1003 std::vector<transformation> t_array;
1004 std::vector<ale_pos> p_array;
1006 for (unsigned int r = 0; r < runs.size(); r++) {
1007 t_array.push_back(runs[r].offset);
1008 p_array.push_back(runs[r].perturb);
1011 runs.clear();
1013 for (unsigned int r = 0; r < t_array.size(); r++)
1014 diff(si, p_array[r], t_array[r], ax_count, frame);
1018 public:
1019 int better() {
1020 assert(runs.size() >= 2);
1021 assert(runs[0].offset.scale() == runs[1].offset.scale());
1023 return (runs[1].get_error() < runs[0].get_error()
1024 || (!finite(runs[0].get_error()) && finite(runs[1].get_error())));
1027 diff_stat_t() : runs(), old_runs(), perturb_multipliers() {
1030 run_index get_run_index(unsigned int perturb_index) {
1031 return run_index(get_current_index(), perturb_index);
1034 run &get_run(unsigned int perturb_index) {
1035 run_index index = get_run_index(perturb_index);
1037 assert(old_runs.count(index));
1038 return old_runs[index];
1041 void rescale(ale_pos scale, scale_cluster _si) {
1042 assert(runs.size() == 1);
1044 si = _si;
1046 runs[0].rescale(scale);
1048 rediff();
1051 void push_element() {
1052 assert(runs.size() == 1);
1054 runs[0].offset.push_element();
1056 rediff();
1059 unsigned int get_current_index() {
1060 assert (runs.size() > 0);
1062 return runs[0].offset.get_current_index();
1065 void set_current_index(unsigned int i) {
1066 assert(runs.size() == 1);
1067 runs[0].offset.set_current_index(i);
1068 rediff();
1071 void calculate_element_region() {
1072 assert(runs.size() == 1);
1074 if (get_offset().get_current_index() > 0
1075 && get_offset().is_nontrivial())
1076 align::calculate_element_region(&runs[0].offset, si, ax_count);
1079 ~diff_stat_t() {
1082 diff_stat_t &operator=(const diff_stat_t &dst) {
1084 * Copy run information.
1086 runs = dst.runs;
1087 old_runs = dst.old_runs;
1090 * Copy diff variables
1092 si = dst.si;
1093 ax_count = dst.ax_count;
1094 frame = dst.frame;
1095 perturb_multipliers = dst.perturb_multipliers;
1097 return *this;
1100 diff_stat_t(const diff_stat_t &dst) : runs(), old_runs(),
1101 perturb_multipliers() {
1102 operator=(dst);
1105 ale_accum get_result() {
1106 assert(runs.size() == 1);
1107 return runs[0].result;
1110 ale_accum get_divisor() {
1111 assert(runs.size() == 1);
1112 return runs[0].divisor;
1115 transformation get_offset() {
1116 assert(runs.size() == 1);
1117 return runs[0].offset;
1120 int operator!=(diff_stat_t &param) {
1121 return (get_error() != param.get_error());
1124 int operator==(diff_stat_t &param) {
1125 return !(operator!=(param));
1128 ale_pos get_error_perturb() {
1129 assert(runs.size() == 1);
1130 return runs[0].get_error_perturb();
1133 ale_accum get_error() const {
1134 assert(runs.size() == 1);
1135 return runs[0].get_error();
1138 public:
1140 * Get the set of transformations produced by a given perturbation
1142 void get_perturb_set(std::vector<transformation> *set,
1143 ale_pos adj_p, ale_pos adj_o, ale_pos adj_b,
1144 ale_pos *current_bd, ale_pos *modified_bd,
1145 std::vector<ale_pos> multipliers = std::vector<ale_pos>()) {
1147 assert(runs.size() == 1);
1149 transformation test_t;
1152 * Translational or euclidean transformation
1155 for (unsigned int i = 0; i < 2; i++)
1156 for (unsigned int s = 0; s < 2; s++) {
1158 if (!multipliers.size())
1159 multipliers.push_back(1);
1161 assert(finite(multipliers[0]));
1163 test_t = get_offset();
1165 // test_t.eu_modify(i, (s ? -adj_p : adj_p) * multipliers[0]);
1166 test_t.translate((i ? point(1, 0) : point(0, 1))
1167 * (s ? -adj_p : adj_p)
1168 * multipliers[0]);
1170 test_t.snap(adj_p / 2);
1172 set->push_back(test_t);
1173 multipliers.erase(multipliers.begin());
1177 if (alignment_class > 0)
1178 for (unsigned int s = 0; s < 2; s++) {
1180 if (!multipliers.size())
1181 multipliers.push_back(1);
1183 assert(multipliers.size());
1184 assert(finite(multipliers[0]));
1186 if (!(adj_o * multipliers[0] < rot_max))
1187 return;
1189 ale_pos adj_s = (s ? 1 : -1) * adj_o * multipliers[0];
1191 test_t = get_offset();
1193 run_index ori = get_run_index(set->size());
1194 point centroid = point::undefined();
1196 if (!old_runs.count(ori))
1197 ori = get_run_index(0);
1199 if (!centroid.finite() && old_runs.count(ori)) {
1200 centroid = old_runs[ori].get_error_centroid();
1202 if (!centroid.finite())
1203 centroid = old_runs[ori].get_centroid();
1205 centroid *= test_t.scale()
1206 / old_runs[ori].offset.scale();
1209 if (!centroid.finite() && !test_t.is_projective()) {
1210 test_t.eu_modify(2, adj_s);
1211 } else if (!centroid.finite()) {
1212 centroid = point(si.input->height() / 2,
1213 si.input->width() / 2);
1215 test_t.rotate(centroid + si.accum->offset(),
1216 adj_s);
1217 } else {
1218 test_t.rotate(centroid + si.accum->offset(),
1219 adj_s);
1222 test_t.snap(adj_p / 2);
1224 set->push_back(test_t);
1225 multipliers.erase(multipliers.begin());
1228 if (alignment_class == 2) {
1231 * Projective transformation
1234 for (unsigned int i = 0; i < 4; i++)
1235 for (unsigned int j = 0; j < 2; j++)
1236 for (unsigned int s = 0; s < 2; s++) {
1238 if (!multipliers.size())
1239 multipliers.push_back(1);
1241 assert(multipliers.size());
1242 assert(finite(multipliers[0]));
1244 ale_pos adj_s = (s ? -1 : 1) * adj_p * multipliers [0];
1246 test_t = get_offset();
1248 if (perturb_type == 0)
1249 test_t.gpt_modify(j, i, adj_s);
1250 else if (perturb_type == 1)
1251 test_t.gr_modify(j, i, adj_s);
1252 else
1253 assert(0);
1255 test_t.snap(adj_p / 2);
1257 set->push_back(test_t);
1258 multipliers.erase(multipliers.begin());
1264 * Barrel distortion
1267 if (bda_mult != 0 && adj_b != 0) {
1269 for (unsigned int d = 0; d < get_offset().bd_count(); d++)
1270 for (unsigned int s = 0; s < 2; s++) {
1272 if (!multipliers.size())
1273 multipliers.push_back(1);
1275 assert (multipliers.size());
1276 assert (finite(multipliers[0]));
1278 ale_pos adj_s = (s ? -1 : 1) * adj_b * multipliers[0];
1280 if (bda_rate > 0 && fabs(modified_bd[d] + adj_s - current_bd[d]) > bda_rate)
1281 continue;
1283 transformation test_t = get_offset();
1285 test_t.bd_modify(d, adj_s);
1287 set->push_back(test_t);
1292 void confirm() {
1293 assert(runs.size() == 2);
1294 runs[0] = runs[1];
1295 runs.pop_back();
1298 void discard() {
1299 assert(runs.size() == 2);
1300 runs.pop_back();
1303 void perturb_test(ale_pos perturb, ale_pos adj_p, ale_pos adj_o, ale_pos adj_b,
1304 ale_pos *current_bd, ale_pos *modified_bd, int stable) {
1306 assert(runs.size() == 1);
1308 std::vector<transformation> t_set;
1310 if (perturb_multipliers.size() == 0) {
1311 get_perturb_set(&t_set, adj_p, adj_o, adj_b,
1312 current_bd, modified_bd);
1314 for (unsigned int i = 0; i < t_set.size(); i++) {
1315 diff_stat_t test = *this;
1317 test.diff(si, perturb, t_set[i], ax_count, frame);
1319 test.confirm();
1321 if (finite(adj_p / test.get_error_perturb()))
1322 perturb_multipliers.push_back(adj_p / test.get_error_perturb());
1323 else
1324 perturb_multipliers.push_back(1);
1328 t_set.clear();
1331 get_perturb_set(&t_set, adj_p, adj_o, adj_b, current_bd, modified_bd,
1332 perturb_multipliers);
1334 int found_unreliable = 1;
1335 std::vector<int> tested(t_set.size(), 0);
1337 for (unsigned int i = 0; i < t_set.size(); i++) {
1338 run_index ori = get_run_index(i);
1341 * Check for stability
1343 if (stable
1344 && old_runs.count(ori)
1345 && old_runs[ori].offset == t_set[i])
1346 tested[i] = 1;
1349 std::vector<ale_pos> perturb_multipliers_original = perturb_multipliers;
1351 while (found_unreliable) {
1353 found_unreliable = 0;
1355 for (unsigned int i = 0; i < t_set.size(); i++) {
1357 if (tested[i])
1358 continue;
1360 diff(si, perturb, t_set[i], ax_count, frame);
1362 if (!(i < perturb_multipliers.size())
1363 || !finite(perturb_multipliers[i])) {
1365 perturb_multipliers.resize(i + 1);
1367 perturb_multipliers[i] =
1368 adj_p / runs[1].get_error_perturb();
1370 if (finite(perturb_multipliers[i]))
1371 found_unreliable = 1;
1373 continue;
1376 run_index ori = get_run_index(i);
1378 if (old_runs.count(ori) == 0)
1379 old_runs.insert(std::pair<run_index, run>(ori, runs[1]));
1380 else
1381 old_runs[ori] = runs[1];
1383 perturb_multipliers[i] = perturb_multipliers_original[i]
1384 * adj_p / runs[1].get_error_perturb();
1386 if (!finite(perturb_multipliers[i]))
1387 perturb_multipliers[i] = 1;
1389 tested[i] = 1;
1391 if (better()
1392 && runs[1].get_error() < runs[0].get_error()
1393 && perturb_multipliers[i]
1394 / perturb_multipliers_original[i] < 2) {
1395 runs[0] = runs[1];
1396 runs.pop_back();
1397 return;
1402 if (runs.size() > 1)
1403 runs.pop_back();
1405 if (!found_unreliable)
1406 return;
1411 * Attempt to make the current element non-trivial, by finding a nearby
1412 * alignment admitting a non-empty element region.
1414 void make_element_nontrivial(ale_pos adj_p, ale_pos adj_o) {
1415 assert(runs.size() == 1);
1417 transformation *t = &runs[0].offset;
1419 if (t->is_nontrivial())
1420 return;
1422 calculate_element_region();
1424 if (t->is_nontrivial())
1425 return;
1427 std::vector<transformation> t_set;
1428 get_perturb_set(&t_set, adj_p, adj_o, 0, NULL, NULL);
1430 for (unsigned int i = 0; i < t_set.size(); i++) {
1432 align::calculate_element_region(&t_set[i], si, ax_count);
1434 if (t_set[i].is_nontrivial()) {
1435 *t = t_set[i];
1436 return;
1445 * Adjust exposure for an aligned frame B against reference A.
1447 * Expects full-LOD images.
1449 * Note: This method does not use any weighting, by certainty or
1450 * otherwise, in the first exposure registration pass, as any bias of
1451 * weighting according to color may also bias the exposure registration
1452 * result; it does use weighting, including weighting by certainty
1453 * (even if certainty weighting is not specified), in the second pass,
1454 * under the assumption that weighting by certainty improves handling
1455 * of out-of-range highlights, and that bias of exposure measurements
1456 * according to color may generally be less harmful after spatial
1457 * registration has been performed.
1459 class exposure_ratio_iterate : public thread::decompose_domain {
1460 pixel_accum *asums;
1461 pixel_accum *bsums;
1462 pixel_accum *asum;
1463 pixel_accum *bsum;
1464 struct scale_cluster c;
1465 transformation t;
1466 int ax_count;
1467 int pass_number;
1468 protected:
1469 void prepare_subdomains(unsigned int N) {
1470 asums = new pixel_accum[N];
1471 bsums = new pixel_accum[N];
1473 void subdomain_algorithm(unsigned int thread,
1474 int i_min, int i_max, int j_min, int j_max) {
1476 point offset = c.accum->offset();
1478 for (mc_iterate m(i_min, i_max, j_min, j_max, thread); !m.done(); m++) {
1480 unsigned int i = (unsigned int) m.get_i();
1481 unsigned int j = (unsigned int) m.get_j();
1483 if (ref_excluded(i, j, offset, c.ax_parameters, ax_count))
1484 continue;
1487 * Transform
1490 struct point q;
1492 q = (c.input_scale < 1.0 && interpolant == NULL)
1493 ? t.scaled_inverse_transform(
1494 point(i + offset[0], j + offset[1]))
1495 : t.unscaled_inverse_transform(
1496 point(i + offset[0], j + offset[1]));
1499 * Check that the transformed coordinates are within
1500 * the boundaries of array c.input, that they are not
1501 * subject to exclusion, and that the weight value in
1502 * the accumulated array is nonzero.
1505 if (input_excluded(q[0], q[1], c.ax_parameters, ax_count))
1506 continue;
1508 if (q[0] >= 0
1509 && q[0] <= c.input->height() - 1
1510 && q[1] >= 0
1511 && q[1] <= c.input->width() - 1
1512 && c.certainty->get_pixel(i, j).minabs_norm() != 0) {
1513 pixel a = c.accum->get_pixel(i, j);
1514 pixel b;
1516 b = c.input->get_bl(q);
1518 pixel weight = ((c.aweight && pass_number)
1519 ? c.aweight->get_pixel(i, j)
1520 : pixel(1, 1, 1))
1521 * (pass_number
1522 ? ppow(c.certainty->get_pixel(i, j)
1523 * c.input_certainty->get_bl(q, 1), 0.5)
1524 : pixel(1, 1, 1));
1526 asums[thread] += a * weight;
1527 bsums[thread] += b * weight;
1532 void finish_subdomains(unsigned int N) {
1533 for (unsigned int n = 0; n < N; n++) {
1534 *asum += asums[n];
1535 *bsum += bsums[n];
1537 delete asums;
1538 delete bsums;
1540 public:
1541 exposure_ratio_iterate(pixel_accum *_asum,
1542 pixel_accum *_bsum,
1543 struct scale_cluster _c,
1544 transformation _t,
1545 int _ax_count,
1546 int _pass_number) : decompose_domain(0, _c.accum->height(),
1547 0, _c.accum->width()){
1549 asum = _asum;
1550 bsum = _bsum;
1551 c = _c;
1552 t = _t;
1553 ax_count = _ax_count;
1554 pass_number = _pass_number;
1558 static void set_exposure_ratio(unsigned int m, struct scale_cluster c,
1559 transformation t, int ax_count, int pass_number) {
1561 if (_exp_register == 2) {
1563 * Use metadata only.
1565 ale_real gain_multiplier = image_rw::exp(m).get_gain_multiplier();
1566 pixel multiplier = pixel(gain_multiplier, gain_multiplier, gain_multiplier);
1568 image_rw::exp(m).set_multiplier(multiplier);
1569 ui::get()->exp_multiplier(multiplier[0],
1570 multiplier[1],
1571 multiplier[2]);
1573 return;
1576 pixel_accum asum(0, 0, 0), bsum(0, 0, 0);
1578 exposure_ratio_iterate eri(&asum, &bsum, c, t, ax_count, pass_number);
1579 eri.run();
1581 // std::cerr << (asum / bsum) << " ";
1583 pixel_accum new_multiplier;
1585 new_multiplier = asum / bsum * image_rw::exp(m).get_multiplier();
1587 if (finite(new_multiplier[0])
1588 && finite(new_multiplier[1])
1589 && finite(new_multiplier[2])) {
1590 image_rw::exp(m).set_multiplier(new_multiplier);
1591 ui::get()->exp_multiplier(new_multiplier[0],
1592 new_multiplier[1],
1593 new_multiplier[2]);
1598 * Copy all ax parameters.
1600 static exclusion *copy_ax_parameters(int local_ax_count, exclusion *source) {
1602 exclusion *dest = (exclusion *) malloc(local_ax_count * sizeof(exclusion));
1604 assert (dest);
1606 if (!dest)
1607 ui::get()->memory_error("exclusion regions");
1609 for (int idx = 0; idx < local_ax_count; idx++)
1610 dest[idx] = source[idx];
1612 return dest;
1616 * Copy ax parameters according to frame.
1618 static exclusion *filter_ax_parameters(int frame, int *local_ax_count) {
1620 exclusion *dest = (exclusion *) malloc(ax_count * sizeof(exclusion));
1622 assert (dest);
1624 if (!dest)
1625 ui::get()->memory_error("exclusion regions");
1627 *local_ax_count = 0;
1629 for (int idx = 0; idx < ax_count; idx++) {
1630 if (ax_parameters[idx].x[4] > frame
1631 || ax_parameters[idx].x[5] < frame)
1632 continue;
1634 dest[*local_ax_count] = ax_parameters[idx];
1636 (*local_ax_count)++;
1639 return dest;
1642 static void scale_ax_parameters(int local_ax_count, exclusion *ax_parameters,
1643 ale_pos ref_scale, ale_pos input_scale) {
1644 for (int i = 0; i < local_ax_count; i++) {
1645 ale_pos scale = (ax_parameters[i].type == exclusion::RENDER)
1646 ? ref_scale
1647 : input_scale;
1649 for (int n = 0; n < 6; n++) {
1650 ax_parameters[i].x[n] = ax_parameters[i].x[n] * scale;
1656 * Prepare the next level of detail for ordinary images.
1658 static const image *prepare_lod(const image *current) {
1659 if (current == NULL)
1660 return NULL;
1662 return current->scale_by_half("prepare_lod");
1666 * Prepare the next level of detail for definition maps.
1668 static const image *prepare_lod_def(const image *current) {
1669 if (current == NULL)
1670 return NULL;
1672 return current->defined_scale_by_half("prepare_lod_def");
1676 * Initialize scale cluster data structures.
1679 static void init_nl_cluster(struct scale_cluster *sc) {
1682 static struct scale_cluster *init_clusters(int frame, ale_real scale_factor,
1683 const image *input_frame, unsigned int steps,
1684 int *local_ax_count) {
1687 * Allocate memory for the array.
1690 struct scale_cluster *scale_clusters =
1691 (struct scale_cluster *) malloc(steps * sizeof(struct scale_cluster));
1693 assert (scale_clusters);
1695 if (!scale_clusters)
1696 ui::get()->memory_error("alignment");
1699 * Prepare images and exclusion regions for the highest level
1700 * of detail.
1703 scale_clusters[0].accum = reference_image;
1705 ui::get()->constructing_lod_clusters(0.0);
1706 scale_clusters[0].input_scale = scale_factor;
1707 if (scale_factor < 1.0 && interpolant == NULL)
1708 scale_clusters[0].input = input_frame->scale(scale_factor, "alignment");
1709 else
1710 scale_clusters[0].input = input_frame;
1712 scale_clusters[0].certainty = reference_defined->clone("certainty");
1713 scale_clusters[0].aweight = alignment_weights;
1714 scale_clusters[0].ax_parameters = filter_ax_parameters(frame, local_ax_count);
1717 * Allocate and determine input frame certainty.
1720 if (scale_clusters[0].input->get_bayer() != IMAGE_BAYER_NONE) {
1721 scale_clusters[0].input_certainty = new image_bayer_ale_real(
1722 scale_clusters[0].input->height(),
1723 scale_clusters[0].input->width(),
1724 scale_clusters[0].input->depth(),
1725 scale_clusters[0].input->get_bayer());
1726 } else {
1727 scale_clusters[0].input_certainty = scale_clusters[0].input->clone("certainty");
1730 for (unsigned int i = 0; i < scale_clusters[0].input_certainty->height(); i++)
1731 for (unsigned int j = 0; j < scale_clusters[0].input_certainty->width(); j++)
1732 for (unsigned int k = 0; k < 3; k++)
1733 if (scale_clusters[0].input->get_channels(i, j) & (1 << k))
1734 ((image *) scale_clusters[0].input_certainty)->chan(i, j, k) =
1735 scale_clusters[0].input->
1736 exp().confidence(scale_clusters[0].input->get_pixel(i, j))[k];
1738 scale_ax_parameters(*local_ax_count, scale_clusters[0].ax_parameters, scale_factor,
1739 (scale_factor < 1.0 && interpolant == NULL) ? scale_factor : 1);
1741 init_nl_cluster(&(scale_clusters[0]));
1744 * Prepare reduced-detail images and exclusion
1745 * regions.
1748 for (unsigned int step = 1; step < steps; step++) {
1749 ui::get()->constructing_lod_clusters(step);
1750 scale_clusters[step].accum = prepare_lod(scale_clusters[step - 1].accum);
1751 scale_clusters[step].certainty = prepare_lod_def(scale_clusters[step - 1].certainty);
1752 scale_clusters[step].aweight = prepare_lod_def(scale_clusters[step - 1].aweight);
1753 scale_clusters[step].ax_parameters
1754 = copy_ax_parameters(*local_ax_count, scale_clusters[step - 1].ax_parameters);
1756 double sf = scale_clusters[step - 1].input_scale / 2;
1757 scale_clusters[step].input_scale = sf;
1759 if (sf >= 1.0 || interpolant != NULL) {
1760 scale_clusters[step].input = scale_clusters[step - 1].input;
1761 scale_clusters[step].input_certainty = scale_clusters[step - 1].input_certainty;
1762 scale_ax_parameters(*local_ax_count, scale_clusters[step].ax_parameters, 0.5, 1);
1763 } else if (sf > 0.5) {
1764 scale_clusters[step].input = scale_clusters[step - 1].input->scale(sf, "alignment");
1765 scale_clusters[step].input_certainty = scale_clusters[step - 1].input->scale(sf, "alignment", 1);
1766 scale_ax_parameters(*local_ax_count, scale_clusters[step].ax_parameters, 0.5, sf);
1767 } else {
1768 scale_clusters[step].input = scale_clusters[step - 1].input->scale(0.5, "alignment");
1769 scale_clusters[step].input_certainty = scale_clusters[step - 1].input_certainty->scale(0.5, "alignment", 1);
1770 scale_ax_parameters(*local_ax_count, scale_clusters[step].ax_parameters, 0.5, 0.5);
1773 init_nl_cluster(&(scale_clusters[step]));
1776 return scale_clusters;
1780 * Destroy the first element in the scale cluster data structure.
1782 static void final_clusters(struct scale_cluster *scale_clusters, ale_real scale_factor,
1783 unsigned int steps) {
1785 if (scale_clusters[0].input_scale < 1.0)
1786 delete scale_clusters[0].input;
1788 free((void *)scale_clusters[0].ax_parameters);
1790 delete scale_clusters[0].certainty;
1792 for (unsigned int step = 1; step < steps; step++) {
1793 delete scale_clusters[step].accum;
1794 delete scale_clusters[step].certainty;
1795 delete scale_clusters[step].aweight;
1797 if (scale_clusters[step].input_scale < 1.0)
1798 delete scale_clusters[step].input;
1800 free((void *)scale_clusters[step].ax_parameters);
1803 free(scale_clusters);
1807 * Calculate the centroid of a control point for the set of frames
1808 * having index lower than m. Divide by any scaling of the output.
1810 static point unscaled_centroid(unsigned int m, unsigned int p) {
1811 assert(_keep);
1813 point point_sum(0, 0);
1814 ale_accum divisor = 0;
1816 for(unsigned int j = 0; j < m; j++) {
1817 point pp = cp_array[p][j];
1819 if (pp.defined()) {
1820 point_sum += kept_t[j].transform_unscaled(pp)
1821 / kept_t[j].scale();
1822 divisor += 1;
1826 if (divisor == 0)
1827 return point::undefined();
1829 return point_sum / divisor;
1833 * Calculate centroid of this frame, and of all previous frames,
1834 * from points common to both sets.
1836 static void centroids(unsigned int m, point *current, point *previous) {
1838 * Calculate the translation
1840 point other_centroid(0, 0);
1841 point this_centroid(0, 0);
1842 ale_pos divisor = 0;
1844 for (unsigned int i = 0; i < cp_count; i++) {
1845 point other_c = unscaled_centroid(m, i);
1846 point this_c = cp_array[i][m];
1848 if (!other_c.defined() || !this_c.defined())
1849 continue;
1851 other_centroid += other_c;
1852 this_centroid += this_c;
1853 divisor += 1;
1857 if (divisor == 0) {
1858 *current = point::undefined();
1859 *previous = point::undefined();
1860 return;
1863 *current = this_centroid / divisor;
1864 *previous = other_centroid / divisor;
1868 * Calculate the RMS error of control points for frame m, with
1869 * transformation t, against control points for earlier frames.
1871 static ale_accum cp_rms_error(unsigned int m, transformation t) {
1872 assert (_keep);
1874 ale_accum err = 0;
1875 ale_accum divisor = 0;
1877 for (unsigned int i = 0; i < cp_count; i++)
1878 for (unsigned int j = 0; j < m; j++) {
1879 const point *p = cp_array[i];
1880 point p_ref = kept_t[j].transform_unscaled(p[j]);
1881 point p_cur = t.transform_unscaled(p[m]);
1883 if (!p_ref.defined() || !p_cur.defined())
1884 continue;
1886 err += p_ref.lengthtosq(p_cur);
1887 divisor += 1;
1890 return sqrt(err / divisor);
1894 * Implement new delta --follow semantics.
1896 * If we have a transformation T such that
1898 * prev_final == T(prev_init)
1900 * Then we also have
1902 * current_init_follow == T(current_init)
1904 * We can calculate T as follows:
1906 * T == prev_final(prev_init^-1)
1908 * Where ^-1 is the inverse operator.
1910 static transformation follow(element_t *element, transformation offset, int lod) {
1912 transformation new_offset = offset;
1915 * Criteria for using following.
1918 if (!element->old_is_default && !element->is_default &&
1919 default_initial_alignment_type == 1) {
1921 * Ensure that the lod for the old initial and final
1922 * alignments are equal to the lod for the new initial
1923 * alignment.
1926 ui::get()->following();
1928 element->old_final_alignment.rescale (1 / pow(2, lod));
1929 element->old_initial_alignment.rescale(1 / pow(2, lod - element->old_lod));
1931 for (offset.set_current_index(0),
1932 element->old_initial_alignment.set_current_index(0),
1933 element->old_final_alignment.set_current_index(0),
1934 new_offset.set_current_index(0);
1936 offset.get_current_index() < _ma_card;
1938 offset.push_element(),
1939 new_offset.push_element()) {
1941 if (alignment_class == 0) {
1943 * Translational transformations
1946 ale_pos t0 = -element->old_initial_alignment.eu_get(0)
1947 + element->old_final_alignment.eu_get(0);
1948 ale_pos t1 = -element->old_initial_alignment.eu_get(1)
1949 + element->old_final_alignment.eu_get(1);
1951 new_offset.eu_modify(0, t0);
1952 new_offset.eu_modify(1, t1);
1954 } else if (alignment_class == 1) {
1956 * Euclidean transformations
1959 ale_pos t2 = -element->old_initial_alignment.eu_get(2)
1960 + element->old_final_alignment.eu_get(2);
1962 new_offset.eu_modify(2, t2);
1964 point p( offset.scaled_height()/2 + offset.eu_get(0) - element->old_initial_alignment.eu_get(0),
1965 offset.scaled_width()/2 + offset.eu_get(1) - element->old_initial_alignment.eu_get(1) );
1967 p = element->old_final_alignment.transform_scaled(p);
1969 new_offset.eu_modify(0, p[0] - offset.scaled_height()/2 - offset.eu_get(0));
1970 new_offset.eu_modify(1, p[1] - offset.scaled_width()/2 - offset.eu_get(1));
1972 } else if (alignment_class == 2) {
1974 * Projective transformations
1977 point p[4];
1979 p[0] = element->old_final_alignment.transform_scaled(element->old_initial_alignment
1980 . scaled_inverse_transform(offset.get_current_element().transform_scaled(point( 0 , 0 ))));
1981 p[1] = element->old_final_alignment.transform_scaled(element->old_initial_alignment
1982 . scaled_inverse_transform(offset.get_current_element().transform_scaled(point(offset.scaled_height(), 0 ))));
1983 p[2] = element->old_final_alignment.transform_scaled(element->old_initial_alignment
1984 . scaled_inverse_transform(offset.get_current_element().transform_scaled(point(offset.scaled_height(), offset.scaled_width()))));
1985 p[3] = element->old_final_alignment.transform_scaled(element->old_initial_alignment
1986 . scaled_inverse_transform(offset.get_current_element().transform_scaled(point( 0 , offset.scaled_width()))));
1988 new_offset.gpt_set(p);
1992 ui::get()->set_offset(offset);
1995 return new_offset;
1998 static void test_global(diff_stat_t *here, scale_cluster si, transformation t,
1999 int local_ax_count, int m, ale_pos local_gs_mo, ale_pos perturb) {
2001 diff_stat_t test(*here);
2003 test.diff(si, perturb, t, local_ax_count, m);
2005 unsigned int ovl = overlap(si, t, local_ax_count);
2007 if (ovl >= local_gs_mo && test.better()) {
2008 test.confirm();
2009 *here = test;
2010 ui::get()->set_match(here->get_error());
2011 ui::get()->set_offset(here->get_offset());
2012 } else {
2013 test.discard();
2019 * Get the set of global transformations for a given density
2021 static void test_globals(diff_stat_t *here,
2022 scale_cluster si, transformation t, int local_gs, ale_pos adj_p,
2023 int local_ax_count, int m, ale_pos local_gs_mo, ale_pos perturb) {
2025 transformation offset = t;
2027 point min, max;
2029 transformation offset_p = offset;
2031 if (!offset_p.is_projective())
2032 offset_p.eu_to_gpt();
2034 min = max = offset_p.gpt_get(0);
2035 for (int p_index = 1; p_index < 4; p_index++) {
2036 point p = offset_p.gpt_get(p_index);
2037 if (p[0] < min[0])
2038 min[0] = p[0];
2039 if (p[1] < min[1])
2040 min[1] = p[1];
2041 if (p[0] > max[0])
2042 max[0] = p[0];
2043 if (p[1] > max[1])
2044 max[1] = p[1];
2047 point inner_min_t = -min;
2048 point inner_max_t = -max + point(si.accum->height(), si.accum->width());
2049 point outer_min_t = -max + point(adj_p - 1, adj_p - 1);
2050 point outer_max_t = point(si.accum->height(), si.accum->width()) - point(adj_p, adj_p);
2052 if (local_gs == 1 || local_gs == 3 || local_gs == 4 || local_gs == 6) {
2055 * Inner
2058 for (ale_pos i = inner_min_t[0]; i <= inner_max_t[0]; i += adj_p)
2059 for (ale_pos j = inner_min_t[1]; j <= inner_max_t[1]; j += adj_p) {
2060 transformation test_t = offset;
2061 test_t.translate(point(i, j));
2062 test_global(here, si, test_t, local_ax_count, m, local_gs_mo, perturb);
2066 if (local_gs == 2 || local_gs == 3 || local_gs == -1 || local_gs == 6) {
2069 * Outer
2072 for (ale_pos i = outer_min_t[0]; i <= outer_max_t[0]; i += adj_p)
2073 for (ale_pos j = outer_min_t[1]; j < inner_min_t[1]; j += adj_p) {
2074 transformation test_t = offset;
2075 test_t.translate(point(i, j));
2076 test_global(here, si, test_t, local_ax_count, m, local_gs_mo, perturb);
2078 for (ale_pos i = outer_min_t[0]; i <= outer_max_t[0]; i += adj_p)
2079 for (ale_pos j = outer_max_t[1]; j > inner_max_t[1]; j -= adj_p) {
2080 transformation test_t = offset;
2081 test_t.translate(point(i, j));
2082 test_global(here, si, test_t, local_ax_count, m, local_gs_mo, perturb);
2084 for (ale_pos i = outer_min_t[0]; i < inner_min_t[0]; i += adj_p)
2085 for (ale_pos j = outer_min_t[1]; j <= outer_max_t[1]; j += adj_p) {
2086 transformation test_t = offset;
2087 test_t.translate(point(i, j));
2088 test_global(here, si, test_t, local_ax_count, m, local_gs_mo, perturb);
2090 for (ale_pos i = outer_max_t[0]; i > inner_max_t[0]; i -= adj_p)
2091 for (ale_pos j = outer_min_t[1]; j <= outer_max_t[1]; j += adj_p) {
2092 transformation test_t = offset;
2093 test_t.translate(point(i, j));
2094 test_global(here, si, test_t, local_ax_count, m, local_gs_mo, perturb);
2099 static void get_translational_set(std::vector<transformation> *set,
2100 transformation t, ale_pos adj_p) {
2102 ale_pos adj_s;
2104 transformation offset = t;
2105 transformation test_t;
2107 for (int i = 0; i < 2; i++)
2108 for (adj_s = -adj_p; adj_s <= adj_p; adj_s += 2 * adj_p) {
2110 test_t = offset;
2112 test_t.translate(i ? point(adj_s, 0) : point(0, adj_s));
2114 set->push_back(test_t);
2118 static int threshold_ok(ale_accum error) {
2119 if ((1 - error) * 100 >= match_threshold)
2120 return 1;
2122 if (!(match_threshold >= 0))
2123 return 1;
2125 return 0;
2129 * Align frame m against the reference.
2131 * XXX: the transformation class currently combines ordinary
2132 * transformations with scaling. This is somewhat convenient for
2133 * some things, but can also be confusing. This method, _align(), is
2134 * one case where special care must be taken to ensure that the scale
2135 * is always set correctly (by using the 'rescale' method).
2137 static diff_stat_t _align(int m, int local_gs, element_t *element) {
2139 const image *input_frame = element->input_frame;
2142 * Local upper/lower data, possibly dependent on image
2143 * dimensions.
2146 ale_pos local_lower, local_upper, local_gs_mo;
2149 * Select the minimum dimension as the reference.
2152 ale_pos reference_size = input_frame->height();
2153 if (input_frame->width() < reference_size)
2154 reference_size = input_frame->width();
2155 ale_pos reference_area = input_frame->height()
2156 * input_frame->width();
2158 if (perturb_lower_percent)
2159 local_lower = perturb_lower
2160 * reference_size
2161 * 0.01
2162 * scale_factor;
2163 else
2164 local_lower = perturb_lower;
2166 if (perturb_upper_percent)
2167 local_upper = perturb_upper
2168 * reference_size
2169 * 0.01
2170 * scale_factor;
2171 else
2172 local_upper = perturb_upper;
2174 local_upper = pow(2, floor(log(local_upper) / log(2)));
2176 if (gs_mo_percent)
2177 local_gs_mo = _gs_mo
2178 * reference_area
2179 * 0.01
2180 * scale_factor;
2181 else
2182 local_gs_mo = _gs_mo;
2185 * Logarithms aren't exact, so we divide repeatedly to discover
2186 * how many steps will occur, and pass this information to the
2187 * user interface.
2190 int step_count = 0;
2191 double step_variable = local_upper;
2192 while (step_variable >= local_lower) {
2193 step_variable /= 2;
2194 step_count++;
2197 ui::get()->set_steps(step_count);
2199 ale_pos perturb = local_upper;
2200 int lod;
2202 if (_keep) {
2203 kept_t[latest] = latest_t;
2204 kept_ok[latest] = latest_ok;
2208 * Maximum level-of-detail. Use a level of detail at most
2209 * 2^lod_diff finer than the adjustment resolution. lod_diff
2210 * is a synonym for lod_max.
2213 const int lod_diff = lod_max;
2216 * Determine how many levels of detail should be prepared.
2220 * Plain (unsigned int) casting seems to be broken in some cases.
2223 unsigned int steps = (perturb > pow(2, lod_max))
2224 ? (unsigned int) lrint(log(perturb) / log(2)) - lod_max + 1 : 1;
2227 * Prepare multiple levels of detail.
2230 int local_ax_count;
2231 struct scale_cluster *scale_clusters = init_clusters(m,
2232 scale_factor, input_frame, steps,
2233 &local_ax_count);
2236 * Initialize variables used in the main loop.
2239 lod = (steps - 1);
2242 * Initialize the default initial transform
2245 if (default_initial_alignment_type == 0) {
2248 * Follow the transformation of the original frame,
2249 * setting new image dimensions.
2252 // element->default_initial_alignment = orig_t;
2253 element->default_initial_alignment.set_current_element(orig_t.get_element(0));
2254 element->default_initial_alignment.set_dimensions(input_frame);
2256 } else if (default_initial_alignment_type == 1)
2259 * Follow previous transformation, setting new image
2260 * dimensions.
2263 element->default_initial_alignment.set_dimensions(input_frame);
2265 else
2266 assert(0);
2268 element->old_is_default = element->is_default;
2271 * Scale default initial transform for lod
2274 element->default_initial_alignment.rescale(1 / pow(2, lod));
2277 * Set the default transformation.
2280 transformation offset = element->default_initial_alignment;
2283 * Load any file-specified transformations
2286 for (offset.set_current_index(0);
2287 offset.get_current_index() < _ma_card;
2288 offset.push_element()) {
2290 offset = tload_next(tload, alignment_class == 2,
2291 offset,
2292 &element->is_default,
2293 offset.get_current_index() == 0);
2297 offset.set_current_index(0);
2299 ui::get()->set_offset(offset);
2301 if (perturb > 0) {
2304 * Apply following logic
2307 transformation new_offset = follow(element, offset, lod);
2309 new_offset.set_current_index(0);
2311 element->old_initial_alignment = offset;
2312 element->old_lod = lod;
2313 offset = new_offset;
2315 } else {
2316 element->old_initial_alignment = offset;
2317 element->old_lod = lod;
2320 struct scale_cluster si = scale_clusters[lod];
2323 * Projective adjustment value
2326 ale_pos adj_p = (perturb >= pow(2, lod_diff))
2327 ? pow(2, lod_diff) : (double) perturb;
2330 * Orientational adjustment value in degrees.
2332 * Since rotational perturbation is now specified as an
2333 * arclength, we have to convert.
2336 ale_pos adj_o = 2 * perturb
2337 / sqrt(pow(scale_clusters[0].input->height(), 2)
2338 + pow(scale_clusters[0].input->width(), 2))
2339 * 180
2340 / M_PI;
2343 * Barrel distortion adjustment value
2346 ale_pos adj_b = perturb * bda_mult;
2349 * Global search overlap requirements.
2352 local_gs_mo /= pow(pow(2, lod), 2);
2355 * Pre-alignment exposure adjustment
2358 if (_exp_register) {
2359 ui::get()->exposure_1();
2360 transformation o = offset;
2361 for (int k = lod; k > 0; k--)
2362 o.rescale(2);
2363 set_exposure_ratio(m, scale_clusters[0], o, local_ax_count, 0);
2367 * Alignment statistics.
2370 diff_stat_t here;
2373 * Current difference (error) value
2376 ui::get()->prematching();
2377 here.diff(si, perturb, offset, local_ax_count, m);
2378 ui::get()->set_match(here.get_error());
2381 * Current and modified barrel distortion parameters
2384 ale_pos current_bd[BARREL_DEGREE];
2385 ale_pos modified_bd[BARREL_DEGREE];
2386 offset.bd_get(current_bd);
2387 offset.bd_get(modified_bd);
2390 * Translational global search step
2393 if (perturb >= local_lower && local_gs != 0 && local_gs != 5
2394 && (local_gs != 6 || element->is_default)) {
2396 ui::get()->global_alignment(perturb, lod);
2397 ui::get()->gs_mo(local_gs_mo);
2399 test_globals(&here, si, here.get_offset(), local_gs, adj_p,
2400 local_ax_count, m, local_gs_mo, perturb);
2402 ui::get()->set_match(here.get_error());
2403 ui::get()->set_offset(here.get_offset());
2407 * Control point alignment
2410 if (local_gs == 5) {
2412 transformation o = here.get_offset();
2414 for (int k = lod; k > 0; k--)
2415 o.rescale(2);
2418 * Determine centroid data
2421 point current, previous;
2422 centroids(m, &current, &previous);
2424 if (current.defined() && previous.defined()) {
2425 o = orig_t;
2426 o.set_dimensions(input_frame);
2427 o.translate((previous - current) * o.scale());
2428 current = previous;
2432 * Determine rotation for alignment classes other than translation.
2435 ale_accum lowest_error = cp_rms_error(m, o);
2437 ale_pos rot_lower = 2 * local_lower
2438 / sqrt(pow(scale_clusters[0].input->height(), 2)
2439 + pow(scale_clusters[0].input->width(), 2))
2440 * 180
2441 / M_PI;
2443 if (alignment_class > 0)
2444 for (ale_pos rot = 30; rot > rot_lower; rot /= 2)
2445 for (ale_pos srot = -rot; srot < rot * 1.5; srot += rot * 2) {
2446 int is_improved = 1;
2447 while (is_improved) {
2448 is_improved = 0;
2449 transformation test_t = o;
2451 * XXX: is this right?
2453 test_t.rotate(current * o.scale(), srot);
2454 ale_pos test_v = cp_rms_error(m, test_t);
2456 if (test_v < lowest_error) {
2457 lowest_error = test_v;
2458 o = test_t;
2459 srot += 3 * rot;
2460 is_improved = 1;
2466 * Determine projective parameters through a local
2467 * minimum search.
2470 if (alignment_class == 2) {
2471 ale_accum adj_p = lowest_error;
2473 if (adj_p < local_lower)
2474 adj_p = local_lower;
2476 while (adj_p >= local_lower) {
2477 transformation test_t = o;
2478 int is_improved = 1;
2479 ale_accum test_v;
2480 ale_accum adj_s;
2482 while (is_improved) {
2483 is_improved = 0;
2485 for (int i = 0; i < 4; i++)
2486 for (int j = 0; j < 2; j++)
2487 for (adj_s = -adj_p; adj_s <= adj_p; adj_s += 2 * adj_p) {
2489 test_t = o;
2491 if (perturb_type == 0)
2492 test_t.gpt_modify(j, i, adj_s);
2493 else if (perturb_type == 1)
2494 test_t.gr_modify(j, i, adj_s);
2495 else
2496 assert(0);
2498 test_v = cp_rms_error(m, test_t);
2500 if (test_v < lowest_error) {
2501 lowest_error = test_v;
2502 o = test_t;
2503 adj_s += 3 * adj_p;
2504 is_improved = 1;
2508 adj_p /= 2;
2512 if (_exp_register)
2513 set_exposure_ratio(m, scale_clusters[0], o, local_ax_count, 0);
2515 for (int k = lod; k > 0; k--)
2516 o.rescale(0.5);
2518 here.diff(si, perturb, o, local_ax_count, m);
2519 here.confirm();
2520 ui::get()->set_match(here.get_error());
2521 ui::get()->set_offset(here.get_offset());
2525 * Announce perturbation size
2528 ui::get()->aligning(perturb, lod);
2531 * Run initial tests to get perturbation multipliers and error
2532 * centroids.
2535 std::vector<transformation> t_set;
2537 here.get_perturb_set(&t_set, adj_p, adj_o, adj_b, current_bd, modified_bd);
2540 * Perturbation adjustment loop.
2543 int stable_count = 0;
2545 while (perturb >= local_lower) {
2548 * Orientational adjustment value in degrees.
2550 * Since rotational perturbation is now specified as an
2551 * arclength, we have to convert.
2554 ale_pos adj_o = 2 * perturb
2555 / sqrt(pow(scale_clusters[0].input->height(), 2)
2556 + pow(scale_clusters[0].input->width(), 2))
2557 * 180
2558 / M_PI;
2561 * Barrel distortion adjustment value
2564 ale_pos adj_b = perturb * bda_mult;
2566 diff_stat_t old_here = here;
2568 here.perturb_test(perturb, adj_p, adj_o, adj_b, current_bd, modified_bd,
2569 stable_count);
2571 if (here.get_offset() == old_here.get_offset())
2572 stable_count++;
2573 else
2574 stable_count = 0;
2576 if (stable_count == 3) {
2578 stable_count = 0;
2580 here.calculate_element_region();
2582 if (here.get_current_index() + 1 < _ma_card) {
2583 here.push_element();
2584 here.make_element_nontrivial(adj_p, adj_o);
2585 element->is_primary = 0;
2586 } else {
2588 here.set_current_index(0);
2590 element->is_primary = 1;
2592 perturb *= 0.5;
2594 if (lod > 0) {
2597 * Work with images twice as large
2600 lod--;
2601 si = scale_clusters[lod];
2604 * Rescale the transforms.
2607 here.rescale(2, si);
2608 element->default_initial_alignment.rescale(2);
2610 } else {
2611 adj_p = perturb;
2615 * Announce changes
2618 ui::get()->alignment_perturbation_level(perturb, lod);
2623 ui::get()->set_match(here.get_error());
2624 ui::get()->set_offset(here.get_offset());
2627 here.set_current_index(0);
2629 if (lod > 0) {
2630 here.rescale(pow(2, lod), scale_clusters[0]);
2631 element->default_initial_alignment.rescale(pow(2, lod));
2634 offset = here.get_offset();
2637 * Post-alignment exposure adjustment
2640 if (_exp_register == 1) {
2641 ui::get()->exposure_2();
2642 set_exposure_ratio(m, scale_clusters[0], offset, local_ax_count, 1);
2646 * Recalculate error
2649 ui::get()->postmatching();
2650 offset.use_full_support();
2651 here.diff(scale_clusters[0], perturb, offset, local_ax_count, m);
2652 here.confirm();
2653 offset.use_restricted_support();
2654 ui::get()->set_match(here.get_error());
2657 * Free the level-of-detail structures
2660 final_clusters(scale_clusters, scale_factor, steps);
2663 * Ensure that the match meets the threshold.
2666 if (threshold_ok(here.get_error())) {
2668 * Update alignment variables
2670 latest_ok = 1;
2671 element->default_initial_alignment = offset;
2672 element->old_final_alignment = offset;
2673 ui::get()->alignment_match_ok();
2674 } else if (local_gs == 4) {
2677 * Align with outer starting points.
2681 * XXX: This probably isn't exactly the right thing to do,
2682 * since variables like old_initial_value have been overwritten.
2685 diff_stat_t nested_result = _align(m, -1, element);
2687 if (threshold_ok(nested_result.get_error())) {
2688 return nested_result;
2689 } else if (nested_result.get_error() < here.get_error()) {
2690 here = nested_result;
2693 if (is_fail_default)
2694 offset = element->default_initial_alignment;
2696 ui::get()->set_match(here.get_error());
2697 ui::get()->alignment_no_match();
2699 } else if (local_gs == -1) {
2701 latest_ok = 0;
2702 latest_t = offset;
2703 return here;
2705 } else {
2706 if (is_fail_default)
2707 offset = element->default_initial_alignment;
2708 latest_ok = 0;
2709 ui::get()->alignment_no_match();
2713 * Write the tonal registration multiplier as a comment.
2716 pixel trm = image_rw::exp(m).get_multiplier();
2717 tsave_trm(tsave, trm[0], trm[1], trm[2]);
2720 * Save the transformation information
2723 for (offset.set_current_index(0);
2724 offset.get_current_index() < _ma_card;
2725 offset.push_element()) {
2727 tsave_next(tsave, offset, alignment_class == 2,
2728 offset.get_current_index() == 0);
2731 offset.set_current_index(0);
2733 latest_t = offset;
2736 * Update match statistics.
2739 match_sum += (1 - here.get_error()) * 100;
2740 match_count++;
2741 latest = m;
2743 return here;
2746 #ifdef USE_FFTW
2748 * High-pass filter for frequency weights
2750 static void hipass(int rows, int cols, fftw_complex *inout) {
2751 for (int i = 0; i < rows * vert_freq_cut; i++)
2752 for (int j = 0; j < cols; j++)
2753 for (int k = 0; k < 2; k++)
2754 inout[i * cols + j][k] = 0;
2755 for (int i = 0; i < rows; i++)
2756 for (int j = 0; j < cols * horiz_freq_cut; j++)
2757 for (int k = 0; k < 2; k++)
2758 inout[i * cols + j][k] = 0;
2759 for (int i = 0; i < rows; i++)
2760 for (int j = 0; j < cols; j++)
2761 for (int k = 0; k < 2; k++)
2762 if (i / (double) rows + j / (double) cols < 2 * avg_freq_cut)
2763 inout[i * cols + j][k] = 0;
2765 #endif
2769 * Reset alignment weights
2771 static void reset_weights() {
2772 if (alignment_weights != NULL)
2773 delete alignment_weights;
2775 alignment_weights = NULL;
2779 * Initialize alignment weights
2781 static void init_weights() {
2782 if (alignment_weights != NULL)
2783 return;
2785 int rows = reference_image->height();
2786 int cols = reference_image->width();
2787 int colors = reference_image->depth();
2789 alignment_weights = new image_ale_real(rows, cols,
2790 colors, "alignment_weights");
2792 assert (alignment_weights);
2794 for (int i = 0; i < rows; i++)
2795 for (int j = 0; j < cols; j++)
2796 alignment_weights->set_pixel(i, j, pixel(1, 1, 1));
2800 * Update alignment weights with weight map
2802 static void map_update() {
2804 if (weight_map == NULL)
2805 return;
2807 init_weights();
2809 point map_offset = reference_image->offset() - weight_map->offset();
2811 int rows = reference_image->height();
2812 int cols = reference_image->width();
2814 for (int i = 0; i < rows; i++)
2815 for (int j = 0; j < cols; j++) {
2816 point map_weight_position = map_offset + point(i, j);
2817 if (map_weight_position[0] >= 0
2818 && map_weight_position[1] >= 0
2819 && map_weight_position[0] <= weight_map->height() - 1
2820 && map_weight_position[1] <= weight_map->width() - 1)
2821 alignment_weights->pix(i, j) *= weight_map->get_bl(map_weight_position);
2826 * Update alignment weights with algorithmic weights
2828 static void wmx_update() {
2829 #ifdef USE_UNIX
2831 static exposure *exp_def = new exposure_default();
2832 static exposure *exp_bool = new exposure_boolean();
2834 if (wmx_file == NULL || wmx_exec == NULL || wmx_defs == NULL)
2835 return;
2837 unsigned int rows = reference_image->height();
2838 unsigned int cols = reference_image->width();
2840 image_rw::write_image(wmx_file, reference_image);
2841 image_rw::write_image(wmx_defs, reference_defined, exp_bool);
2843 /* execute ... */
2844 int exit_status = 1;
2845 if (!fork()) {
2846 execlp(wmx_exec, wmx_exec, wmx_file, wmx_defs, NULL);
2847 ui::get()->exec_failure(wmx_exec, wmx_file, wmx_defs);
2850 wait(&exit_status);
2852 if (exit_status)
2853 ui::get()->fork_failure("d2::align");
2855 image *wmx_weights = image_rw::read_image(wmx_file, exp_def);
2857 if (wmx_weights->height() != rows || wmx_weights->width() != cols)
2858 ui::get()->error("algorithmic weighting must not change image size");
2860 if (alignment_weights == NULL)
2861 alignment_weights = wmx_weights;
2862 else
2863 for (unsigned int i = 0; i < rows; i++)
2864 for (unsigned int j = 0; j < cols; j++)
2865 alignment_weights->pix(i, j) *= wmx_weights->pix(i, j);
2866 #endif
2870 * Update alignment weights with frequency weights
2872 static void fw_update() {
2873 #ifdef USE_FFTW
2874 if (horiz_freq_cut == 0
2875 && vert_freq_cut == 0
2876 && avg_freq_cut == 0)
2877 return;
2880 * Required for correct operation of --fwshow
2883 assert (alignment_weights == NULL);
2885 int rows = reference_image->height();
2886 int cols = reference_image->width();
2887 int colors = reference_image->depth();
2889 alignment_weights = new image_ale_real(rows, cols,
2890 colors, "alignment_weights");
2892 fftw_complex *inout = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * rows * cols);
2894 assert (inout);
2896 fftw_plan pf = fftw_plan_dft_2d(rows, cols,
2897 inout, inout,
2898 FFTW_FORWARD, FFTW_ESTIMATE);
2900 fftw_plan pb = fftw_plan_dft_2d(rows, cols,
2901 inout, inout,
2902 FFTW_BACKWARD, FFTW_ESTIMATE);
2904 for (int k = 0; k < colors; k++) {
2905 for (int i = 0; i < rows * cols; i++) {
2906 inout[i][0] = reference_image->get_pixel(i / cols, i % cols)[k];
2907 inout[i][1] = 0;
2910 fftw_execute(pf);
2911 hipass(rows, cols, inout);
2912 fftw_execute(pb);
2914 for (int i = 0; i < rows * cols; i++) {
2915 #if 0
2916 alignment_weights->pix(i / cols, i % cols)[k] = fabs(inout[i][0] / (rows * cols));
2917 #else
2918 alignment_weights->pix(i / cols, i % cols)[k] =
2919 sqrt(pow(inout[i][0] / (rows * cols), 2)
2920 + pow(inout[i][1] / (rows * cols), 2));
2921 #endif
2925 fftw_destroy_plan(pf);
2926 fftw_destroy_plan(pb);
2927 fftw_free(inout);
2929 if (fw_output != NULL)
2930 image_rw::write_image(fw_output, alignment_weights);
2931 #endif
2935 * Update alignment to frame N.
2937 static void update_to(int n) {
2939 assert (n <= latest + 1);
2940 assert (n >= 0);
2942 static std::vector<element_t> elements;
2944 if (latest < 0) {
2946 elements.resize(1);
2949 * Handle the initial frame
2952 elements[0].input_frame = image_rw::open(n);
2954 const image *i = elements[0].input_frame;
2955 int is_default;
2956 transformation result = alignment_class == 2
2957 ? transformation::gpt_identity(i, scale_factor)
2958 : transformation::eu_identity(i, scale_factor);
2959 result = tload_first(tload, alignment_class == 2, result, &is_default);
2960 tsave_first(tsave, result, alignment_class == 2);
2962 if (_keep > 0) {
2963 kept_t = new transformation[image_rw::count()];
2964 kept_ok = (int *) malloc(image_rw::count()
2965 * sizeof(int));
2966 assert (kept_t);
2967 assert (kept_ok);
2969 if (!kept_t || !kept_ok)
2970 ui::get()->memory_error("alignment");
2972 kept_ok[0] = 1;
2973 kept_t[0] = result;
2976 latest = 0;
2977 latest_ok = 1;
2978 latest_t = result;
2980 elements[0].default_initial_alignment = result;
2981 orig_t = result;
2983 image_rw::close(n);
2986 for (int i = latest + 1; i <= n; i++) {
2987 int j = 0;
2990 * Handle supplemental frames.
2993 assert (reference != NULL);
2995 ui::get()->set_arender_current();
2996 reference->sync(i - 1);
2997 ui::get()->clear_arender_current();
2998 reference_image = reference->get_image();
2999 reference_defined = reference->get_defined();
3001 reset_weights();
3002 fw_update();
3003 wmx_update();
3004 map_update();
3006 assert (reference_image != NULL);
3007 assert (reference_defined != NULL);
3009 elements[j].input_frame = image_rw::open(i);
3010 elements[j].is_primary = 1;
3012 _align(i, _gs, &elements[j]);
3014 image_rw::close(n);
3017 if (elements.size() > _ma_card)
3018 elements.resize(_ma_card);
3021 public:
3024 * Set the control point count
3026 static void set_cp_count(unsigned int n) {
3027 assert (cp_array == NULL);
3029 cp_count = n;
3030 cp_array = (const point **) malloc(n * sizeof(const point *));
3034 * Set control points.
3036 static void set_cp(unsigned int i, const point *p) {
3037 cp_array[i] = p;
3041 * Register exposure
3043 static void exp_register() {
3044 _exp_register = 1;
3048 * Register exposure only based on metadata
3050 static void exp_meta_only() {
3051 _exp_register = 2;
3055 * Don't register exposure
3057 static void exp_noregister() {
3058 _exp_register = 0;
3062 * Set alignment class to translation only. Only adjust the x and y
3063 * position of images. Do not rotate input images or perform
3064 * projective transformations.
3066 static void class_translation() {
3067 alignment_class = 0;
3071 * Set alignment class to Euclidean transformations only. Adjust the x
3072 * and y position of images and the orientation of the image about the
3073 * image center.
3075 static void class_euclidean() {
3076 alignment_class = 1;
3080 * Set alignment class to perform general projective transformations.
3081 * See the file gpt.h for more information about general projective
3082 * transformations.
3084 static void class_projective() {
3085 alignment_class = 2;
3089 * Set the default initial alignment to the identity transformation.
3091 static void initial_default_identity() {
3092 default_initial_alignment_type = 0;
3096 * Set the default initial alignment to the most recently matched
3097 * frame's final transformation.
3099 static void initial_default_follow() {
3100 default_initial_alignment_type = 1;
3104 * Perturb output coordinates.
3106 static void perturb_output() {
3107 perturb_type = 0;
3111 * Perturb source coordinates.
3113 static void perturb_source() {
3114 perturb_type = 1;
3118 * Frames under threshold align optimally
3120 static void fail_optimal() {
3121 is_fail_default = 0;
3125 * Frames under threshold keep their default alignments.
3127 static void fail_default() {
3128 is_fail_default = 1;
3132 * Align images with an error contribution from each color channel.
3134 static void all() {
3135 channel_alignment_type = 0;
3139 * Align images with an error contribution only from the green channel.
3140 * Other color channels do not affect alignment.
3142 static void green() {
3143 channel_alignment_type = 1;
3147 * Align images using a summation of channels. May be useful when
3148 * dealing with images that have high frequency color ripples due to
3149 * color aliasing.
3151 static void sum() {
3152 channel_alignment_type = 2;
3156 * Error metric exponent
3159 static void set_metric_exponent(float me) {
3160 metric_exponent = me;
3164 * Match threshold
3167 static void set_match_threshold(float mt) {
3168 match_threshold = mt;
3172 * Perturbation lower and upper bounds.
3175 static void set_perturb_lower(ale_pos pl, int plp) {
3176 perturb_lower = pl;
3177 perturb_lower_percent = plp;
3180 static void set_perturb_upper(ale_pos pu, int pup) {
3181 perturb_upper = pu;
3182 perturb_upper_percent = pup;
3186 * Maximum rotational perturbation.
3189 static void set_rot_max(int rm) {
3192 * Obtain the largest power of two not larger than rm.
3195 rot_max = pow(2, floor(log(rm) / log(2)));
3199 * Barrel distortion adjustment multiplier
3202 static void set_bda_mult(ale_pos m) {
3203 bda_mult = m;
3207 * Barrel distortion maximum rate of change
3210 static void set_bda_rate(ale_pos m) {
3211 bda_rate = m;
3215 * Level-of-detail
3218 static void set_lod_max(int lm) {
3219 lod_max = lm;
3223 * Set the scale factor
3225 static void set_scale(ale_pos s) {
3226 scale_factor = s;
3230 * Set reference rendering to align against
3232 static void set_reference(render *r) {
3233 reference = r;
3237 * Set the interpolant
3239 static void set_interpolant(filter::scaled_filter *f) {
3240 interpolant = f;
3244 * Set alignment weights image
3246 static void set_weight_map(const image *i) {
3247 weight_map = i;
3251 * Set frequency cuts
3253 static void set_frequency_cut(double h, double v, double a) {
3254 horiz_freq_cut = h;
3255 vert_freq_cut = v;
3256 avg_freq_cut = a;
3260 * Set algorithmic alignment weighting
3262 static void set_wmx(const char *e, const char *f, const char *d) {
3263 wmx_exec = e;
3264 wmx_file = f;
3265 wmx_defs = d;
3269 * Show frequency weights
3271 static void set_fl_show(const char *filename) {
3272 fw_output = filename;
3276 * Set transformation file loader.
3278 static void set_tload(tload_t *tl) {
3279 tload = tl;
3283 * Set transformation file saver.
3285 static void set_tsave(tsave_t *ts) {
3286 tsave = ts;
3290 * Get match statistics for frame N.
3292 static int match(int n) {
3293 update_to(n);
3295 if (n == latest)
3296 return latest_ok;
3297 else if (_keep)
3298 return kept_ok[n];
3299 else {
3300 assert(0);
3301 exit(1);
3306 * Message that old alignment data should be kept.
3308 static void keep() {
3309 assert (latest == -1);
3310 _keep = 1;
3314 * Get alignment for frame N.
3316 static transformation of(int n) {
3317 update_to(n);
3318 if (n == latest)
3319 return latest_t;
3320 else if (_keep)
3321 return kept_t[n];
3322 else {
3323 assert(0);
3324 exit(1);
3329 * Use Monte Carlo alignment sampling with argument N.
3331 static void mc(ale_pos n) {
3332 _mc = n;
3336 * Set the certainty-weighted flag.
3338 static void certainty_weighted(int flag) {
3339 certainty_weights = flag;
3343 * Set the global search type.
3345 static void gs(const char *type) {
3346 if (!strcmp(type, "local")) {
3347 _gs = 0;
3348 } else if (!strcmp(type, "inner")) {
3349 _gs = 1;
3350 } else if (!strcmp(type, "outer")) {
3351 _gs = 2;
3352 } else if (!strcmp(type, "all")) {
3353 _gs = 3;
3354 } else if (!strcmp(type, "central")) {
3355 _gs = 4;
3356 } else if (!strcmp(type, "defaults")) {
3357 _gs = 6;
3358 } else if (!strcmp(type, "points")) {
3359 _gs = 5;
3360 keep();
3361 } else {
3362 ui::get()->error("bad global search type");
3367 * Multi-alignment contiguity
3369 static void ma_cont(double value) {
3370 _ma_cont = value;
3374 * Multi-alignment cardinality
3376 static void ma_card(unsigned int value) {
3377 assert (value >= 1);
3378 _ma_card = value;
3382 * Set the minimum overlap for global searching
3384 static void gs_mo(ale_pos value, int _gs_mo_percent) {
3385 _gs_mo = value;
3386 gs_mo_percent = _gs_mo_percent;
3390 * Set alignment exclusion regions
3392 static void set_exclusion(exclusion *_ax_parameters, int _ax_count) {
3393 ax_count = _ax_count;
3394 ax_parameters = _ax_parameters;
3398 * Get match summary statistics.
3400 static ale_accum match_summary() {
3401 return match_sum / match_count;
3405 #endif