feat(motion): add FFT plans and Kuglin–Hines phase correlation

Radix-2 Cooley–Tukey with SIMD butterflies and Bluestein chirp-z for
arbitrary lengths, cached plans, parallel 2D transforms, real-input
half-length transforms and Tukey/Hann windows. Phase correlation packs
both patches into one complex FFT, normalises the cross-power spectrum
with a Gaussian low-pass and refines the peak with a log-parabola fit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 09:19:18 +00:00
1 parent 800843d2ae
commit bda76ccff2
6 files changed
+1199

No files matched your search

@@ -0,0 +1,176 @@
using Titano.Core.Motion;
using Titano.Testing;
namespace Titano.Core.Tests.Motion;
public sealed class FourierTests
{
[Theory]
[Case(1)]
[Case(2)]
[Case(64)]
[Case(1024)]
[Case(4096)]
public void PowerOfTwoRoundTrip(int n)
{
var (re, im) = RandomSignal(n, seed: n);
var (r0, i0) = ((double[])re.Clone(), (double[])im.Clone());
Fourier.Forward(re, im);
Fourier.Inverse(re, im);
Assert.LessOrEqual(MaxError(r0, i0, re, im), 1e-5);
}
[Theory]
[Case(3)]
[Case(7)]
[Case(13)]
[Case(97)]
[Case(251)]
[Case(1009)]
public void BluesteinMatchesDirectDftForPrimes(int n)
{
var (re, im) = RandomSignal(n, seed: n);
var (er, ei) = Dft(re, im);
Fourier.Forward(re, im);
var scale = double.Sqrt(n);
Assert.LessOrEqual(MaxError(er, ei, re, im) / scale, 1e-9);
}
[Theory]
[Case(12)]
[Case(100)]
[Case(1000)]
public void CompositeLengthsRoundTrip(int n)
{
var (re, im) = RandomSignal(n, seed: 3 * n);
var (r0, i0) = ((double[])re.Clone(), (double[])im.Clone());
Fourier.Forward(re, im);
Fourier.Inverse(re, im);
Assert.LessOrEqual(MaxError(r0, i0, re, im), 1e-5);
}
[Theory]
[Case(64)]
[Case(100)]
[Case(15)]
public void RealTransformMatchesComplexAndRoundTrips(int n)
{
var (signal, _) = RandomSignal(n, seed: 11 * n);
var bins = n / 2 + 1;
var hr = new double[bins];
var hi = new double[bins];
Fourier.ForwardReal(signal, hr, hi);
var re = (double[])signal.Clone();
var im = new double[n];
Fourier.Forward(re, im);
Assert.LessOrEqual(MaxError(re.AsSpan(0, bins).ToArray(), im.AsSpan(0, bins).ToArray(), hr, hi), 1e-9);
var back = new double[n];
Fourier.InverseReal(hr, hi, back);
for (var i = 0; i < n; i++) Assert.Approximately(signal[i], back[i], 1e-9);
}
[Theory]
[Case(64, 64)]
[Case(48, 36)]
[Case(256, 160)]
public void TwoDimensionalRoundTripAndShiftTheorem(int width, int height)
{
var (re, im) = RandomSignal(width * height, seed: width + height);
var (r0, i0) = ((double[])re.Clone(), (double[])im.Clone());
Fourier.Forward2D(re, im, width, height);
// A unit impulse at (1, 0) transforms to e^(−2πiu/W) on every row: check one bin of a separate impulse.
var dr = new double[width * height];
var di = new double[width * height];
dr[1] = 1;
Fourier.Forward2D(dr, di, width, height);
var (s, c) = double.SinCos(-2 * double.Pi * 3 / width);
Assert.Approximately(c, dr[2 * width + 3], 1e-12);
Assert.Approximately(s, di[2 * width + 3], 1e-12);
Fourier.Inverse2D(re, im, width, height);
Assert.LessOrEqual(MaxError(r0, i0, re, im), 1e-5);
}
[Test]
public void ParsevalHolds()
{
const int n = 512;
var (re, im) = RandomSignal(n, seed: 5);
double time = 0, freq = 0;
for (var i = 0; i < n; i++) time += re[i] * re[i] + im[i] * im[i];
Fourier.Forward(re, im);
for (var i = 0; i < n; i++) freq += re[i] * re[i] + im[i] * im[i];
Assert.Approximately(time, freq / n, 1e-9 * time);
}
[Test]
public void WindowsHaveExpectedShape()
{
var hann = new double[9];
Fourier.Hann(hann);
Assert.Approximately(0, hann[0], 1e-15);
Assert.Approximately(1, hann[4], 1e-15);
Assert.Approximately(0.5, hann[2], 1e-12);
Assert.Approximately(hann[1], hann[7], 1e-15);
var rect = new double[9];
Fourier.Tukey(rect, 0);
Assert.True(rect.All(v => v == 1));
var tukey = new double[101];
Fourier.Tukey(tukey, 0.5);
Assert.Approximately(0, tukey[0], 1e-15);
Assert.Equal(1.0, tukey[25]);
Assert.Equal(1.0, tukey[75]);
// Mid-taper (x = 0.125) is at half height; the flanks rise monotonically and mirror each other.
Assert.InRange(tukey[12], 0.45, 0.5);
Assert.InRange(tukey[13], 0.5, 0.55);
Assert.Monotonic(tukey.Take(26).ToArray());
for (var i = 0; i < 101; i++) Assert.Approximately(tukey[i], tukey[100 - i], 1e-15);
}
[Test]
public void PlansAreCached() => Assert.Same(Fourier.Plan(96), Fourier.Plan(96));
private static (double[] Re, double[] Im) RandomSignal(int n, int seed)
{
var random = new Random(seed);
var re = new double[n];
var im = new double[n];
for (var i = 0; i < n; i++)
{
re[i] = random.NextDouble() * 2 - 1;
im[i] = random.NextDouble() * 2 - 1;
}
return (re, im);
}
private static (double[] Re, double[] Im) Dft(double[] re, double[] im)
{
var n = re.Length;
var or = new double[n];
var oi = new double[n];
for (var k = 0; k < n; k++)
{
double sr = 0, si = 0;
for (var t = 0; t < n; t++)
{
var (s, c) = double.SinCos(-2 * double.Pi * ((long)k * t % n) / n);
sr += re[t] * c - im[t] * s;
si += re[t] * s + im[t] * c;
}
or[k] = sr;
oi[k] = si;
}
return (or, oi);
}
private static double MaxError(double[] ar, double[] ai, double[] br, double[] bi)
{
double max = 0;
for (var i = 0; i < ar.Length; i++) max = double.Max(max, double.Max(double.Abs(ar[i] - br[i]), double.Abs(ai[i] - bi[i])));
return max;
}
}
@@ -0,0 +1,83 @@
using Titano.Core.Motion;
using Titano.Testing;
namespace Titano.Core.Tests.Motion;
public sealed class PhaseCorrelatorTests
{
private const int Size = 256;
private const int Patch = 128;
private readonly TestContext _context;
public PhaseCorrelatorTests(TestContext context) => _context = context;
[Theory]
[Case("noise", 3.25, -1.6)]
[Case("noise", 0.5, 0.5)]
[Case("noise", -7.8, 2.1)]
[Case("noise", 0.0, 0.0)]
[Case("natural", 3.25, -1.6)]
[Case("natural", 0.5, 0.5)]
[Case("natural", -7.8, 2.1)]
[Case("natural", 12.3, -9.45)]
public void SubPixelErrorWithinTenthOfPixel(string texture, double dx, double dy)
{
var image = texture == "noise" ? SyntheticImages.Noise(Size, 0.8, seed: 7) : SyntheticImages.Natural(Size, seed: 7);
var shifted = SyntheticImages.Shift(image, Size, dx, dy);
var reference = SyntheticImages.Crop(image, Size, 64, 64, Patch, Patch);
var moving = SyntheticImages.Crop(shifted, Size, 64, 64, Patch, Patch);
var result = new PhaseCorrelator(Patch, Patch).Correlate(reference, moving);
var error = double.Hypot(result.Dx - dx, result.Dy - dy);
_context.Log($"{texture} ({dx}, {dy}) → ({result.Dx:F4}, {result.Dy:F4}) error {error:F4} px, confidence {result.Confidence:F3}, peak {result.Peak:F3}");
Assert.LessOrEqual(error, 0.10);
Assert.Greater(result.Confidence, 0.5);
}
[Test]
public void NonPowerOfTwoPatchesUseBluestein()
{
var image = SyntheticImages.Natural(Size, seed: 3);
var shifted = SyntheticImages.Shift(image, Size, -2.4, 1.3);
var reference = SyntheticImages.Crop(image, Size, 60, 70, 96, 80);
var moving = SyntheticImages.Crop(shifted, Size, 60, 70, 96, 80);
var result = new PhaseCorrelator(96, 80).Correlate(reference, moving);
Assert.Within(-2.4, 1.3, result.Dx, result.Dy, 0.10);
}
[Test]
public void PatchesAreReadFromLargerPlanes()
{
var image = SyntheticImages.Noise(Size, 1.0, seed: 9);
var shifted = SyntheticImages.Shift(image, Size, 1.75, -0.25);
var a = SyntheticImages.Crop(image, Size, 0, 0, Size, Size);
var b = SyntheticImages.Crop(shifted, Size, 0, 0, Size, Size);
var result = new PhaseCorrelator(64, 64).Correlate(a, b, Size, 100, 40);
Assert.Within(1.75, -0.25, result.Dx, result.Dy, 0.10);
}
[Test]
public void UnrelatedContentHasLowConfidence()
{
var a = SyntheticImages.Crop(SyntheticImages.Noise(Size, 0.8, seed: 1), Size, 0, 0, Patch, Patch);
var b = SyntheticImages.Crop(SyntheticImages.Noise(Size, 0.8, seed: 2), Size, 0, 0, Patch, Patch);
var result = new PhaseCorrelator(Patch, Patch).Correlate(a, b);
_context.Log($"confidence {result.Confidence:F3}, peak {result.Peak:F3}");
Assert.Less(result.Confidence, 0.4);
Assert.Less(result.Peak, 0.2);
}
[Test]
public void MaxShiftLimitsTheSearch()
{
var image = SyntheticImages.Noise(Size, 0.8, seed: 4);
var shifted = SyntheticImages.Shift(image, Size, 20, 0);
var a = SyntheticImages.Crop(image, Size, 64, 64, Patch, Patch);
var b = SyntheticImages.Crop(shifted, Size, 64, 64, Patch, Patch);
var free = new PhaseCorrelator(Patch, Patch).Correlate(a, b);
Assert.Within(20, 0, free.Dx, free.Dy, 0.10);
var limited = new PhaseCorrelator(Patch, Patch, new PhaseCorrelatorOptions { MaxShift = 8 }).Correlate(a, b);
Assert.LessOrEqual(double.Abs(limited.Dx), 8.5);
}
}
@@ -0,0 +1,122 @@
using Titano.Core.Imaging;
using Titano.Core.Motion;
namespace Titano.Core.Tests.Motion;
/// <summary>Deterministic synthetic textures (periodic, band-limited) and exact sub-pixel shifts by Fourier phase ramp.</summary>
internal static class SyntheticImages
{
/// <summary>Gaussian-filtered white noise: spectral envelope exp(−2π²σ²|f|²), mean 0.5, standard deviation 0.15.</summary>
public static double[] Noise(int size, double sigma, int seed) =>
Synthesize(size, seed, f => double.Exp(-2 * double.Pi * double.Pi * sigma * sigma * f * f));
/// <summary>Natural-image-like texture: amplitude ∝ 1/f^1.4 with a soft high-frequency roll-off.</summary>
public static double[] Natural(int size, int seed) =>
Synthesize(size, seed, f => f == 0 ? 0 : double.Pow(f * size, -1.4) * double.Exp(-f * f / (2 * 0.2 * 0.2)));
/// <summary>Periodic shift with sub-pixel accuracy: result(x, y) = image(x − dx, y − dy).</summary>
public static double[] Shift(double[] image, int size, double dx, double dy)
{
var re = (double[])image.Clone();
var im = new double[re.Length];
Fourier.Forward2D(re, im, size, size);
for (var v = 0; v < size; v++)
{
for (var u = 0; u < size; u++)
{
var (s, c) = double.SinCos(-2 * double.Pi * (Signed(u, size) * dx + Signed(v, size) * dy) / size);
var i = v * size + u;
(re[i], im[i]) = (re[i] * c - im[i] * s, re[i] * s + im[i] * c);
}
}
Fourier.Inverse2D(re, im, size, size);
return re;
}
/// <summary>Copies a rectangle of a square periodic image into a float plane.</summary>
public static float[] Crop(double[] image, int size, int x0, int y0, int width, int height)
{
var plane = new float[width * height];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++) plane[y * width + x] = (float)image[((y0 + y) % size) * size + (x0 + x) % size];
}
return plane;
}
/// <summary>Single-channel buffer from a plane.</summary>
public static ImageBuffer ToBuffer(float[] plane, int width, int height)
{
var buffer = new ImageBuffer(width, height, 1, clear: false);
plane.AsSpan().CopyTo(buffer.Plane(0));
return buffer;
}
/// <summary>RGB buffer whose channels are scaled copies of a plane (distinct but correlated colours).</summary>
public static ImageBuffer ToRgb(float[] plane, int width, int height)
{
var buffer = new ImageBuffer(width, height, 3, clear: false);
for (var c = 0; c < 3; c++)
{
var dst = buffer.Plane(c);
var gain = 0.6f + 0.2f * c;
for (var i = 0; i < plane.Length; i++) dst[i] = plane[i] * gain;
}
return buffer;
}
/// <summary>Peak signal-to-noise ratio in dB for unit peak over the window [x0, x1)×[y0, y1).</summary>
public static double Psnr(ReadOnlySpan<float> a, ReadOnlySpan<float> b, int width, int x0, int y0, int x1, int y1)
{
double sum = 0;
var n = 0;
for (var y = y0; y < y1; y++)
{
for (var x = x0; x < x1; x++)
{
var d = a[y * width + x] - (double)b[y * width + x];
sum += d * d;
n++;
}
}
var mse = sum / n;
return mse == 0 ? double.PositiveInfinity : 10 * double.Log10(1 / mse);
}
private static double[] Synthesize(int size, int seed, Func<double, double> envelope)
{
var random = new Random(seed);
var re = new double[size * size];
var im = new double[size * size];
for (var v = 0; v < size; v++)
{
for (var u = 0; u < size; u++)
{
// Nyquist bins stay empty so the phase-ramp shift is exact for a real image.
if (u == size / 2 || v == size / 2) continue;
double fx = Signed(u, size) / (double)size, fy = Signed(v, size) / (double)size;
var a = envelope(double.Sqrt(fx * fx + fy * fy));
re[v * size + u] = a * Gaussian(random);
im[v * size + u] = a * Gaussian(random);
}
}
re[0] = im[0] = 0;
Fourier.Inverse2D(re, im, size, size);
double mean = 0, sq = 0;
foreach (var x in re) mean += x;
mean /= re.Length;
foreach (var x in re) sq += (x - mean) * (x - mean);
var scale = 0.15 / double.Sqrt(sq / re.Length);
for (var i = 0; i < re.Length; i++) re[i] = 0.5 + (re[i] - mean) * scale;
return re;
}
private static double Gaussian(Random random)
{
var u1 = 1.0 - random.NextDouble();
var u2 = random.NextDouble();
return double.Sqrt(-2 * double.Log(u1)) * double.Cos(2 * double.Pi * u2);
}
private static int Signed(int index, int length) => index <= length / 2 ? index : index - length;
}