feat(imaging): add separable resampler and pixel conversion tests
Two-pass Lanczos3 (downscale, support stretched by the reduction) and Catmull-Rom (upscale) with normalised, edge-folded weights; exact area-average box path for thumbnails; pass order chosen by cost, Vector<float> inner loops, parallel rows. Tests cover constant images, energy preservation, step ringing against the kernel's exact discrete bound, Exif orientations and dithering. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
3 files changed
+485
No files matched your search
@@ -0,0 +1,201 @@
|
||||
using System.Numerics;
|
||||
|
||||
namespace Titano.Core.Imaging;
|
||||
|
||||
/// <summary>Reconstruction filters for <see cref="Resampler"/>.</summary>
|
||||
public enum ResampleFilter
|
||||
{
|
||||
/// <summary>Lanczos3 on axes that shrink, Catmull-Rom on axes that grow.</summary>
|
||||
Auto,
|
||||
|
||||
/// <summary>Exact area average (no ringing; fastest for large reductions such as thumbnails).</summary>
|
||||
Box,
|
||||
|
||||
Lanczos3,
|
||||
CatmullRom,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Separable two-pass resampling of linear-light <see cref="ImageBuffer"/>s. When shrinking, the kernel is stretched
|
||||
/// by the reduction factor (proper low-pass support); weights are normalised and folded at the edges (clamp), so
|
||||
/// constant images stay constant and mean energy is preserved. Rows are processed in parallel.
|
||||
/// </summary>
|
||||
public static class Resampler
|
||||
{
|
||||
/// <summary>Resizes into a new buffer with the same channel count.</summary>
|
||||
public static ImageBuffer Resize(ImageBuffer source, int width, int height, ResampleFilter filter = ResampleFilter.Auto, int maxDegreeOfParallelism = -1)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
|
||||
var parallel = new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism };
|
||||
if (width == source.Width && height == source.Height) return source.Clone();
|
||||
var wx = width == source.Width ? null : Weights.Build(source.Width, width, filter);
|
||||
var wy = height == source.Height ? null : Weights.Build(source.Height, height, filter);
|
||||
if (wx is null) return Vertical(source, wy!, parallel);
|
||||
if (wy is null) return Horizontal(source, wx, parallel);
|
||||
|
||||
// Run the pass that leaves the smaller intermediate work first.
|
||||
var horizontalFirst = (long)source.Height * width * wx.Stride + (long)height * width * wy.Stride
|
||||
<= (long)height * source.Width * wy.Stride + (long)height * width * wx.Stride;
|
||||
using var intermediate = horizontalFirst ? Horizontal(source, wx, parallel) : Vertical(source, wy, parallel);
|
||||
return horizontalFirst ? Vertical(intermediate, wy, parallel) : Horizontal(intermediate, wx, parallel);
|
||||
}
|
||||
|
||||
/// <summary>Area-average reduction so that the long edge is at most <paramref name="maxLongEdge"/>
|
||||
/// (a copy when the image is already small enough).</summary>
|
||||
public static ImageBuffer Thumbnail(ImageBuffer source, int maxLongEdge)
|
||||
{
|
||||
var (w, h) = FitWithin(source.Width, source.Height, maxLongEdge);
|
||||
return w == source.Width && h == source.Height ? source.Clone() : Resize(source, w, h, ResampleFilter.Box);
|
||||
}
|
||||
|
||||
/// <summary>Largest size with the same aspect ratio whose long edge is ≤ <paramref name="maxLongEdge"/> (never upscales).</summary>
|
||||
public static (int Width, int Height) FitWithin(int width, int height, int maxLongEdge)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxLongEdge);
|
||||
var longEdge = Math.Max(width, height);
|
||||
if (longEdge <= maxLongEdge) return (width, height);
|
||||
var scale = maxLongEdge / (double)longEdge;
|
||||
return (Math.Max(1, (int)Math.Round(width * scale)), Math.Max(1, (int)Math.Round(height * scale)));
|
||||
}
|
||||
|
||||
private static ImageBuffer Horizontal(ImageBuffer source, Weights w, ParallelOptions parallel)
|
||||
{
|
||||
var result = new ImageBuffer(w.Length, source.Height, source.Channels, clear: false);
|
||||
Parallel.For(0, source.Height, parallel, y =>
|
||||
{
|
||||
for (var c = 0; c < source.Channels; c++)
|
||||
{
|
||||
ReadOnlySpan<float> src = source.Row(c, y);
|
||||
var dst = result.Row(c, y);
|
||||
for (var x = 0; x < dst.Length; x++)
|
||||
{
|
||||
dst[x] = Dot(src.Slice(w.Start[x], w.Count[x]), w.Values.AsSpan(x * w.Stride, w.Count[x]));
|
||||
}
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
private static ImageBuffer Vertical(ImageBuffer source, Weights w, ParallelOptions parallel)
|
||||
{
|
||||
var result = new ImageBuffer(source.Width, w.Length, source.Channels, clear: false);
|
||||
Parallel.For(0, w.Length, parallel, y =>
|
||||
{
|
||||
var taps = w.Values.AsSpan(y * w.Stride, w.Count[y]);
|
||||
for (var c = 0; c < source.Channels; c++)
|
||||
{
|
||||
var dst = result.Row(c, y);
|
||||
dst.Clear();
|
||||
for (var k = 0; k < taps.Length; k++) MultiplyAdd(source.Row(c, w.Start[y] + k), taps[k], dst);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
private static float Dot(ReadOnlySpan<float> a, ReadOnlySpan<float> b)
|
||||
{
|
||||
var i = 0;
|
||||
var sum = 0f;
|
||||
if (Vector.IsHardwareAccelerated && a.Length >= Vector<float>.Count)
|
||||
{
|
||||
var acc = Vector<float>.Zero;
|
||||
for (; i <= a.Length - Vector<float>.Count; i += Vector<float>.Count) acc += new Vector<float>(a[i..]) * new Vector<float>(b[i..]);
|
||||
sum = Vector.Sum(acc);
|
||||
}
|
||||
for (; i < a.Length; i++) sum += a[i] * b[i];
|
||||
return sum;
|
||||
}
|
||||
|
||||
private static void MultiplyAdd(ReadOnlySpan<float> src, float weight, Span<float> dst)
|
||||
{
|
||||
var i = 0;
|
||||
if (Vector.IsHardwareAccelerated)
|
||||
{
|
||||
var w = new Vector<float>(weight);
|
||||
for (; i <= dst.Length - Vector<float>.Count; i += Vector<float>.Count) (new Vector<float>(dst[i..]) + new Vector<float>(src[i..]) * w).CopyTo(dst[i..]);
|
||||
}
|
||||
for (; i < dst.Length; i++) dst[i] += src[i] * weight;
|
||||
}
|
||||
|
||||
/// <summary>Per output sample: a contiguous source range and its normalised weights (stride-padded).</summary>
|
||||
private sealed class Weights
|
||||
{
|
||||
public required int Length { get; init; }
|
||||
public required int Stride { get; init; }
|
||||
public required int[] Start { get; init; }
|
||||
public required int[] Count { get; init; }
|
||||
public required float[] Values { get; init; }
|
||||
|
||||
public static Weights Build(int source, int target, ResampleFilter filter)
|
||||
{
|
||||
var scale = target / (double)source;
|
||||
var kind = filter == ResampleFilter.Auto ? (scale < 1 ? ResampleFilter.Lanczos3 : ResampleFilter.CatmullRom) : filter;
|
||||
var radius = kind switch { ResampleFilter.Lanczos3 => 3.0, ResampleFilter.CatmullRom => 2.0, _ => 0.5 };
|
||||
var stretch = Math.Max(1.0, 1 / scale);
|
||||
var stride = (int)Math.Ceiling(2 * radius * stretch) + 2;
|
||||
var start = new int[target];
|
||||
var count = new int[target];
|
||||
var values = new float[target * stride];
|
||||
var taps = new double[source];
|
||||
for (var i = 0; i < target; i++)
|
||||
{
|
||||
double lo, hi;
|
||||
if (kind == ResampleFilter.Box)
|
||||
{
|
||||
lo = i / scale;
|
||||
hi = (i + 1) / scale;
|
||||
}
|
||||
else
|
||||
{
|
||||
var center = (i + 0.5) / scale;
|
||||
lo = center - radius * stretch;
|
||||
hi = center + radius * stretch;
|
||||
}
|
||||
int first = Math.Max(0, (int)Math.Floor(lo) - 1), last = Math.Min(source - 1, (int)Math.Ceiling(hi));
|
||||
int left = (int)Math.Floor(lo) - 1, right = (int)Math.Ceiling(hi);
|
||||
Array.Clear(taps, first, last - first + 1);
|
||||
var sum = 0.0;
|
||||
for (var j = left; j <= right; j++)
|
||||
{
|
||||
double weight;
|
||||
if (kind == ResampleFilter.Box)
|
||||
{
|
||||
weight = Math.Max(0, Math.Min(hi, j + 1) - Math.Max(lo, j));
|
||||
}
|
||||
else
|
||||
{
|
||||
var x = (j + 0.5 - (i + 0.5) / scale) / stretch;
|
||||
weight = kind == ResampleFilter.Lanczos3 ? Lanczos3(x) : CatmullRom(x);
|
||||
}
|
||||
if (weight == 0) continue;
|
||||
taps[Math.Clamp(j, 0, source - 1)] += weight; // clamp-to-edge folds outside taps inward
|
||||
sum += weight;
|
||||
}
|
||||
while (first < last && taps[first] == 0) first++;
|
||||
while (last > first && taps[last] == 0) last--;
|
||||
start[i] = first;
|
||||
count[i] = last - first + 1;
|
||||
for (var j = first; j <= last; j++) values[i * stride + j - first] = (float)(taps[j] / sum);
|
||||
}
|
||||
return new Weights { Length = target, Stride = stride, Start = start, Count = count, Values = values };
|
||||
}
|
||||
|
||||
private static double Lanczos3(double x)
|
||||
{
|
||||
x = Math.Abs(x);
|
||||
if (x < 1e-9) return 1;
|
||||
if (x >= 3) return 0;
|
||||
var px = Math.PI * x;
|
||||
return 3 * Math.Sin(px) * Math.Sin(px / 3) / (px * px);
|
||||
}
|
||||
|
||||
private static double CatmullRom(double x)
|
||||
{
|
||||
x = Math.Abs(x);
|
||||
return x < 1 ? (1.5 * x - 2.5) * x * x + 1
|
||||
: x < 2 ? ((-0.5 * x + 2.5) * x - 4) * x + 2
|
||||
: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user