merge: motion and geometry modules
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
30 files changed
+5003
No files matched your search
@@ -0,0 +1,56 @@
|
||||
using Titano.Core.Imaging.Geometry;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Geometry;
|
||||
|
||||
public sealed class Affine2DTests
|
||||
{
|
||||
[Test]
|
||||
public void CompositionAppliesInnerFirst()
|
||||
{
|
||||
var scale = Affine2D.Scaling(2, 3);
|
||||
var move = Affine2D.Translation(5, -1);
|
||||
var (x, y) = (move * scale).Apply(1, 1);
|
||||
Assert.Approximately(7, x, 1e-15);
|
||||
Assert.Approximately(2, y, 1e-15);
|
||||
Assert.Equal(move * scale, scale.Then(move));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InverseUndoesTheMap()
|
||||
{
|
||||
var map = Affine2D.Similarity(1.3, 0.4, 12, -7) * Affine2D.Scaling(1, 0.8);
|
||||
var inverse = map.Invert();
|
||||
Assert.True((inverse * map).IsIdentity(1e-12));
|
||||
Assert.True((map * inverse).IsIdentity(1e-12));
|
||||
var (x, y) = map.Apply(3.5, -2.25);
|
||||
var (bx, by) = inverse.Apply(x, y);
|
||||
Assert.Within(3.5, -2.25, bx, by, 1e-12);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SingularMapsDoNotInvert()
|
||||
{
|
||||
Assert.False(new Affine2D(1, 2, 2, 4, 0, 0).TryInvert(out _));
|
||||
Assert.Throws<InvalidOperationException>(() => Affine2D.Scaling(0, 1).Invert());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RotationAboutPivotKeepsThePivot()
|
||||
{
|
||||
var map = Affine2D.About(Affine2D.Rotation(0.7), 40, 30);
|
||||
var (x, y) = map.Apply(40, 30);
|
||||
Assert.Within(40, 30, x, y, 1e-12);
|
||||
var (vx, vy) = map.ApplyVector(1, 0);
|
||||
Assert.Within(double.Cos(0.7), double.Sin(0.7), vx, vy, 1e-15);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SimilarityDecomposes()
|
||||
{
|
||||
var map = Affine2D.Similarity(1.25, -0.3, 4, 5);
|
||||
Assert.Approximately(1.25, map.Scale, 1e-12);
|
||||
Assert.Approximately(-0.3, map.Angle, 1e-12);
|
||||
Assert.Approximately(1.25 * 1.25, map.Determinant, 1e-12);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using Titano.Core.Imaging.Geometry;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Geometry;
|
||||
|
||||
public sealed class AspectRatioTests
|
||||
{
|
||||
[Theory]
|
||||
[Case(1920.0, 1080.0, 1, 1, 420.0, 0.0, 1080.0, 1080.0)]
|
||||
[Case(1920.0, 1080.0, 9, 16, 656.25, 0.0, 607.5, 1080.0)]
|
||||
[Case(4000.0, 3000.0, 16, 9, 0.0, 375.0, 4000.0, 2250.0)]
|
||||
[Case(6000.0, 4000.0, 3, 2, 0.0, 0.0, 6000.0, 4000.0)]
|
||||
[Case(1080.0, 1920.0, 4, 5, 0.0, 285.0, 1080.0, 1350.0)]
|
||||
[Case(3840.0, 2160.0, 21, 9, 0.0, 257.142857142857, 3840.0, 1645.71428571429)]
|
||||
public void FitCropCentresTheLargestCrop(double bw, double bh, int w, int h, double x, double y, double cw, double ch)
|
||||
{
|
||||
var crop = AspectRatio.FitCrop(RectD.FromSize(bw, bh), AspectRatio.Custom(w, h).Resolve(bw, bh));
|
||||
Assert.Approximately(x, crop.X, 1e-9);
|
||||
Assert.Approximately(y, crop.Y, 1e-9);
|
||||
Assert.Approximately(cw, crop.Width, 1e-9);
|
||||
Assert.Approximately(ch, crop.Height, 1e-9);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(-1.0, 100.0)]
|
||||
[Case(0.0, 280.0)]
|
||||
[Case(1.0, 460.0)]
|
||||
[Case(5.0, 460.0)]
|
||||
[Case(-0.5, 190.0)]
|
||||
public void FitCropOffsetMovesWithinTheSlack(double offset, double expectedX)
|
||||
{
|
||||
var crop = AspectRatio.FitCrop(new RectD(100, 50, 720, 360), 1.0, offset, offset);
|
||||
Assert.Approximately(expectedX, crop.X, 1e-9);
|
||||
Assert.Approximately(50, crop.Y, 1e-9);
|
||||
Assert.Approximately(360, crop.Width, 1e-9);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PresetsAndParsing()
|
||||
{
|
||||
Assert.Equal(AspectRatio.Widescreen, AspectRatio.Custom(32, 18));
|
||||
Assert.Equal("16:9", AspectRatio.Widescreen.ToString());
|
||||
Assert.Equal("9:16", AspectRatio.Vertical.ToString());
|
||||
Assert.Equal(8, AspectRatio.Presets.Count);
|
||||
Assert.Approximately(1.5, AspectRatio.Source.Resolve(6000, 4000), 1e-15);
|
||||
Assert.Approximately(21.0 / 9, AspectRatio.Cinema.Resolve(6000, 4000), 1e-15);
|
||||
Assert.True(AspectRatio.TryParse("4/5", out var portrait));
|
||||
Assert.Equal(AspectRatio.Portrait, portrait);
|
||||
Assert.True(AspectRatio.TryParse("source", out var source));
|
||||
Assert.True(source.IsSource);
|
||||
Assert.False(AspectRatio.TryParse("16:0", out _));
|
||||
Assert.False(AspectRatio.TryParse("wide", out _));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Imaging.Geometry;
|
||||
using Titano.Core.Tests.Motion;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Geometry;
|
||||
|
||||
public sealed class GeometryStageTests
|
||||
{
|
||||
private const int Size = 128;
|
||||
|
||||
private readonly TestContext _context;
|
||||
|
||||
public GeometryStageTests(TestContext context) => _context = context;
|
||||
|
||||
[Test]
|
||||
public void IdentityWarpReproducesTheImage()
|
||||
{
|
||||
using var source = Texture(sigma: 1.0);
|
||||
using var output = GeometryStage.Apply(source, new GeometrySettings());
|
||||
Assert.Equal(Size, output.Width);
|
||||
Assert.Equal(3, output.Channels);
|
||||
var psnr = SyntheticImages.Psnr(source.Plane(1), output.Plane(1), Size, 0, 0, Size, Size);
|
||||
_context.Log($"identity PSNR {psnr:F1} dB");
|
||||
Assert.GreaterOrEqual(psnr, 60);
|
||||
Assert.True(source.Data.SequenceEqual(output.Data));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HalfPixelShiftAndBackStaysWithinBounds()
|
||||
{
|
||||
using var source = Texture(sigma: 2.0);
|
||||
using var shifted = new ImageBuffer(Size, Size);
|
||||
using var back = new ImageBuffer(Size, Size);
|
||||
GeometryStage.Warp(source, shifted, Affine2D.Translation(0.5, 0.5));
|
||||
GeometryStage.Warp(shifted, back, Affine2D.Translation(-0.5, -0.5));
|
||||
var psnr = SyntheticImages.Psnr(source.Plane(0), back.Plane(0), Size, 4, 4, Size - 4, Size - 4);
|
||||
_context.Log($"0.5 px round trip PSNR {psnr:F1} dB");
|
||||
Assert.GreaterOrEqual(psnr, 40);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LinearRampsAreReproducedUnderSubPixelWarps()
|
||||
{
|
||||
using var ramp = new ImageBuffer(64, 64, 1);
|
||||
for (var y = 0; y < 64; y++)
|
||||
for (var x = 0; x < 64; x++)
|
||||
ramp[0, x, y] = 0.01f * x + 0.005f * y;
|
||||
using var output = new ImageBuffer(64, 64, 1);
|
||||
var map = Affine2D.About(Affine2D.Similarity(0.8, 0.2, 0, 0), 32, 32);
|
||||
GeometryStage.Warp(ramp, output, map);
|
||||
for (var y = 8; y < 56; y++)
|
||||
{
|
||||
for (var x = 8; x < 56; x++)
|
||||
{
|
||||
var (sx, sy) = map.Apply(x, y);
|
||||
Assert.Approximately(0.01 * sx + 0.005 * sy, output[0, x, y], 2e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TransparentBordersCarryCoverage()
|
||||
{
|
||||
using var source = Texture(sigma: 1.0);
|
||||
using var output = GeometryStage.Apply(source, new GeometrySettings
|
||||
{
|
||||
Warp = Affine2D.Translation(-10, 0),
|
||||
Border = BorderMode.Transparent,
|
||||
});
|
||||
Assert.Equal(4, output.Channels);
|
||||
for (var y = 0; y < Size; y += 7)
|
||||
{
|
||||
Assert.Equal(0f, output[3, 3, y]);
|
||||
Assert.Equal(0f, output[0, 3, y]);
|
||||
Assert.Equal(1f, output[3, 40, y]);
|
||||
Assert.Equal(source[1, 30, y], output[1, 40, y]);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ClampReplicatesEdges()
|
||||
{
|
||||
using var source = Texture(sigma: 1.0);
|
||||
using var output = GeometryStage.Apply(source, new GeometrySettings { Warp = Affine2D.Translation(-10, 0) });
|
||||
for (var y = 0; y < Size; y += 5) Assert.Approximately(source[2, 0, y], output[2, 2, y], 1e-6);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PlanFitsAspectAndMapsPixelCentres()
|
||||
{
|
||||
var plan = GeometryStage.Plan(1920, 1080, new GeometrySettings { Aspect = AspectRatio.Square, OutputWidth = 540 });
|
||||
Assert.Equal(540, plan.OutputWidth);
|
||||
Assert.Equal(540, plan.OutputHeight);
|
||||
Assert.Equal(new RectD(420, 0, 1080, 1080), plan.Crop);
|
||||
var (x, y) = plan.OutputToSource.Apply(0, 0);
|
||||
Assert.Within(420.5, 0.5, x, y, 1e-12);
|
||||
|
||||
var cropped = GeometryStage.Plan(800, 600, new GeometrySettings { Crop = new RectD(100, 50, 200, 100), OutputWidth = 400, OutputHeight = 200 });
|
||||
Assert.Equal(new RectD(100, 50, 200, 100), cropped.Crop);
|
||||
var (cx, cy) = cropped.OutputToSource.Apply(0, 0);
|
||||
Assert.Within(99.75, 49.75, cx, cy, 1e-12);
|
||||
|
||||
var vertical = GeometryStage.Plan(1920, 1080, new GeometrySettings { Aspect = AspectRatio.Vertical, OutputHeight = 1920 });
|
||||
Assert.Equal(1080, vertical.OutputWidth);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DownscalingDoesNotAlias()
|
||||
{
|
||||
using var checker = new ImageBuffer(256, 256, 1);
|
||||
for (var y = 0; y < 256; y++)
|
||||
for (var x = 0; x < 256; x++)
|
||||
checker[0, x, y] = (x + y) % 2 == 0 ? 1f : 0f;
|
||||
using var small = GeometryStage.Apply(checker, new GeometrySettings { OutputWidth = 64 });
|
||||
Assert.Equal(64, small.Height);
|
||||
for (var y = 2; y < 62; y++)
|
||||
for (var x = 2; x < 62; x++)
|
||||
Assert.Approximately(0.5, small[0, x, y], 0.02);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CancellationStopsTheWarp()
|
||||
{
|
||||
using var source = Texture(sigma: 1.0);
|
||||
using var cts = new CancellationTokenSource();
|
||||
cts.Cancel();
|
||||
Assert.Throws<OperationCanceledException>(() => GeometryStage.Apply(source, new GeometrySettings(), cts.Token));
|
||||
}
|
||||
|
||||
private static ImageBuffer Texture(double sigma) =>
|
||||
SyntheticImages.ToRgb(SyntheticImages.Crop(SyntheticImages.Noise(Size, sigma, seed: 21), Size, 0, 0, Size, Size), Size, Size);
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
using Titano.Core.Motion;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Motion;
|
||||
|
||||
public sealed class FourierTests
|
||||
{
|
||||
private readonly TestContext _context;
|
||||
|
||||
public FourierTests(TestContext context) => _context = context;
|
||||
|
||||
[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);
|
||||
var error = MaxError(r0, i0, re, im);
|
||||
_context.Log($"n = {n}: round-trip max error {error:E2}");
|
||||
Assert.LessOrEqual(error, 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 error = MaxError(er, ei, re, im) / double.Sqrt(n);
|
||||
_context.Log($"n = {n}: Bluestein vs direct DFT, max error / √n {error:E2}");
|
||||
Assert.LessOrEqual(error, 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,119 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Motion;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Motion;
|
||||
|
||||
public sealed class FrameInterpolatorTests
|
||||
{
|
||||
private const int Base = 256;
|
||||
private const int Frame = 160;
|
||||
private const int Margin = 16;
|
||||
|
||||
private readonly TestContext _context;
|
||||
|
||||
public FrameInterpolatorTests(TestContext context) => _context = context;
|
||||
|
||||
[Test]
|
||||
public void EndpointsReproduceTheKeyFrames()
|
||||
{
|
||||
var texture = SyntheticImages.Natural(Base, seed: 13);
|
||||
using var a = Shifted(texture, 0, 0);
|
||||
using var b = Shifted(texture, 3, -1.5);
|
||||
using var interpolator = new FrameInterpolator(FlowQuality.Balanced);
|
||||
using var output = new ImageBuffer(Frame, Frame);
|
||||
interpolator.Interpolate(a, b, 0, output);
|
||||
Assert.True(a.Data.SequenceEqual(output.Data));
|
||||
interpolator.Interpolate(a, b, 1, output);
|
||||
Assert.True(b.Data.SequenceEqual(output.Data));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(0.5)]
|
||||
[Case(0.25)]
|
||||
public void TranslationIsInterpolatedAlongTheMotion(double t)
|
||||
{
|
||||
const double dx = 4, dy = -2;
|
||||
var texture = SyntheticImages.Natural(Base, seed: 13);
|
||||
using var a = Shifted(texture, 0, 0);
|
||||
using var b = Shifted(texture, dx, dy);
|
||||
using var truth = Shifted(texture, t * dx, t * dy);
|
||||
using var interpolator = new FrameInterpolator();
|
||||
using var output = new ImageBuffer(Frame, Frame);
|
||||
interpolator.Interpolate(a, b, t, output);
|
||||
var psnr = SyntheticImages.Psnr(truth.Plane(1), output.Plane(1), Frame, Margin, Margin, Frame - Margin, Frame - Margin);
|
||||
|
||||
using var fade = new ImageBuffer(Frame, Frame);
|
||||
for (var i = 0; i < fade.Data.Length; i++) fade.Data[i] = (float)((1 - t) * a.Data[i] + t * b.Data[i]);
|
||||
var fadePsnr = SyntheticImages.Psnr(truth.Plane(1), fade.Plane(1), Frame, Margin, Margin, Frame - Margin, Frame - Margin);
|
||||
_context.Log($"t = {t}: interpolated {psnr:F1} dB, cross-fade {fadePsnr:F1} dB");
|
||||
Assert.GreaterOrEqual(psnr, 35);
|
||||
Assert.Greater(psnr, fadePsnr + 10);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OcclusionReasoningPicksTheVisibleFrame()
|
||||
{
|
||||
// Exact flows: the square moves 12 px right; at t = 0.5 a 6 px strip behind it is visible only in B
|
||||
// and the strip ahead of it shows the square, which must be fetched along the square's motion.
|
||||
var background = SyntheticImages.Natural(Base, seed: 3);
|
||||
var foreground = SyntheticImages.Noise(Base, 1.2, seed: 4);
|
||||
using var a = Composite(background, foreground, 50);
|
||||
using var b = Composite(background, foreground, 62);
|
||||
using var truth = Composite(background, foreground, 56);
|
||||
using var forward = new MotionField(Frame, Frame, 1);
|
||||
using var backward = new MotionField(Frame, Frame, 1);
|
||||
for (var y = 50; y < 98; y++)
|
||||
{
|
||||
forward.U.Slice(y * Frame + 50, 48).Fill(12);
|
||||
backward.U.Slice(y * Frame + 62, 48).Fill(-12);
|
||||
}
|
||||
using var handled = new ImageBuffer(Frame, Frame);
|
||||
using var unweighted = new ImageBuffer(Frame, Frame);
|
||||
FrameInterpolator.Synthesize(a, b, forward, backward, 0.5, handled);
|
||||
FrameInterpolator.Synthesize(a, b, forward, backward, 0.5, unweighted, occlusionThreshold: 1e9);
|
||||
// Rows through the object, columns around its trailing and leading edges.
|
||||
var withWeights = SyntheticImages.Psnr(truth.Plane(1), handled.Plane(1), Frame, 36, 50, 124, 98);
|
||||
var without = SyntheticImages.Psnr(truth.Plane(1), unweighted.Plane(1), Frame, 36, 50, 124, 98);
|
||||
_context.Log($"exact flows, object region: occlusion-aware {withWeights:F1} dB, without sample weighting {without:F1} dB");
|
||||
Assert.GreaterOrEqual(withWeights, 42);
|
||||
Assert.Greater(withWeights, without + 10);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MovingObjectIsInterpolatedWithEstimatedFlow()
|
||||
{
|
||||
var background = SyntheticImages.Natural(Base, seed: 3);
|
||||
var foreground = SyntheticImages.Noise(Base, 1.2, seed: 4);
|
||||
using var a = Composite(background, foreground, 50);
|
||||
using var b = Composite(background, foreground, 62);
|
||||
using var truth = Composite(background, foreground, 56);
|
||||
using var interpolator = new FrameInterpolator();
|
||||
using var output = new ImageBuffer(Frame, Frame);
|
||||
interpolator.Interpolate(a, b, 0.5, output);
|
||||
using var fade = new ImageBuffer(Frame, Frame);
|
||||
for (var i = 0; i < fade.Data.Length; i++) fade.Data[i] = 0.5f * (a.Data[i] + b.Data[i]);
|
||||
var psnr = SyntheticImages.Psnr(truth.Plane(1), output.Plane(1), Frame, 36, 50, 124, 98);
|
||||
var fadePsnr = SyntheticImages.Psnr(truth.Plane(1), fade.Plane(1), Frame, 36, 50, 124, 98);
|
||||
_context.Log($"estimated flows, object region: {psnr:F1} dB, cross-fade {fadePsnr:F1} dB");
|
||||
Assert.GreaterOrEqual(psnr, 33);
|
||||
Assert.Greater(psnr, fadePsnr + 5);
|
||||
}
|
||||
|
||||
private static ImageBuffer Shifted(double[] texture, double dx, double dy)
|
||||
{
|
||||
var shifted = dx == 0 && dy == 0 ? texture : SyntheticImages.Shift(texture, Base, dx, dy);
|
||||
return SyntheticImages.ToRgb(SyntheticImages.Crop(shifted, Base, 48, 48, Frame, Frame), Frame, Frame);
|
||||
}
|
||||
|
||||
/// <summary>Static background with a 48×48 textured square whose left edge is at <paramref name="x0"/>; the square carries its texture along.</summary>
|
||||
private static ImageBuffer Composite(double[] background, double[] foreground, int x0)
|
||||
{
|
||||
var plane = SyntheticImages.Crop(background, Base, 0, 0, Frame, Frame);
|
||||
for (var y = 50; y < 98; y++)
|
||||
{
|
||||
for (var x = 0; x < 48; x++) plane[y * Frame + x0 + x] = (float)(0.3 + 0.8 * (foreground[y * Base + x] - 0.5));
|
||||
}
|
||||
return SyntheticImages.ToRgb(plane, Frame, Frame);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Motion;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Motion;
|
||||
|
||||
public sealed class MotionBlurTests
|
||||
{
|
||||
private const int Size = 128;
|
||||
|
||||
private readonly TestContext _context;
|
||||
|
||||
public MotionBlurTests(TestContext context) => _context = context;
|
||||
|
||||
[Theory]
|
||||
[Case(180.0, 90.0, 0.4330127018922193)]
|
||||
[Case(180.0, 0.0, 0.5)]
|
||||
[Case(360.0, 0.0, 1.0)]
|
||||
[Case(180.0, 180.0, 0.0)]
|
||||
[Case(180.0, 270.0, 0.0)]
|
||||
[Case(90.0, 54.0, 0.2)]
|
||||
public void BlurFractionComposesShutterAngles(double target, double real, double expected) =>
|
||||
Assert.Approximately(expected, ShutterAngle.BlurFraction(target, real), 1e-12);
|
||||
|
||||
[Test]
|
||||
public void RealShutterAngleFromExposure()
|
||||
{
|
||||
Assert.Approximately(180, ShutterAngle.FromExposure(1, 2), 1e-12);
|
||||
Assert.Approximately(3.6, ShutterAngle.FromExposure(1 / 250.0, 0.4), 1e-12);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ZeroVectorsLeaveTheImageIdentical()
|
||||
{
|
||||
using var source = Texture();
|
||||
using var motion = new MotionField(Size, Size, 2);
|
||||
using var output = new ImageBuffer(Size, Size);
|
||||
new MotionBlurRenderer().Render(source, motion, 0.5, output);
|
||||
Assert.True(source.Data.SequenceEqual(output.Data));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PointBlursIntoASegmentWithItsEnergy()
|
||||
{
|
||||
using var source = new ImageBuffer(Size, Size, 1);
|
||||
source[0, 64, 64] = 1f;
|
||||
using var motion = new MotionField(Size, Size, 4);
|
||||
motion.Fill(20, 0);
|
||||
using var output = new ImageBuffer(Size, Size, 1);
|
||||
new MotionBlurRenderer().Render(source, motion, 0.5, output);
|
||||
|
||||
double total = 0;
|
||||
var columns = new HashSet<int>();
|
||||
for (var y = 0; y < Size; y++)
|
||||
{
|
||||
for (var x = 0; x < Size; x++)
|
||||
{
|
||||
var value = output[0, x, y];
|
||||
total += value;
|
||||
if (value <= 1e-6f) continue;
|
||||
Assert.Equal(64, y);
|
||||
columns.Add(x);
|
||||
}
|
||||
}
|
||||
_context.Log($"point energy after blur {total:F6}, segment columns {columns.Min()}..{columns.Max()}");
|
||||
Assert.Approximately(1, total, 1e-4);
|
||||
Assert.InRange(columns.Min(), 58, 60);
|
||||
Assert.InRange(columns.Max(), 68, 70);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EnergyIsPreservedOnTexture()
|
||||
{
|
||||
using var source = Texture();
|
||||
using var motion = new MotionField(Size, Size, 2);
|
||||
for (var j = 0; j < motion.Rows; j++)
|
||||
for (var i = 0; i < motion.Columns; i++)
|
||||
{
|
||||
// A smooth swirl: magnitude up to ~6 px.
|
||||
var k = j * motion.Columns + i;
|
||||
motion.U[k] = (float)(6 * double.Sin(j * 0.1));
|
||||
motion.V[k] = (float)(4 * double.Cos(i * 0.08));
|
||||
}
|
||||
using var output = new ImageBuffer(Size, Size);
|
||||
new MotionBlurRenderer().Render(source, motion, 1.0, output);
|
||||
for (var c = 0; c < 3; c++)
|
||||
{
|
||||
var before = Mean(source.Plane(c), 16);
|
||||
var after = Mean(output.Plane(c), 16);
|
||||
_context.Log($"channel {c}: mean {before:F6} → {after:F6} ({(after - before) / before:P3})");
|
||||
Assert.Approximately(before, after, 2e-3 * before);
|
||||
}
|
||||
Assert.False(source.Data.SequenceEqual(output.Data));
|
||||
}
|
||||
|
||||
private static double Mean(ReadOnlySpan<float> plane, int margin)
|
||||
{
|
||||
double sum = 0;
|
||||
var n = 0;
|
||||
for (var y = margin; y < Size - margin; y++)
|
||||
for (var x = margin; x < Size - margin; x++)
|
||||
{
|
||||
sum += plane[y * Size + x];
|
||||
n++;
|
||||
}
|
||||
return sum / n;
|
||||
}
|
||||
|
||||
private static ImageBuffer Texture() =>
|
||||
SyntheticImages.ToRgb(SyntheticImages.Crop(SyntheticImages.Natural(Size, seed: 31), Size, 0, 0, Size, Size), Size, Size);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Imaging.Geometry;
|
||||
using Titano.Core.Motion;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Motion;
|
||||
|
||||
public sealed class OpticalFlowTests
|
||||
{
|
||||
private const int Base = 256;
|
||||
private const int Frame = 192;
|
||||
private const int Margin = 16;
|
||||
|
||||
private readonly TestContext _context;
|
||||
|
||||
public OpticalFlowTests(TestContext context) => _context = context;
|
||||
|
||||
[Theory]
|
||||
[Case(FlowQuality.Draft)]
|
||||
[Case(FlowQuality.Balanced)]
|
||||
[Case(FlowQuality.Best)]
|
||||
public void TranslationEndPointErrorBelowAThirdOfAPixel(FlowQuality quality)
|
||||
{
|
||||
const double dx = 2.3, dy = -1.7;
|
||||
var texture = SyntheticImages.Natural(Base, seed: 11);
|
||||
using var a = SyntheticImages.ToRgb(SyntheticImages.Crop(texture, Base, 32, 32, Frame, Frame), Frame, Frame);
|
||||
using var b = SyntheticImages.ToRgb(SyntheticImages.Crop(SyntheticImages.Shift(texture, Base, dx, dy), Base, 32, 32, Frame, Frame), Frame, Frame);
|
||||
using var engine = new OpticalFlowEngine(quality);
|
||||
using var field = engine.Compute(a, b);
|
||||
var epe = MeanEndPointError(field, (_, _) => (dx, dy));
|
||||
_context.Log($"{quality}: step {field.Step}, mean EPE {epe:F4} px");
|
||||
Assert.Less(epe, 0.3);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RotationEndPointErrorBelowOnePixel()
|
||||
{
|
||||
var angle = 3.0 * double.Pi / 180;
|
||||
var texture = SyntheticImages.Natural(Base, seed: 5);
|
||||
using var baseImage = SyntheticImages.ToRgb(SyntheticImages.Crop(texture, Base, 0, 0, Base, Base), Base, Base);
|
||||
using var rotated = new ImageBuffer(Base, Base);
|
||||
const double c = (Base - 1) / 2.0;
|
||||
// rotated(x) = base(R⁻¹(x − c) + c): content turns by +angle about the centre.
|
||||
GeometryStage.Warp(baseImage, rotated, Affine2D.About(Affine2D.Rotation(-angle), c, c));
|
||||
using var a = Crop(baseImage, 32);
|
||||
using var b = Crop(rotated, 32);
|
||||
using var engine = new OpticalFlowEngine(FlowQuality.Best);
|
||||
using var field = engine.Compute(a, b);
|
||||
var truth = Affine2D.About(Affine2D.Rotation(angle), c - 32, c - 32);
|
||||
var epe = MeanEndPointError(field, (x, y) =>
|
||||
{
|
||||
var (tx, ty) = truth.Apply(x, y);
|
||||
return (tx - x, ty - y);
|
||||
});
|
||||
_context.Log($"rotation 3°: mean EPE {epe:F4} px");
|
||||
Assert.Less(epe, 1.0);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ForwardBackwardErrorIsSmallForConsistentMotion()
|
||||
{
|
||||
var texture = SyntheticImages.Natural(Base, seed: 2);
|
||||
using var a = SyntheticImages.ToRgb(SyntheticImages.Crop(texture, Base, 32, 32, Frame, Frame), Frame, Frame);
|
||||
using var b = SyntheticImages.ToRgb(SyntheticImages.Crop(SyntheticImages.Shift(texture, Base, -1.5, 0.75), Base, 32, 32, Frame, Frame), Frame, Frame);
|
||||
using var engine = new OpticalFlowEngine(FlowQuality.Balanced);
|
||||
var (forward, backward) = engine.ComputeBidirectional(a, b);
|
||||
using (forward)
|
||||
using (backward)
|
||||
{
|
||||
Assert.True(forward.HasConsistency);
|
||||
var stats = forward.Statistics(reliableError: 0.5);
|
||||
_context.Log($"reliable {stats.ReliableFraction:P1}, mean |w| {stats.MeanMagnitude:F3}");
|
||||
Assert.Greater(stats.ReliableFraction, 0.85);
|
||||
Assert.Approximately(1.677, stats.MedianMagnitude, 0.1);
|
||||
Assert.Less(forward.SampleError(96, 96), 0.2);
|
||||
var (bu, bv) = backward.Sample(96, 96);
|
||||
Assert.Within(1.5, -0.75, bu, bv, 0.2);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FieldSamplingHistogramAndStatistics()
|
||||
{
|
||||
using var field = new MotionField(9, 5, 4);
|
||||
Assert.Equal(3, field.Columns);
|
||||
Assert.Equal(2, field.Rows);
|
||||
for (var j = 0; j < field.Rows; j++)
|
||||
for (var i = 0; i < field.Columns; i++)
|
||||
{
|
||||
field.U[j * field.Columns + i] = i;
|
||||
field.V[j * field.Columns + i] = 2 * j;
|
||||
}
|
||||
var (u, v) = field.Sample(6, 2);
|
||||
Assert.Approximately(1.5, u, 1e-6);
|
||||
Assert.Approximately(1, v, 1e-6);
|
||||
Assert.True(float.IsNaN(field.SampleError(0, 0)));
|
||||
|
||||
field.Fill(3, 4);
|
||||
var histogram = field.MagnitudeHistogram(10, 10);
|
||||
Assert.Equal(6, histogram[5]);
|
||||
Assert.Equal(6, field.MagnitudeHistogram(4, 2)[3]);
|
||||
var stats = field.Statistics();
|
||||
Assert.Approximately(5, stats.MeanMagnitude, 1e-6);
|
||||
Assert.Approximately(5, stats.P95Magnitude, 1e-6);
|
||||
Assert.Approximately(3, stats.MeanU, 1e-6);
|
||||
Assert.Equal(1.0, stats.ReliableFraction);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PyramidLevelsHalveAndPreserveMean()
|
||||
{
|
||||
var texture = SyntheticImages.Crop(SyntheticImages.Noise(Base, 1.5, seed: 8), Base, 0, 0, 101, 75);
|
||||
using var pyramid = new GrayPyramid(101, 75, GrayPyramid.LevelsFor(101, 75));
|
||||
Assert.Equal(3, pyramid.Levels);
|
||||
pyramid.Build(texture);
|
||||
Assert.Equal(51, pyramid.LevelWidth(1));
|
||||
Assert.Equal(38, pyramid.LevelHeight(1));
|
||||
Assert.Equal(26, pyramid.LevelWidth(2));
|
||||
var mean0 = pyramid.Level(0).ToArray().Average();
|
||||
var mean2 = pyramid.Level(2).ToArray().Average();
|
||||
Assert.Approximately(mean0, mean2, 0.02);
|
||||
|
||||
var flat = new float[64 * 64];
|
||||
flat.AsSpan().Fill(0.25f);
|
||||
using var constant = new GrayPyramid(64, 64, 3);
|
||||
constant.Build(flat);
|
||||
Assert.True(constant.Level(2).ToArray().All(x => x == 0.25f));
|
||||
}
|
||||
|
||||
private static double MeanEndPointError(MotionField field, Func<double, double, (double U, double V)> truth)
|
||||
{
|
||||
double sum = 0;
|
||||
var n = 0;
|
||||
for (var j = 0; j < field.Rows; j++)
|
||||
{
|
||||
for (var i = 0; i < field.Columns; i++)
|
||||
{
|
||||
double x = i * field.Step, y = j * field.Step;
|
||||
if (x < Margin || y < Margin || x >= Frame - Margin || y >= Frame - Margin) continue;
|
||||
var (tu, tv) = truth(x, y);
|
||||
var k = j * field.Columns + i;
|
||||
sum += double.Hypot(field.U[k] - tu, field.V[k] - tv);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
return sum / n;
|
||||
}
|
||||
|
||||
private static ImageBuffer Crop(ImageBuffer source, int offset)
|
||||
{
|
||||
var crop = new ImageBuffer(Frame, Frame);
|
||||
GeometryStage.Warp(source, crop, Affine2D.Translation(offset, offset));
|
||||
return crop;
|
||||
}
|
||||
}
|
||||
@@ -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,97 @@
|
||||
using Titano.Core.Motion;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Motion;
|
||||
|
||||
public sealed class PlaneOpsTests
|
||||
{
|
||||
private const int Width = 37;
|
||||
private const int Height = 23;
|
||||
|
||||
[Theory]
|
||||
[Case(1)]
|
||||
[Case(2)]
|
||||
public void MedianFilterMatchesBruteForce(int radius)
|
||||
{
|
||||
var source = RandomPlane(seed: radius);
|
||||
var output = new float[source.Length];
|
||||
PlaneOps.MedianFilter(source, output, Width, Height, radius);
|
||||
for (var y = 0; y < Height; y++)
|
||||
{
|
||||
for (var x = 0; x < Width; x++)
|
||||
{
|
||||
var window = new List<float>();
|
||||
for (var dy = -radius; dy <= radius; dy++)
|
||||
for (var dx = -radius; dx <= radius; dx++)
|
||||
window.Add(source[int.Clamp(y + dy, 0, Height - 1) * Width + int.Clamp(x + dx, 0, Width - 1)]);
|
||||
window.Sort();
|
||||
Assert.Equal(window[window.Count / 2], output[y * Width + x]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(1)]
|
||||
[Case(3)]
|
||||
public void BoxFilterMatchesBruteForce(int radius)
|
||||
{
|
||||
var source = RandomPlane(seed: 10 + radius);
|
||||
var output = new float[source.Length];
|
||||
PlaneOps.BoxFilter(source, output, new float[source.Length], Width, Height, radius);
|
||||
for (var y = 0; y < Height; y++)
|
||||
{
|
||||
for (var x = 0; x < Width; x++)
|
||||
{
|
||||
double sum = 0;
|
||||
for (var dy = -radius; dy <= radius; dy++)
|
||||
for (var dx = -radius; dx <= radius; dx++)
|
||||
sum += source[int.Clamp(y + dy, 0, Height - 1) * Width + int.Clamp(x + dx, 0, Width - 1)];
|
||||
Assert.Approximately(sum / ((2 * radius + 1) * (2 * radius + 1)), output[y * Width + x], 1e-5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BinomialBlurKeepsConstantsAndMean()
|
||||
{
|
||||
var flat = new float[Width * Height];
|
||||
flat.AsSpan().Fill(0.7f);
|
||||
PlaneOps.Binomial5(flat, flat, new float[flat.Length], Width, Height);
|
||||
Assert.True(flat.All(v => double.Abs(v - 0.7) < 1e-6));
|
||||
|
||||
var impulse = new float[Width * Height];
|
||||
impulse[11 * Width + 17] = 1;
|
||||
var blurred = new float[impulse.Length];
|
||||
PlaneOps.Binomial5(impulse, blurred, new float[impulse.Length], Width, Height);
|
||||
Assert.Approximately(1, blurred.Sum(v => (double)v), 1e-6);
|
||||
Assert.Approximately(36.0 / 256, blurred[11 * Width + 17], 1e-7);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SelectionAndMedian()
|
||||
{
|
||||
var values = new float[] { 5, 1, 4, 2, 3 };
|
||||
Assert.Equal(3f, PlaneOps.Median(values));
|
||||
Assert.Equal(2.5f, PlaneOps.Median(new float[] { 4, 1, 3, 2 }));
|
||||
Assert.Equal(1f, PlaneOps.Select(new float[] { 3, 1, 2 }, 0));
|
||||
Assert.Equal(7f, PlaneOps.Median(new float[] { 7 }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BilinearIsExactAtPixelCentresAndClamps()
|
||||
{
|
||||
var plane = RandomPlane(seed: 3);
|
||||
Assert.Equal(plane[5 * Width + 9], PlaneOps.Bilinear(plane, Width, Height, 9, 5));
|
||||
Assert.Equal(plane[0], PlaneOps.Bilinear(plane, Width, Height, -3, -8));
|
||||
var mid = 0.5f * (plane[5 * Width + 9] + plane[5 * Width + 10]);
|
||||
Assert.Approximately(mid, PlaneOps.Bilinear(plane, Width, Height, 9.5f, 5), 1e-6);
|
||||
}
|
||||
|
||||
private static float[] RandomPlane(int seed)
|
||||
{
|
||||
var random = new Random(seed);
|
||||
var plane = new float[Width * Height];
|
||||
for (var i = 0; i < plane.Length; i++) plane[i] = (float)random.NextDouble();
|
||||
return plane;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Imaging.Geometry;
|
||||
using Titano.Core.Motion;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Motion;
|
||||
|
||||
public sealed class StabilizerTests
|
||||
{
|
||||
private const int Width = 256;
|
||||
private const int Height = 192;
|
||||
private const int Frames = 48;
|
||||
|
||||
private readonly TestContext _context;
|
||||
|
||||
public StabilizerTests(TestContext context) => _context = context;
|
||||
|
||||
[Test]
|
||||
public void TexturelessFramesReportNoShakeAndNoCorrection()
|
||||
{
|
||||
var random = new Random(17);
|
||||
using var stabilizer = new Stabilizer(128, 128);
|
||||
using var frame = new ImageBuffer(128, 128);
|
||||
for (var k = 0; k < 20; k++)
|
||||
{
|
||||
var data = frame.Data;
|
||||
for (var i = 0; i < data.Length; i++) data[i] = 0.3f + 0.004f * (float)Gaussian(random);
|
||||
Assert.False(stabilizer.AddFrame(frame).Estimated);
|
||||
}
|
||||
var result = stabilizer.Solve();
|
||||
_context.Log($"textureless shake {result.ShakeRms:F4} px, crop scale {result.CropScale:F4}");
|
||||
Assert.LessOrEqual(result.ShakeRms, 0.1);
|
||||
Assert.False(result.Recommended);
|
||||
Assert.Equal(1.0, result.CropScale);
|
||||
Assert.True(result.Corrections.All(c => c == Affine2D.Identity));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void JitterIsReducedByAtLeastEightyPercent()
|
||||
{
|
||||
var random = new Random(23);
|
||||
var cameras = new Affine2D[Frames];
|
||||
for (var k = 0; k < Frames; k++) cameras[k] = Camera(2.0 * Gaussian(random), 2.0 * Gaussian(random), 0.3 * Gaussian(random), pan: 0, k);
|
||||
var result = Stabilize(cameras, out var motionError);
|
||||
var before = Jitter(cameras, null);
|
||||
var after = Jitter(cameras, result.Corrections);
|
||||
var reduction = 1 - after / before;
|
||||
_context.Log($"frame-to-frame jitter {before:F3} → {after:F3} px ({reduction:P1}); motion error {motionError:F4} px; shake {result.ShakeRms:F3} px; crop cost {result.CropCost:P1}");
|
||||
Assert.GreaterOrEqual(reduction, 0.8);
|
||||
Assert.Less(motionError, 0.1);
|
||||
Assert.True(result.Recommended);
|
||||
Assert.Greater(result.ShakeRms, 1.0);
|
||||
Assert.InRange(result.CropCost, 0.01, 0.3);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IntentionalPanSurvivesStabilisation()
|
||||
{
|
||||
const double pan = 1.5;
|
||||
var random = new Random(29);
|
||||
var cameras = new Affine2D[Frames];
|
||||
for (var k = 0; k < Frames; k++) cameras[k] = Camera(1.5 * Gaussian(random), 1.5 * Gaussian(random), 0.2 * Gaussian(random), pan, k);
|
||||
var result = Stabilize(cameras, out _);
|
||||
|
||||
// The stabilised view still follows the pan: content drifts left by `pan` px per frame.
|
||||
var (bx, by) = cameras[0].Apply(Width / 2.0, Height / 2.0);
|
||||
(double X, double Y) Track(int k)
|
||||
{
|
||||
var (x, y) = cameras[k].Invert().Apply(bx, by);
|
||||
return result.Corrections[k].Apply(x, y);
|
||||
}
|
||||
var (sx, sy) = Track(0);
|
||||
var (ex, ey) = Track(Frames - 1);
|
||||
var velocity = (ex - sx) / (Frames - 1);
|
||||
_context.Log($"stabilised velocity {velocity:F3} px/frame (pan {-pan}), vertical drift {ey - sy:F3} px");
|
||||
Assert.Approximately(-pan, velocity, 0.1);
|
||||
var reduction = 1 - Jitter(cameras, result.Corrections, removeMean: true) / Jitter(cameras, null, removeMean: true);
|
||||
Assert.GreaterOrEqual(reduction, 0.8);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SmootherKeepsLinesAndEnds()
|
||||
{
|
||||
var line = Enumerable.Range(0, 30).Select(i => 3 + 0.5 * i).ToArray();
|
||||
var smoothed = PathSmoother.LocalLinear(line, 5);
|
||||
for (var i = 0; i < line.Length; i++) Assert.Approximately(line[i], smoothed[i], 1e-9);
|
||||
// Frame-rate jitter (alternating ±1) is removed in the interior and strongly attenuated at the ends.
|
||||
var noisy = Enumerable.Range(0, 200).Select(i => i % 2 == 0 ? 1.0 : -1.0).ToArray();
|
||||
var flat = PathSmoother.LocalLinear(noisy, 8);
|
||||
var interior = flat.Skip(24).SkipLast(24).Max(double.Abs);
|
||||
var ends = flat.Max(double.Abs);
|
||||
_context.Log($"interior {interior:E2}, ends {ends:E2}");
|
||||
Assert.Less(interior, 0.01);
|
||||
Assert.Less(ends, 0.2);
|
||||
}
|
||||
|
||||
/// <summary>Frame pixel → base-texture coordinate: jitter translation and rotation about the frame centre, plus a pan.</summary>
|
||||
private static Affine2D Camera(double tx, double ty, double degrees, double pan, int k) =>
|
||||
Affine2D.Translation(100 + pan * k, 150)
|
||||
* Affine2D.About(Affine2D.Rotation(degrees * double.Pi / 180), (Width - 1) / 2.0, (Height - 1) / 2.0)
|
||||
* Affine2D.Translation(tx, ty);
|
||||
|
||||
private static StabilizationResult Stabilize(Affine2D[] cameras, out double motionError)
|
||||
{
|
||||
const int Base = 512;
|
||||
using var texture = SyntheticImages.ToRgb(SyntheticImages.Crop(SyntheticImages.Natural(Base, seed: 41), Base, 0, 0, Base, Base), Base, Base);
|
||||
using var frame = new ImageBuffer(Width, Height);
|
||||
using var stabilizer = new Stabilizer(Width, Height);
|
||||
double error = 0;
|
||||
var samples = 0;
|
||||
for (var k = 0; k < cameras.Length; k++)
|
||||
{
|
||||
GeometryStage.Warp(texture, frame, cameras[k]);
|
||||
var motion = stabilizer.AddFrame(frame);
|
||||
if (k == 0) continue;
|
||||
// True inter-frame map: previous frame → base → current frame.
|
||||
var truth = cameras[k].Invert() * cameras[k - 1];
|
||||
foreach (var (x, y) in GridPoints())
|
||||
{
|
||||
var (tx, ty) = truth.Apply(x, y);
|
||||
var (mx, my) = motion.Transform.Apply(x, y);
|
||||
error += double.Hypot(tx - mx, ty - my);
|
||||
samples++;
|
||||
}
|
||||
}
|
||||
motionError = error / samples;
|
||||
return stabilizer.Solve();
|
||||
}
|
||||
|
||||
/// <summary>RMS frame-to-frame displacement of fixed content points in the (corrected) frames.</summary>
|
||||
private static double Jitter(Affine2D[] cameras, IReadOnlyList<Affine2D>? corrections, bool removeMean = false)
|
||||
{
|
||||
var points = GridPoints().Select(p => cameras[0].Apply(p.X, p.Y)).ToArray();
|
||||
var steps = new List<(double X, double Y)>();
|
||||
for (var k = 1; k < cameras.Length; k++)
|
||||
{
|
||||
foreach (var (bx, by) in points)
|
||||
{
|
||||
var (x0, y0) = cameras[k - 1].Invert().Apply(bx, by);
|
||||
var (x1, y1) = cameras[k].Invert().Apply(bx, by);
|
||||
if (corrections is not null)
|
||||
{
|
||||
(x0, y0) = corrections[k - 1].Apply(x0, y0);
|
||||
(x1, y1) = corrections[k].Apply(x1, y1);
|
||||
}
|
||||
steps.Add((x1 - x0, y1 - y0));
|
||||
}
|
||||
}
|
||||
double mx = 0, my = 0;
|
||||
if (removeMean)
|
||||
{
|
||||
mx = steps.Average(s => s.X);
|
||||
my = steps.Average(s => s.Y);
|
||||
}
|
||||
return double.Sqrt(steps.Average(s => (s.X - mx) * (s.X - mx) + (s.Y - my) * (s.Y - my)));
|
||||
}
|
||||
|
||||
private static IEnumerable<(double X, double Y)> GridPoints()
|
||||
{
|
||||
for (var j = 1; j <= 3; j++)
|
||||
for (var i = 1; i <= 3; i++)
|
||||
yield return (Width * i / 4.0, Height * j / 4.0);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Motion;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Motion;
|
||||
|
||||
public sealed class TemporalStackerTests
|
||||
{
|
||||
private const int Size = 96;
|
||||
|
||||
private readonly TestContext _context;
|
||||
|
||||
public TemporalStackerTests(TestContext context) => _context = context;
|
||||
|
||||
[Test]
|
||||
public void StarTrailLuminanceNeverDecreasesWithUnitDecay()
|
||||
{
|
||||
var random = new Random(5);
|
||||
using var stacker = new StarTrailStacker(1.0);
|
||||
using var frame = new ImageBuffer(Size, Size);
|
||||
var previous = new float[Size * Size];
|
||||
var current = new float[Size * Size];
|
||||
long steps = 0, nonDecreasing = 0;
|
||||
for (var k = 0; k < 40; k++)
|
||||
{
|
||||
NightFrame(frame, random, k);
|
||||
stacker.Add(frame);
|
||||
ColorSpace.Luminance(stacker.Result!, current);
|
||||
if (k > 0)
|
||||
{
|
||||
for (var i = 0; i < current.Length; i++)
|
||||
{
|
||||
steps++;
|
||||
if (current[i] >= previous[i]) nonDecreasing++;
|
||||
}
|
||||
}
|
||||
(previous, current) = (current, previous);
|
||||
}
|
||||
var fraction = nonDecreasing / (double)steps;
|
||||
_context.Log($"non-decreasing on {fraction:P3} of {steps} pixel steps");
|
||||
Assert.GreaterOrEqual(fraction, 0.99);
|
||||
Assert.Equal(40, stacker.Count);
|
||||
// The trail of the first star position is still lit after 40 frames.
|
||||
Assert.Greater(stacker.Result![1, StarX(0), StarY(0)], 0.5f);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FiniteTrailsFadeToOnePercentOverTheirLength()
|
||||
{
|
||||
Assert.Equal(1.0, StarTrailStacker.DecayForTrailLength(double.PositiveInfinity));
|
||||
Assert.Equal(1.0, StarTrailStacker.DecayForTrailLength(0));
|
||||
var decay = StarTrailStacker.DecayForTrailLength(20);
|
||||
Assert.Approximately(0.01, double.Pow(decay, 20), 1e-12);
|
||||
|
||||
using var stacker = new StarTrailStacker(decay);
|
||||
using var lit = new ImageBuffer(8, 8, 1);
|
||||
using var dark = new ImageBuffer(8, 8, 1);
|
||||
lit[0, 3, 3] = 1f;
|
||||
stacker.Add(lit);
|
||||
for (var k = 0; k < 20; k++) stacker.Add(dark);
|
||||
Assert.Approximately(0.01, stacker.Result![0, 3, 3], 1e-5);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MedianRemovesATransientOutlierFrame()
|
||||
{
|
||||
var plane = SyntheticImages.Crop(SyntheticImages.Natural(128, seed: 12), 128, 0, 0, Size, Size);
|
||||
var random = new Random(8);
|
||||
using var stacker = new TemporalStacker(7, StackMode.Median);
|
||||
for (var k = 0; k < 7; k++)
|
||||
{
|
||||
using var frame = SyntheticImages.ToRgb(plane, Size, Size);
|
||||
var data = frame.Data;
|
||||
for (var i = 0; i < data.Length; i++) data[i] += 0.01f * (float)(random.NextDouble() - 0.5);
|
||||
if (k == 3)
|
||||
{
|
||||
// An aircraft light streak crossing one frame.
|
||||
for (var c = 0; c < 3; c++)
|
||||
for (var x = 10; x < 80; x++)
|
||||
frame[c, x, 40 + x / 8] = 5f;
|
||||
}
|
||||
stacker.Push(frame);
|
||||
}
|
||||
Assert.True(stacker.IsFull);
|
||||
using var output = new ImageBuffer(Size, Size);
|
||||
stacker.Render(output);
|
||||
using var reference = SyntheticImages.ToRgb(plane, Size, Size);
|
||||
double maxError = 0;
|
||||
for (var i = 0; i < output.Data.Length; i++) maxError = double.Max(maxError, double.Abs(output.Data[i] - reference.Data[i]));
|
||||
_context.Log($"max deviation from the clean frame {maxError:F4}");
|
||||
Assert.Less(maxError, 0.01);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(1)]
|
||||
[Case(5)]
|
||||
[Case(6)]
|
||||
[Case(32)]
|
||||
[Case(33)]
|
||||
public void MedianIsExact(int count)
|
||||
{
|
||||
var random = new Random(count);
|
||||
var frames = new List<ImageBuffer>();
|
||||
try
|
||||
{
|
||||
for (var k = 0; k < count; k++)
|
||||
{
|
||||
var frame = new ImageBuffer(37, 5, 3);
|
||||
var data = frame.Data;
|
||||
for (var i = 0; i < data.Length; i++) data[i] = (float)random.NextDouble();
|
||||
frames.Add(frame);
|
||||
}
|
||||
using var output = new ImageBuffer(37, 5, 3);
|
||||
TemporalStacker.Median(frames, output);
|
||||
for (var i = 0; i < output.Data.Length; i++)
|
||||
{
|
||||
var sorted = frames.Select(f => f.Data[i]).Order().ToArray();
|
||||
var expected = count % 2 == 1 ? sorted[count / 2] : 0.5f * (sorted[count / 2 - 1] + sorted[count / 2]);
|
||||
Assert.Equal(expected, output.Data[i]);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var f in frames) f.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MeanReducesNoiseBySquareRootOfN()
|
||||
{
|
||||
const int n = 16;
|
||||
const double sigma = 0.05;
|
||||
var random = new Random(3);
|
||||
using var stacker = new TemporalStacker(n, StackMode.Mean);
|
||||
using var frame = new ImageBuffer(Size, Size, 1);
|
||||
for (var k = 0; k < n; k++)
|
||||
{
|
||||
var data = frame.Data;
|
||||
for (var i = 0; i < data.Length; i++) data[i] = 0.4f + (float)(sigma * Gaussian(random));
|
||||
stacker.Push(frame);
|
||||
}
|
||||
using var output = new ImageBuffer(Size, Size, 1);
|
||||
stacker.Render(output);
|
||||
var values = output.Data.ToArray();
|
||||
var mean = values.Average(v => (double)v);
|
||||
var std = double.Sqrt(values.Average(v => (v - mean) * (v - mean)));
|
||||
_context.Log($"residual σ {std:F5} (expected {sigma / double.Sqrt(n):F5})");
|
||||
Assert.Approximately(0.4, mean, 0.002);
|
||||
Assert.Approximately(sigma / double.Sqrt(n), std, 0.15 * sigma / double.Sqrt(n));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WindowSlidesOverTheNewestFrames()
|
||||
{
|
||||
using var stacker = new TemporalStacker(3, StackMode.Median);
|
||||
using var frame = new ImageBuffer(4, 4, 1);
|
||||
for (var k = 0; k < 10; k++)
|
||||
{
|
||||
frame.Data.Fill(k);
|
||||
stacker.Push(frame);
|
||||
}
|
||||
Assert.Equal(3, stacker.Count);
|
||||
using var output = new ImageBuffer(4, 4, 1);
|
||||
stacker.Render(output);
|
||||
Assert.True(output.Data.ToArray().All(v => v == 8f));
|
||||
using var other = new ImageBuffer(5, 4, 1);
|
||||
Assert.Throws<ArgumentException>(() => stacker.Push(other));
|
||||
stacker.Clear();
|
||||
Assert.Throws<InvalidOperationException>(() => stacker.Render(output));
|
||||
}
|
||||
|
||||
private static int StarX(int k) => 20 + k;
|
||||
|
||||
private static int StarY(int k) => 30 + k / 3;
|
||||
|
||||
/// <summary>Dark noisy sky with one star drifting one pixel per frame and a few twinkling faint ones.</summary>
|
||||
private static void NightFrame(ImageBuffer frame, Random random, int k)
|
||||
{
|
||||
var data = frame.Data;
|
||||
for (var i = 0; i < data.Length; i++) data[i] = 0.002f + 0.001f * (float)random.NextDouble();
|
||||
for (var c = 0; c < 3; c++)
|
||||
{
|
||||
frame[c, StarX(k), StarY(k)] = 0.9f;
|
||||
frame[c, 60, 70] = 0.1f + 0.05f * (k % 3);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
using Titano.Core.Imaging.Geometry;
|
||||
using Titano.Core.Motion;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Motion;
|
||||
|
||||
public sealed class VirtualCameraTests
|
||||
{
|
||||
private static readonly CameraKeyframe[] Path =
|
||||
[
|
||||
new(0, 0.5, 0.5, 1.0, 0),
|
||||
new(30, 0.3, 0.6, 2.0, 5),
|
||||
new(75, 0.7, 0.4, 1.5, -3),
|
||||
new(100, 0.55, 0.45, 3.0, 0) { Easing = BezierEasing.Linear },
|
||||
];
|
||||
|
||||
[Test]
|
||||
public void EasedPathHitsKeyframesExactly()
|
||||
{
|
||||
var camera = new VirtualCamera(Path.Reverse());
|
||||
foreach (var k in Path) Assert.Equal(k.State, camera.Evaluate(k.Frame));
|
||||
Assert.Equal(Path[0].State, camera.Evaluate(-10));
|
||||
Assert.Equal(Path[^1].State, camera.Evaluate(250));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EaseInOutPathIsC1Continuous()
|
||||
{
|
||||
var camera = new VirtualCamera(Path);
|
||||
const double h = 1e-5;
|
||||
foreach (var frame in new[] { 30.0, 75.0 })
|
||||
{
|
||||
foreach (var component in Components)
|
||||
{
|
||||
var at = component(camera.Evaluate(frame));
|
||||
var left = (at - component(camera.Evaluate(frame - h))) / h;
|
||||
var right = (component(camera.Evaluate(frame + h)) - at) / h;
|
||||
Assert.Approximately(left, right, 1e-3);
|
||||
Assert.Approximately(0, right, 1e-3);
|
||||
}
|
||||
}
|
||||
|
||||
// No jumps in velocity anywhere: neighbouring derivatives differ only by curvature × step.
|
||||
foreach (var component in Components)
|
||||
{
|
||||
double? previous = null;
|
||||
for (var t = 0.0; t <= 100; t += 0.05)
|
||||
{
|
||||
var d = (component(camera.Evaluate(t + h)) - component(camera.Evaluate(t - h))) / (2 * h);
|
||||
if (previous is { } p) Assert.Less(double.Abs(d - p), 2e-3);
|
||||
previous = d;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EasingPresetsBehave()
|
||||
{
|
||||
for (var t = 0.0; t <= 1.0; t += 0.01)
|
||||
{
|
||||
Assert.Approximately(t, BezierEasing.Linear.Evaluate(t), 1e-9);
|
||||
Assert.Approximately(1, BezierEasing.EaseInOut.Evaluate(t) + BezierEasing.EaseInOut.Evaluate(1 - t), 1e-9);
|
||||
}
|
||||
Assert.Less(BezierEasing.EaseIn.Evaluate(0.5), 0.5);
|
||||
Assert.Greater(BezierEasing.EaseOut.Evaluate(0.5), 0.5);
|
||||
Assert.Equal(0.0, BezierEasing.EaseInOut.Evaluate(0));
|
||||
Assert.Equal(1.0, BezierEasing.EaseInOut.Evaluate(1));
|
||||
Assert.Monotonic(Enumerable.Range(0, 101).Select(i => BezierEasing.EaseInOut.Evaluate(i / 100.0)));
|
||||
// CSS "ease" reference value: cubic-bezier(0.25, 0.1, 0.25, 1) at t = 0.5 ≈ 0.8024.
|
||||
Assert.Approximately(0.8024, new BezierEasing(0.25, 0.1, 0.25, 1).Evaluate(0.5), 1e-3);
|
||||
var overshoot = new BezierEasing(0.3, 0, 0.6, 1.6);
|
||||
Assert.Greater(Enumerable.Range(0, 101).Max(i => overshoot.Evaluate(i / 100.0)), 1.0);
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => _ = new BezierEasing(1.2, 0, 0.5, 1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ZoomInterpolatesGeometrically()
|
||||
{
|
||||
var camera = new VirtualCamera([new CameraKeyframe(0, 0.5, 0.5, 1, 0) { Easing = BezierEasing.Linear }, new CameraKeyframe(10, 0.5, 0.5, 4, 0)]);
|
||||
Assert.Approximately(2, camera.Evaluate(5).Zoom, 1e-12);
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new VirtualCamera([new CameraKeyframe(0, 0.5, 0.5, 0.5, 0)]));
|
||||
Assert.Throws<ArgumentException>(() => new VirtualCamera([new CameraKeyframe(3, 0.5, 0.5, 1, 0), new CameraKeyframe(3, 0.2, 0.5, 1, 0)]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ViewMapsToSourceWindow()
|
||||
{
|
||||
const int w = 1920, h = 1080;
|
||||
Assert.True(VirtualCamera.ViewToSource(new CameraState(0.5, 0.5, 1, 0), w, h).IsIdentity(1e-12));
|
||||
|
||||
var zoomed = VirtualCamera.ViewToSource(new CameraState(0.25, 0.5, 2, 0), w, h);
|
||||
var (cx, cy) = zoomed.Apply((w - 1) / 2.0, (h - 1) / 2.0);
|
||||
Assert.Within(479.5, 539.5, cx, cy, 1e-9);
|
||||
// The view's left edge lands half a view-width (w/4 source pixels) left of the centre.
|
||||
var (lx, _) = zoomed.Apply(-0.5, (h - 1) / 2.0);
|
||||
Assert.Approximately(480 - w / 4.0 - 0.5, lx, 1e-9);
|
||||
|
||||
var rolled = VirtualCamera.ViewToSource(new CameraState(0.5, 0.5, 1, 90), w, h);
|
||||
var (vx, vy) = rolled.ApplyVector(1, 0);
|
||||
Assert.Within(0, 1, vx, vy, 1e-12);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ComposesWithStabilisationIntoOneAffine()
|
||||
{
|
||||
const int w = 640, h = 480;
|
||||
var camera = new VirtualCamera(Path);
|
||||
var correction = Affine2D.About(Affine2D.Similarity(1.01, 0.004, 1.5, -2.25), (w - 1) / 2.0, (h - 1) / 2.0);
|
||||
var combined = camera.ToSource(42.5, w, h, correction);
|
||||
var view = VirtualCamera.ViewToSource(camera.Evaluate(42.5), w, h);
|
||||
foreach (var (x, y) in new[] { (0.0, 0.0), (320.0, 240.0), (639.0, 100.0) })
|
||||
{
|
||||
// Stabilised coordinates of the source sample must be where the view looks.
|
||||
var (sx, sy) = combined.Apply(x, y);
|
||||
var (tx, ty) = correction.Apply(sx, sy);
|
||||
var (ex, ey) = view.Apply(x, y);
|
||||
Assert.Within(ex, ey, tx, ty, 1e-9);
|
||||
}
|
||||
Assert.Equal(view, camera.ToSource(42.5, w, h));
|
||||
}
|
||||
|
||||
private static readonly Func<CameraState, double>[] Components = [s => s.CenterX, s => s.CenterY, s => s.Zoom, s => s.Rotation / 100];
|
||||
}
|
||||
Reference in new issue
Block a user