diff --git a/exotic/exotic.py b/exotic/exotic.py index 279e12da..ed7e6348 100644 --- a/exotic/exotic.py +++ b/exotic/exotic.py @@ -21102,7 +21102,9 @@ def transformation(image_data, file_name, roi=1, report_failure=True, reference_ if np.all(np.isfinite(shift)) and np.isfinite(error): max_shift = max(abs(shift[0]), abs(shift[1])) if max_shift <= max(roi_current.shape): - fft_tform = SimilarityTransform(scale=1, rotation=0, translation=[-shift[1], -shift[0]]) + # phase_cross_correlation(current, reference) returns the shift that moves the reference onto the + # current frame, so the reference-to-current transform uses it with a positive sign. + fft_tform = SimilarityTransform(scale=1, rotation=0, translation=[shift[1], shift[0]]) fft_high_confidence = error <= 0.1 and max_shift <= max(roi_current.shape) * 0.25 _record_transform_stage_timing('fft_translation', perf_counter() - stage_start, True) if fft_high_confidence: diff --git a/tests/test_fft_alignment_sign.py b/tests/test_fft_alignment_sign.py new file mode 100644 index 00000000..3c97e6cf --- /dev/null +++ b/tests/test_fft_alignment_sign.py @@ -0,0 +1,39 @@ +"""Regression test for the sign of the FFT translation in transformation(). + +transformation() returns a transform that maps reference-frame pixels onto the current frame (as the astroalign and +imreg_dft branches do). Its FFT fallback calls phase_cross_correlation(roi_current, roi_reference), whose shift moves the +reference onto the current frame, so the translation must use that shift with a positive sign. With the old negated +sign, a field moved by (+10, +5) px sent a reference star at (100, 80) to (90, 75) instead of (110, 85). +Fix originally proposed in PR #1426 (commit 8f30f97). +""" +import numpy as np +import pytest + + +def _field(points, dx, dy, shape=(200, 240), seed=1): + rng = np.random.default_rng(seed) + yy, xx = np.mgrid[0:shape[0], 0:shape[1]] + img = np.zeros(shape) + for x, y in points: + img += 500 * np.exp(-((xx - (x + dx)) ** 2 + (yy - (y + dy)) ** 2) / (2 * 2.0 ** 2)) + return img + rng.normal(0, 1, shape) + + +def test_fft_fallback_maps_reference_onto_current(monkeypatch): + from exotic import exotic as ex + + def fail(*args, **kwargs): + raise RuntimeError("forced failure so the FFT translation decides") + + # Force the feature-matching branches to fail so the FFT result is the one returned. + monkeypatch.setattr(ex.aa, "find_transform", fail) + monkeypatch.setattr(ex.ird, "similarity", fail) + + rng = np.random.default_rng(0) + points = [(rng.uniform(30, 200), rng.uniform(30, 160)) for _ in range(25)] + reference = _field(points, 0, 0, seed=1) + current = _field(points, 10, 5, seed=2) # independent noise, or the noise itself correlates at zero shift + + tform = ex.transformation(current, "synthetic", report_failure=False, reference_image=reference) + mapped = tform(np.array([[100.0, 80.0]]))[0] + assert np.allclose(mapped, [110.0, 85.0], atol=1.0), mapped