using System.Buffers;
using Titano.Core.Imaging;
namespace Titano.Core.Motion;
/// Speed/quality trade-off of .
public enum FlowQuality
{
/// Vectors every 4 px, few iterations: previews and analysis histograms.
Draft,
/// Vectors every 2 px: motion blur and analysis.
Balanced,
/// Per-pixel vectors, more iterations and a 5×5 median: frame interpolation.
Best,
}
/// Parameters of the dense pyramidal Lucas–Kanade solver.
public sealed record OpticalFlowOptions
{
/// Upper bound on pyramid levels (the coarsest level keeps ≥ 16 px on its short side).
public int MaxLevels { get; init; } = 5;
/// Finest level solved; the output grid step is 2^FinestLevel pixels.
public int FinestLevel { get; init; } = 1;
/// Warp–solve iterations per level.
public int Iterations { get; init; } = 4;
/// Lucas–Kanade integration window radius (box of (2r+1)² samples) at every level.
public int WindowRadius { get; init; } = 3;
/// Median filter radius applied to the field after each level (0 = off).
public int MedianRadius { get; init; } = 1;
/// Tikhonov term added to the structure tensor diagonal (perceptual luminance² per px²).
public float Regularization { get; init; } = 1e-5f;
public static OpticalFlowOptions For(FlowQuality quality) => quality switch
{
FlowQuality.Draft => new OpticalFlowOptions { MaxLevels = 4, FinestLevel = 2, Iterations = 3 },
FlowQuality.Balanced => new OpticalFlowOptions(),
FlowQuality.Best => new OpticalFlowOptions { MaxLevels = 6, FinestLevel = 0, Iterations = 5, WindowRadius = 4, MedianRadius = 2 },
_ => throw new ArgumentOutOfRangeException(nameof(quality)),
};
}
///
/// Dense optical flow by pyramidal Lucas–Kanade (Lucas & Kanade 1981; Bouguet 2000) solved for a window
/// around every pixel of each level: both frames get a σ = 1 binomial blur, box-window structure tensors of
/// the first frame's gradients are inverted once per level (inverse-compositional form), and each iteration
/// warps the second frame by the current flow (bilinear) and re-solves every window with a first-order
/// correction for its neighbours' flows; the field is median filtered between levels (Sun, Roth & Black
/// 2010). Chosen over Farnebäck polynomial expansion because every step is a separable box filter or a
/// per-pixel 2×2 solve that vectorises and parallelises cleanly, with equal sub-pixel accuracy on smooth
/// motion. Forward–backward consistency (Sundaram et al. 2010) marks occlusions. One engine holds reusable
/// workspaces, so it must not be shared between threads.
///
public sealed class OpticalFlowEngine : IDisposable
{
private const float MaxUpdate = 2f;
private GrayPyramid? _first;
private GrayPyramid? _second;
private float[][] _work = [];
private int _capacity;
public OpticalFlowEngine(OpticalFlowOptions? options = null) => Options = options ?? new OpticalFlowOptions();
public OpticalFlowEngine(FlowQuality quality) : this(OpticalFlowOptions.For(quality))
{
}
public OpticalFlowOptions Options { get; }
/// Flow from to (perceptual luminance of both).
public MotionField Compute(ImageBuffer from, ImageBuffer to, CancellationToken cancellationToken = default)
{
BuildPyramids(from, to);
return Compute(_first!, _second!, cancellationToken);
}
/// Flow between two prebuilt pyramids (lets callers reuse each frame's pyramid for two pairs).
public MotionField Compute(GrayPyramid from, GrayPyramid to, CancellationToken cancellationToken = default)
{
if (from.Width != to.Width || from.Height != to.Height || from.Levels != to.Levels)
throw new ArgumentException("Pyramids differ in size or depth.", nameof(to));
var coarsest = int.Min(from.Levels, Options.MaxLevels) - 1;
var finest = int.Clamp(Options.FinestLevel, 0, coarsest);
EnsureWorkspace(from.LevelWidth(finest) * from.LevelHeight(finest));
float[] u = _work[0], v = _work[1];
for (var level = coarsest; level >= finest; level--)
{
cancellationToken.ThrowIfCancellationRequested();
var w = from.LevelWidth(level);
var h = from.LevelHeight(level);
if (level == coarsest)
{
Array.Clear(u, 0, w * h);
Array.Clear(v, 0, w * h);
}
else
{
var (nu, nv) = u == _work[0] ? (_work[2], _work[3]) : (_work[0], _work[1]);
Upsample(u, nu, from.LevelWidth(level + 1), from.LevelHeight(level + 1), w, h);
Upsample(v, nv, from.LevelWidth(level + 1), from.LevelHeight(level + 1), w, h);
(u, v) = (nu, nv);
}
SolveLevel(from.LevelArray(level), to.LevelArray(level), w, h, u, v, cancellationToken);
}
var step = 1 << finest;
var field = new MotionField(from.Width, from.Height, step);
var n = field.Count;
var fu = field.U;
var fv = field.V;
for (var i = 0; i < n; i++)
{
fu[i] = u[i] * step;
fv[i] = v[i] * step;
}
return field;
}
/// Forward and backward flow with their forward–backward consistency errors filled in.
public (MotionField Forward, MotionField Backward) ComputeBidirectional(ImageBuffer from, ImageBuffer to, CancellationToken cancellationToken = default)
{
BuildPyramids(from, to);
return ComputeBidirectional(_first!, _second!, cancellationToken);
}
///
public (MotionField Forward, MotionField Backward) ComputeBidirectional(GrayPyramid from, GrayPyramid to, CancellationToken cancellationToken = default)
{
var forward = Compute(from, to, cancellationToken);
try
{
var backward = Compute(to, from, cancellationToken);
CheckConsistency(forward, backward);
return (forward, backward);
}
catch
{
forward.Dispose();
throw;
}
}
///
/// Fills both fields' with |w(p) + w'(p + w(p))|; vectors leaving the
/// frame get +∞ (unverifiable, treated as occluded).
///
public static void CheckConsistency(MotionField forward, MotionField backward)
{
if (forward.ImageWidth != backward.ImageWidth || forward.ImageHeight != backward.ImageHeight)
throw new ArgumentException("Fields describe different image sizes.", nameof(backward));
Fill(forward, backward);
Fill(backward, forward);
forward.HasConsistency = backward.HasConsistency = true;
static void Fill(MotionField field, MotionField other)
{
var u = field.U;
var v = field.V;
var error = field.Error;
var maxX = field.ImageWidth - 0.5;
var maxY = field.ImageHeight - 0.5;
for (var j = 0; j < field.Rows; j++)
{
for (var i = 0; i < field.Columns; i++)
{
var k = j * field.Columns + i;
var x = i * field.Step + (double)u[k];
var y = j * field.Step + (double)v[k];
if (x < -0.5 || y < -0.5 || x > maxX || y > maxY)
{
error[k] = float.PositiveInfinity;
continue;
}
var (bu, bv) = other.Sample(x, y);
error[k] = float.Hypot(u[k] + bu, v[k] + bv);
}
}
}
}
public void Dispose()
{
_first?.Dispose();
_second?.Dispose();
_first = _second = null;
foreach (var a in _work) ArrayPool.Shared.Return(a);
_work = [];
_capacity = 0;
}
private void BuildPyramids(ImageBuffer from, ImageBuffer to)
{
if (from.Width != to.Width || from.Height != to.Height) throw new ArgumentException("Frames differ in size.", nameof(to));
if (_first is null || _first.Width != from.Width || _first.Height != from.Height)
{
_first?.Dispose();
_second?.Dispose();
var levels = GrayPyramid.LevelsFor(from.Width, from.Height, 16, Options.MaxLevels);
_first = new GrayPyramid(from.Width, from.Height, levels);
_second = new GrayPyramid(from.Width, from.Height, levels);
}
_first.Build(from);
_second!.Build(to);
}
private void EnsureWorkspace(int length)
{
if (length <= _capacity) return;
foreach (var a in _work) ArrayPool.Shared.Return(a);
// u, v, u', v', Ix, Iy, H11, H12, H22, Bx, By, scratch, smoothed first, smoothed second.
_work = new float[14][];
for (var i = 0; i < _work.Length; i++) _work[i] = ArrayPool.Shared.Rent(length);
_capacity = length;
}
private void SolveLevel(float[] i0, float[] i1, int w, int h, float[] u, float[] v, CancellationToken cancellationToken)
{
var (spareU, spareV) = u == _work[0] ? (_work[2], _work[3]) : (_work[0], _work[1]);
float[] ix = _work[4], iy = _work[5], h11 = _work[6], h12 = _work[7], h22 = _work[8], bx = _work[9], by = _work[10], scratch = _work[11];
var radius = Options.WindowRadius;
var lambda = Options.Regularization;
// Central differences under-estimate high-frequency derivatives relative to how the bilinearly warped
// frame responds to a flow change (ratio 1/cos πf), which over-shoots the Gauss–Newton step beyond 2×
// above f ≈ 1/3 cycles/px and makes the iteration diverge. A σ = 1 blur of both frames removes that
// band; being the same translation-invariant filter on both, it does not bias the solution.
PlaneOps.Binomial5(i0, _work[12], scratch, w, h);
PlaneOps.Binomial5(i1, _work[13], scratch, w, h);
i0 = _work[12];
i1 = _work[13];
// Gradients of the first frame and their structure-tensor products.
PlaneOps.ForRows(h, w, y =>
{
var row = y * w;
var up = int.Max(y - 1, 0) * w;
var down = int.Min(y + 1, h - 1) * w;
for (var x = 0; x < w; x++)
{
var gx = 0.5f * (i0[row + int.Min(x + 1, w - 1)] - i0[row + int.Max(x - 1, 0)]);
var gy = 0.5f * (i0[down + x] - i0[up + x]);
ix[row + x] = gx;
iy[row + x] = gy;
h11[row + x] = gx * gx;
h12[row + x] = gx * gy;
h22[row + x] = gy * gy;
}
});
PlaneOps.BoxFilter(h11, h11, scratch, w, h, radius);
PlaneOps.BoxFilter(h12, h12, scratch, w, h, radius);
PlaneOps.BoxFilter(h22, h22, scratch, w, h, radius);
PlaneOps.ForRows(h, w, y =>
{
for (int x = 0, k = y * w; x < w; x++, k++)
{
var a = h11[k] + lambda;
var b = h12[k];
var c = h22[k] + lambda;
var r = 1f / (a * c - b * b);
h11[k] = c * r;
h12[k] = -b * r;
h22[k] = a * r;
}
});
for (var iteration = 0; iteration < Options.Iterations; iteration++)
{
cancellationToken.ThrowIfCancellationRequested();
// Each window solves for one flow v: min Σ_y (I1w(y) + g(y)·(v − u(y)) − I0(y))², i.e. the classic
// Lucas–Kanade window with a first-order correction for the neighbours' own flows. Unlike the
// per-pixel update u −= G⁻¹·box(g·It), this does not feed the current error back through
// ill-conditioned (aperture) windows, so it cannot diverge. Samples warped outside the frame
// vote for their current flow (It = 0).
PlaneOps.ForRows(h, w, y =>
{
var span = i1.AsSpan(0, w * h);
for (int x = 0, k = y * w; x < w; x++, k++)
{
var px = x + u[k];
var py = y + v[k];
var it = px >= 0 && py >= 0 && px <= w - 1 && py <= h - 1
? PlaneOps.Bilinear(span, w, h, px, py) - i0[k]
: 0f;
var r = ix[k] * u[k] + iy[k] * v[k] - it;
bx[k] = ix[k] * r;
by[k] = iy[k] * r;
}
});
PlaneOps.BoxFilter(bx, bx, scratch, w, h, radius);
PlaneOps.BoxFilter(by, by, scratch, w, h, radius);
PlaneOps.ForRows(h, w, y =>
{
for (int x = 0, k = y * w; x < w; x++, k++)
{
// (G + λI)⁻¹ (box(q) + λu): the regulariser keeps textureless windows at their current flow.
var qx = bx[k] + lambda * u[k];
var qy = by[k] + lambda * v[k];
var nu = h11[k] * qx + h12[k] * qy;
var nv = h12[k] * qx + h22[k] * qy;
u[k] += float.Clamp(nu - u[k], -MaxUpdate, MaxUpdate);
v[k] += float.Clamp(nv - v[k], -MaxUpdate, MaxUpdate);
}
});
}
if (Options.MedianRadius > 0)
{
PlaneOps.MedianFilter(u, spareU, w, h, Options.MedianRadius);
PlaneOps.MedianFilter(v, spareV, w, h, Options.MedianRadius);
Array.Copy(spareU, u, w * h);
Array.Copy(spareV, v, w * h);
}
}
/// Doubles the resolution and the magnitude of a level's flow (level-ℓ pixel k ↔ level-(ℓ−1) pixel 2k).
private static void Upsample(float[] coarse, float[] fine, int cw, int ch, int w, int h)
{
PlaneOps.ForRows(h, w, y =>
{
var span = coarse.AsSpan(0, cw * ch);
for (var x = 0; x < w; x++) fine[y * w + x] = 2 * PlaneOps.Bilinear(span, cw, ch, 0.5f * x, 0.5f * y);
});
}
}