diff --git a/IMPLEMENTATION.md b/IMPLEMENTATION.md index add3577..659613e 100644 --- a/IMPLEMENTATION.md +++ b/IMPLEMENTATION.md @@ -105,16 +105,22 @@ Each type lives in `src/FrameProcessor/Domain/`. Tests in `tests/FrameProcessor. ### [x] 3.3 `IImagePipeline` + `ImagePipeline` - Single method: `byte[] Process(Stream input, Frame frame)`. -- Steps (`SPEC.md` §3.2): decode → resize (cover/center-crop to oriented resolution) → dither against display palette → remap pixels display→device → rotate 90° CW if portrait → encode indexed PNG (`PngColorType.Palette`, smallest bit depth fitting the palette, `PaletteQuantizer(deviceColors)`). +- Steps (`SPEC.md` §3.2): decode → smart crop to oriented aspect (see 3.5) → resize to oriented resolution → dither against display palette → remap pixels display→device → rotate 90° CW if portrait → encode indexed PNG (`PngColorType.Palette`, smallest bit depth fitting the palette, `PaletteQuantizer(deviceColors)`). - Output dimensions always match the frame's *declared* `width × height` regardless of orientation. ### [x] 3.4 `ImagePipelineTests` golden fixtures -- Check in `tests/FrameProcessor.Tests/Fixtures/inputs/` (landscape.jpg, portrait.jpg, tiny-1x1.png, non-divisible.jpg). +- Check in `tests/FrameProcessor.Tests/Fixtures/inputs/` (landscape.jpg, portrait.jpg, tiny-1x1.png, non-divisible.jpg, asymmetric-edges.jpg). - Generate expected outputs once, commit under `Fixtures/expected//.png`. - Assert byte-equality of produced PNG vs golden. - Run for all four dithering algorithms against the canonical Spectra 6 palette. - **DoD:** `dotnet test` green; deleting a fixture output and rerunning fails loud. +### [x] 3.5 Smart crop (`PLAN.md` "Smart cropping") +- `ISmartCropper` + `SaliencySmartCropper`: Sobel edge density on a 256 px analysis canvas, summed-area table, slide the max-fitting target-aspect window, keep the highest-energy position. +- Same-aspect inputs return full bounds; any exception logs a warning and falls back to the centered max-fitting crop. +- `ImagePipeline` applies the crop, then a pure `Resize` to the oriented resolution. +- **Tests:** `SaliencySmartCropperTests` (bias on both axes, edge-hugging subject, bounds/aspect); `asymmetric-edges.jpg` golden fixture. + --- ## Phase 4 — Storage @@ -173,7 +179,7 @@ Each type lives in `src/FrameProcessor/Domain/`. Tests in `tests/FrameProcessor. - On reconnect, drain immediately. - **Manual check:** stop broker, upload → 200 with `mqttPublished: false`; restart broker → `mosquitto_sub` sees the message within backoff window. -### [ ] 6.6 Reliable auto-reconnect (`SPEC.md` §5.2) +### [x] 6.6 Reliable auto-reconnect (`SPEC.md` §5.2) - `MqttOptions`: `ReconnectBackoffSeconds`, `KeepAliveSeconds`, `ConnectTimeoutSeconds`; wire keep-alive + connect timeout into `BuildClientOptions()`. - `DisconnectedAsync` handler logs the reason and signals a `_reconnect` channel; only `ExecuteAsync` calls `ConnectAsync`. - Reconnect loop uses the backoff schedule (capped, reset on success) instead of the hardcoded 5 s poll; wakes the retry queue on success. diff --git a/PLAN.md b/PLAN.md index 6b3b3ea..f55ebc7 100644 --- a/PLAN.md +++ b/PLAN.md @@ -49,9 +49,12 @@ src/FrameProcessor/ HealthController.cs // GET /health ImagePipeline/ IImagePipeline.cs - ImagePipeline.cs // scale → dither → remap → encode (indexed PNG) + ImagePipeline.cs // smart-crop → resize → dither → remap → encode (indexed PNG) PaletteFactory.cs // builds ImageSharp ReadOnlyMemory from PaletteEntry list DitheringRegistry.cs // maps DitherAlgorithm → IDither + SmartCrop/ + ISmartCropper.cs // computes a crop rect in source coordinates + SaliencySmartCropper.cs // Sobel edge-density saliency search Mqtt/ MqttPublisher.cs // persistent MQTTnet client, QoS 1, background retry queue Storage/ @@ -154,19 +157,39 @@ Validation on load: name URL-safe, MAC parses to 6 bytes, palette has ≥2 entri For each upload: 1. **Load** the input via ImageSharp (`Image.Load(stream)`). -2. **Resize** with `ResizeMode.Crop` (center-crop cover) to the frame's resolution — swap W/H if `orientation == portrait`. -3. **Dither** against a palette built from the already-parsed `DisplayColor` of each `PaletteEntry`, using the configured dither algorithm: +2. **Smart crop** — `ISmartCropper.ComputeCropRect` picks a source-coordinate rectangle whose aspect matches the frame's oriented resolution (W/H swapped for portrait). If aspects already match within tolerance, the full source bounds is returned and no crop is applied. Otherwise the crop is applied via `Crop(rect)`. See "Smart cropping" below. +3. **Resize** to the frame's oriented resolution. Aspects already match after the smart crop, so this is a pure scale (no cover/crop semantics needed). +4. **Dither** against a palette built from the already-parsed `DisplayColor` of each `PaletteEntry`, using the configured dither algorithm: ```csharp var displayPalette = frame.Palette.Select(p => p.DisplayColor).ToArray(); img.Mutate(x => x.Dither(ditherings[frame.Dithering], displayPalette)); ``` `frame.Dithering` is a `DitherAlgorithm` enum; `ditherings` is `IReadOnlyDictionary`. -4. **Remap** each pixel from `DisplayColor` → `DeviceColor`. Build a `Dictionary` once per frame from the palette and do a single pixel-buffer pass. Since the dither in step 3 produces only palette colors, every pixel finds a mapping. -5. **Rotate** 90° if `orientation == portrait` so the output PNG is always `width × height` as declared (e.g., 1600×1200), with content rotated for portrait mounting. -6. **Encode** as **indexed PNG** (`PngColorType.Palette`, `PngBitDepth.Bit4` — fits 6 colors in a nibble). ImageSharp's `PngEncoder` with `Quantizer = new PaletteQuantizer(deviceColorPalette)` produces this in one call. -7. **Atomic write**: `{tmpPath} → {finalPath}` via `File.Move(..., overwrite: true)` so the GET endpoint never sees a half-written file. +5. **Remap** each pixel from `DisplayColor` → `DeviceColor`. Build a `Dictionary` once per frame from the palette and do a single pixel-buffer pass. Since the dither in step 4 produces only palette colors, every pixel finds a mapping. +6. **Rotate** 90° if `orientation == portrait` so the output PNG is always `width × height` as declared (e.g., 1600×1200), with content rotated for portrait mounting. +7. **Encode** as **indexed PNG** (`PngColorType.Palette`, `PngBitDepth.Bit4` — fits 6 colors in a nibble). ImageSharp's `PngEncoder` with `Quantizer = new PaletteQuantizer(deviceColorPalette)` produces this in one call. +8. **Atomic write**: `{tmpPath} → {finalPath}` via `File.Move(..., overwrite: true)` so the GET endpoint never sees a half-written file. -`IImagePipeline` is a single injected service. Encapsulates 1–6 and returns the bytes; `ImageStore` does step 7. +`IImagePipeline` is a single injected service. Encapsulates 1–7 and returns the bytes; `ImageStore` does step 8. + +### Smart cropping + +A hard center crop slices the subject in half when going between landscape and portrait. The pipeline instead picks the crop window by Sobel edge density — edge-rich regions tend to coincide with the photo's subject (faces, in particular, contribute a lot of edges via eyes, nose, and hair). + +Algorithm (`SaliencySmartCropper`): + +1. If source aspect matches target aspect within ~0.5%, return full source bounds — no crop needed. +2. Compute the **max-fitting centered rect** at the target aspect. This is the upper bound on crop size and the fallback if any later step throws. +3. Downscale a clone of the source to **256 px on the long edge** (cheap analysis canvas). +4. Compute per-pixel **Sobel magnitude** on Rec. 601 luma, build a **summed-area table** for O(1) rectangle sums. +5. Slide the max-fitting target-aspect window over the downscaled image with an 8 px step (always including the last position on each axis, so edge-hugging subjects aren't missed), pick the position with maximum total edge energy. Only one window size is searched: edge energy is non-negative, so a smaller window can never outscore a larger one containing it. +6. Scale the winning rect back to source coordinates, clamp to image bounds, return. + +Failure mode: the whole `ComputeCropRect` is wrapped in `try/catch`; on any exception we log a warning and return the centered max-fitting rect. A bad photo must never 500 the upload — same doctrine as MQTT failure being non-fatal. + +Determinism: pure managed integer/float math, no native deps, no ML model. Golden-image byte equality holds across runs. + +No configuration knob in v1 — smart crop is always on, and same-aspect inputs hit the zero-cost fast path. --- @@ -190,7 +213,7 @@ For each upload: `tests/FrameProcessor.Tests` (xUnit + ImageSharp): -- **`ImagePipelineTests`** — golden-image fixtures. Check in 3-4 small test inputs (`landscape.jpg`, `portrait.jpg`, `tiny-1x1.png`, `non-divisible.jpg`) and expected outputs for one canonical Spectra 6 palette. Assert byte-equality of the indexed PNG output. ImageSharp dither output is deterministic for a given input/palette/algorithm, so this is a strong correctness anchor. +- **`ImagePipelineTests`** — golden-image fixtures. Check in synthetic test inputs (`landscape.jpg`, `portrait.jpg`, `tiny-1x1.png`, `non-divisible.jpg`, `asymmetric-edges.jpg`) and expected outputs for one canonical Spectra 6 palette. Assert byte-equality of the indexed PNG output. The pipeline (dither + smart crop) is deterministic for a given input/palette/algorithm, so this is a strong correctness anchor. `asymmetric-edges.jpg` exercises the saliency search by placing a high-edge checkerboard on one half of the source and flat gray on the other — the smart crop must bias toward the edge-rich half. - **`PaletteFactoryTests`** — hex parsing, count, error messages on bad hex. - **`MacAddressTests`** — round-trip: `"AA:BB:CC:DD:EE:FF"`, `"aa-bb-cc-dd-ee-ff"`, `"AABBCCDDEEFF"`, and surrounding whitespace all parse to the same value; `ToString()` always emits the canonical lowercase-no-separator form; equality compares on the 6 bytes. - **`FrameNameTests`** — accepts URL-safe names, rejects names with reserved or whitespace characters with a clear error. diff --git a/SPEC.md b/SPEC.md index 00c3759..9b882ac 100644 --- a/SPEC.md +++ b/SPEC.md @@ -32,13 +32,14 @@ Both forms produce identical downstream behavior. For each accepted image, the service performs the following stages in order: 1. **Decode** the input into an in-memory RGBA bitmap. -2. **Resize** to the frame's resolution using `cover` semantics — scale the input so it fully covers the target rectangle, then center-crop overflow. Aspect ratio is preserved; no stretching. -3. **Dither** the bitmap against a palette built from the frame's `color` (display) values, using the dithering algorithm configured for that frame. Output of this stage contains only colors from the display palette. -4. **Remap** each pixel from its display color to its corresponding `deviceColor` per the palette. Output of this stage contains only colors from the device-color palette. -5. **Rotate** the bitmap 90° clockwise if the frame's orientation is `portrait`. The output dimensions always match the frame's declared resolution (e.g., 1600×1200) regardless of orientation. -6. **Encode** as an **indexed PNG** with a palette of the frame's device colors, using the smallest bit depth that fits the palette size. -7. **Persist** the resulting PNG to storage, replacing any previous image for the same frame **atomically** (no half-written file is ever observable via the HTTP fetch endpoint). -8. **Notify** by publishing an MQTT message announcing that a new image is available. +2. **Smart crop** to the frame's target aspect ratio. The service selects the source-coordinate crop rectangle by saliency (Sobel edge density): the rectangle of target aspect with the highest total edge energy is kept. This preserves the most visually interesting region of the source when the input aspect ratio differs from the frame's. If the input already matches the frame's aspect ratio (within a small tolerance), no cropping is performed. Smart-crop failure is non-fatal: on any internal error the service falls back to a centered max-fitting crop and logs a warning — a difficult photo never fails the upload. +3. **Resize** the cropped bitmap to the frame's resolution. Aspect ratio is preserved by the preceding crop, so this stage is a pure scale. +4. **Dither** the bitmap against a palette built from the frame's `color` (display) values, using the dithering algorithm configured for that frame. Output of this stage contains only colors from the display palette. +5. **Remap** each pixel from its display color to its corresponding `deviceColor` per the palette. Output of this stage contains only colors from the device-color palette. +6. **Rotate** the bitmap 90° clockwise if the frame's orientation is `portrait`. The output dimensions always match the frame's declared resolution (e.g., 1600×1200) regardless of orientation. +7. **Encode** as an **indexed PNG** with a palette of the frame's device colors, using the smallest bit depth that fits the palette size. +8. **Persist** the resulting PNG to storage, replacing any previous image for the same frame **atomically** (no half-written file is ever observable via the HTTP fetch endpoint). +9. **Notify** by publishing an MQTT message announcing that a new image is available. ### 3.3 Output delivery diff --git a/src/FrameProcessor/ImagePipeline/ImagePipeline.cs b/src/FrameProcessor/ImagePipeline/ImagePipeline.cs index dc6e615..7c4ddd7 100644 --- a/src/FrameProcessor/ImagePipeline/ImagePipeline.cs +++ b/src/FrameProcessor/ImagePipeline/ImagePipeline.cs @@ -1,4 +1,5 @@ using FrameProcessor.Domain; +using FrameProcessor.ImagePipeline.SmartCrop; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.PixelFormats; @@ -9,6 +10,13 @@ namespace FrameProcessor.ImagePipeline; public sealed class ImagePipeline : IImagePipeline { + private readonly ISmartCropper _smartCropper; + + public ImagePipeline(ISmartCropper smartCropper) + { + _smartCropper = smartCropper; + } + public byte[] Process(Stream input, Frame frame) { ArgumentNullException.ThrowIfNull(input); @@ -21,13 +29,14 @@ public sealed class ImagePipeline : IImagePipeline using var image = Image.Load(input); + var crop = _smartCropper.ComputeCropRect(image, oriented.Width, oriented.Height); + if (crop != image.Bounds) + { + image.Mutate(ctx => ctx.Crop(crop)); + } + image.Mutate(ctx => ctx - .Resize(new ResizeOptions - { - Size = new Size(oriented.Width, oriented.Height), - Mode = ResizeMode.Crop, - Position = AnchorPositionMode.Center, - }) + .Resize(oriented.Width, oriented.Height) .Dither(dither, displayPalette)); RemapDisplayToDevice(image, frame.Palette); diff --git a/src/FrameProcessor/ImagePipeline/SmartCrop/ISmartCropper.cs b/src/FrameProcessor/ImagePipeline/SmartCrop/ISmartCropper.cs new file mode 100644 index 0000000..18f1dc1 --- /dev/null +++ b/src/FrameProcessor/ImagePipeline/SmartCrop/ISmartCropper.cs @@ -0,0 +1,20 @@ +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; + +namespace FrameProcessor.ImagePipeline.SmartCrop; + +/// +/// Picks the source-coordinate crop rectangle to apply before resizing an +/// input image to a frame's target resolution. Implementations may use +/// saliency or other heuristics to keep the most interesting region. +/// +public interface ISmartCropper +{ + /// + /// Returns a crop rectangle in 's coordinate + /// space whose aspect ratio matches : + /// . If the source already matches the + /// target aspect, returns the full source bounds. + /// + Rectangle ComputeCropRect(Image source, int targetWidth, int targetHeight); +} diff --git a/src/FrameProcessor/ImagePipeline/SmartCrop/SaliencySmartCropper.cs b/src/FrameProcessor/ImagePipeline/SmartCrop/SaliencySmartCropper.cs new file mode 100644 index 0000000..0425e1d --- /dev/null +++ b/src/FrameProcessor/ImagePipeline/SmartCrop/SaliencySmartCropper.cs @@ -0,0 +1,221 @@ +using Microsoft.Extensions.Logging; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; + +namespace FrameProcessor.ImagePipeline.SmartCrop; + +/// +/// Smart cropper that picks the region with the highest Sobel edge density. +/// Edge-rich regions tend to coincide with the photo's subject (including +/// faces, which are high in edge content from eyes, nose and hair), so this +/// is a face-detection-free proxy for "the interesting part of the image". +/// +public sealed class SaliencySmartCropper : ISmartCropper +{ + private const double AspectMatchTolerance = 0.005; + private const int SmallLongEdge = 256; + private const int SlideStep = 8; + + private readonly ILogger _logger; + + public SaliencySmartCropper(ILogger logger) + { + _logger = logger; + } + + public Rectangle ComputeCropRect(Image source, int targetWidth, int targetHeight) + { + ArgumentNullException.ThrowIfNull(source); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(targetWidth); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(targetHeight); + + try + { + return ComputeInternal(source, targetWidth, targetHeight); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Smart crop failed; falling back to centered crop."); + return MaxFittingCenteredRect(source.Width, source.Height, (double)targetWidth / targetHeight); + } + } + + private static Rectangle ComputeInternal(Image source, int targetWidth, int targetHeight) + { + var srcW = source.Width; + var srcH = source.Height; + var tgtAspect = (double)targetWidth / targetHeight; + var srcAspect = (double)srcW / srcH; + + if (Math.Abs(srcAspect - tgtAspect) / tgtAspect < AspectMatchTolerance) + { + return source.Bounds; + } + + var fallback = MaxFittingCenteredRect(srcW, srcH, tgtAspect); + if (fallback.Width < 4 || fallback.Height < 4) + { + return fallback; + } + + var (smallW, smallH) = SmallDimensions(srcW, srcH); + using var small = source.Clone(ctx => ctx.Resize(smallW, smallH)); + + var mag = ComputeSobelMagnitude(small); + var sat = BuildSat(mag, smallW, smallH); + + // Only the max-fitting window size is searched: edge energy is + // non-negative, so a smaller window never outscores a larger one + // containing it. + var smallMaxRect = MaxFittingCenteredRect(smallW, smallH, tgtAspect); + var winW = smallMaxRect.Width; + var winH = smallMaxRect.Height; + if (winW < 2 || winH < 2) + { + return fallback; + } + + var maxX = smallW - winW; + var maxY = smallH - winH; + var stride = smallW + 1; + var bestSmallRect = smallMaxRect; + double bestEnergy = -1; + + // Step by SlideStep but always visit the last position, so a subject + // touching the right/bottom edge isn't cut by grid misalignment. + for (var y = 0; ; y = Math.Min(y + SlideStep, maxY)) + { + for (var x = 0; ; x = Math.Min(x + SlideStep, maxX)) + { + var energy = SumRect(sat, stride, x, y, x + winW, y + winH); + if (energy > bestEnergy) + { + bestEnergy = energy; + bestSmallRect = new Rectangle(x, y, winW, winH); + } + + if (x == maxX) + { + break; + } + } + + if (y == maxY) + { + break; + } + } + + var sx = (double)srcW / smallW; + var sy = (double)srcH / smallH; + var x0 = (int)Math.Round(bestSmallRect.X * sx); + var y0 = (int)Math.Round(bestSmallRect.Y * sy); + var x1 = (int)Math.Round((bestSmallRect.X + bestSmallRect.Width) * sx); + var y1 = (int)Math.Round((bestSmallRect.Y + bestSmallRect.Height) * sy); + + x0 = Math.Clamp(x0, 0, srcW - 1); + y0 = Math.Clamp(y0, 0, srcH - 1); + x1 = Math.Clamp(x1, x0 + 1, srcW); + y1 = Math.Clamp(y1, y0 + 1, srcH); + + return new Rectangle(x0, y0, x1 - x0, y1 - y0); + } + + private static (int W, int H) SmallDimensions(int srcW, int srcH) + { + if (srcW >= srcH) + { + var w = Math.Min(SmallLongEdge, srcW); + var h = Math.Max(1, (int)Math.Round((double)srcH * w / srcW)); + return (w, h); + } + else + { + var h = Math.Min(SmallLongEdge, srcH); + var w = Math.Max(1, (int)Math.Round((double)srcW * h / srcH)); + return (w, h); + } + } + + private static Rectangle MaxFittingCenteredRect(int srcW, int srcH, double tgtAspect) + { + var srcAspect = (double)srcW / srcH; + int cropW, cropH; + if (srcAspect >= tgtAspect) + { + cropH = srcH; + cropW = Math.Min(srcW, (int)Math.Round(srcH * tgtAspect)); + } + else + { + cropW = srcW; + cropH = Math.Min(srcH, (int)Math.Round(srcW / tgtAspect)); + } + + var x = (srcW - cropW) / 2; + var y = (srcH - cropH) / 2; + return new Rectangle(x, y, cropW, cropH); + } + + private static float[] ComputeSobelMagnitude(Image img) + { + var w = img.Width; + var h = img.Height; + var lum = new byte[w * h]; + + img.ProcessPixelRows(accessor => + { + for (var y = 0; y < accessor.Height; y++) + { + var row = accessor.GetRowSpan(y); + var off = y * w; + for (var x = 0; x < row.Length; x++) + { + var p = row[x]; + // Rec. 601 luma (integer-fixed to keep determinism across runtimes). + lum[off + x] = (byte)((p.R * 299 + p.G * 587 + p.B * 114 + 500) / 1000); + } + } + }); + + var mag = new float[w * h]; + for (var y = 1; y < h - 1; y++) + { + for (var x = 1; x < w - 1; x++) + { + var i = y * w + x; + int a = lum[i - w - 1], b = lum[i - w], c = lum[i - w + 1]; + int d = lum[i - 1], e = lum[i + 1]; + int f = lum[i + w - 1], g = lum[i + w], hh = lum[i + w + 1]; + + var gx = (c + 2 * e + hh) - (a + 2 * d + f); + var gy = (f + 2 * g + hh) - (a + 2 * b + c); + mag[i] = Math.Abs(gx) + Math.Abs(gy); + } + } + return mag; + } + + private static double[] BuildSat(float[] mag, int w, int h) + { + var stride = w + 1; + var sat = new double[stride * (h + 1)]; + for (var y = 0; y < h; y++) + { + double rowSum = 0; + for (var x = 0; x < w; x++) + { + rowSum += mag[y * w + x]; + sat[(y + 1) * stride + (x + 1)] = sat[y * stride + (x + 1)] + rowSum; + } + } + return sat; + } + + private static double SumRect(double[] sat, int stride, int x0, int y0, int x1, int y1) + => sat[y1 * stride + x1] + - sat[y0 * stride + x1] + - sat[y1 * stride + x0] + + sat[y0 * stride + x0]; +} diff --git a/src/FrameProcessor/Program.cs b/src/FrameProcessor/Program.cs index 85b9963..e885468 100644 --- a/src/FrameProcessor/Program.cs +++ b/src/FrameProcessor/Program.cs @@ -2,6 +2,7 @@ using System.Net; using FrameProcessor.Concurrency; using FrameProcessor.Configuration; using FrameProcessor.ImagePipeline; +using FrameProcessor.ImagePipeline.SmartCrop; using FrameProcessor.Middleware; using FrameProcessor.Mqtt; using FrameProcessor.Storage; @@ -150,6 +151,7 @@ builder.Services.AddOptions() .Bind(builder.Configuration); builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/tests/FrameProcessor.Tests/Fixtures/expected/atkinson/asymmetric-edges.png b/tests/FrameProcessor.Tests/Fixtures/expected/atkinson/asymmetric-edges.png new file mode 100644 index 0000000..24a0199 Binary files /dev/null and b/tests/FrameProcessor.Tests/Fixtures/expected/atkinson/asymmetric-edges.png differ diff --git a/tests/FrameProcessor.Tests/Fixtures/expected/atkinson/landscape.png b/tests/FrameProcessor.Tests/Fixtures/expected/atkinson/landscape.png index 3f562b1..8e00cd6 100644 Binary files a/tests/FrameProcessor.Tests/Fixtures/expected/atkinson/landscape.png and b/tests/FrameProcessor.Tests/Fixtures/expected/atkinson/landscape.png differ diff --git a/tests/FrameProcessor.Tests/Fixtures/expected/atkinson/non-divisible.png b/tests/FrameProcessor.Tests/Fixtures/expected/atkinson/non-divisible.png index 3822d8f..9f5d0cc 100644 Binary files a/tests/FrameProcessor.Tests/Fixtures/expected/atkinson/non-divisible.png and b/tests/FrameProcessor.Tests/Fixtures/expected/atkinson/non-divisible.png differ diff --git a/tests/FrameProcessor.Tests/Fixtures/expected/atkinson/portrait.png b/tests/FrameProcessor.Tests/Fixtures/expected/atkinson/portrait.png index 92903fe..3e8b92a 100644 Binary files a/tests/FrameProcessor.Tests/Fixtures/expected/atkinson/portrait.png and b/tests/FrameProcessor.Tests/Fixtures/expected/atkinson/portrait.png differ diff --git a/tests/FrameProcessor.Tests/Fixtures/expected/floyd-steinberg/asymmetric-edges.png b/tests/FrameProcessor.Tests/Fixtures/expected/floyd-steinberg/asymmetric-edges.png new file mode 100644 index 0000000..0f36425 Binary files /dev/null and b/tests/FrameProcessor.Tests/Fixtures/expected/floyd-steinberg/asymmetric-edges.png differ diff --git a/tests/FrameProcessor.Tests/Fixtures/expected/floyd-steinberg/landscape.png b/tests/FrameProcessor.Tests/Fixtures/expected/floyd-steinberg/landscape.png index 7e0daee..35cc838 100644 Binary files a/tests/FrameProcessor.Tests/Fixtures/expected/floyd-steinberg/landscape.png and b/tests/FrameProcessor.Tests/Fixtures/expected/floyd-steinberg/landscape.png differ diff --git a/tests/FrameProcessor.Tests/Fixtures/expected/floyd-steinberg/non-divisible.png b/tests/FrameProcessor.Tests/Fixtures/expected/floyd-steinberg/non-divisible.png index 1454e2b..aa4a341 100644 Binary files a/tests/FrameProcessor.Tests/Fixtures/expected/floyd-steinberg/non-divisible.png and b/tests/FrameProcessor.Tests/Fixtures/expected/floyd-steinberg/non-divisible.png differ diff --git a/tests/FrameProcessor.Tests/Fixtures/expected/floyd-steinberg/portrait.png b/tests/FrameProcessor.Tests/Fixtures/expected/floyd-steinberg/portrait.png index cf260b4..c860a69 100644 Binary files a/tests/FrameProcessor.Tests/Fixtures/expected/floyd-steinberg/portrait.png and b/tests/FrameProcessor.Tests/Fixtures/expected/floyd-steinberg/portrait.png differ diff --git a/tests/FrameProcessor.Tests/Fixtures/expected/jarvis/asymmetric-edges.png b/tests/FrameProcessor.Tests/Fixtures/expected/jarvis/asymmetric-edges.png new file mode 100644 index 0000000..b91feac Binary files /dev/null and b/tests/FrameProcessor.Tests/Fixtures/expected/jarvis/asymmetric-edges.png differ diff --git a/tests/FrameProcessor.Tests/Fixtures/expected/jarvis/landscape.png b/tests/FrameProcessor.Tests/Fixtures/expected/jarvis/landscape.png index 9d9e352..50357aa 100644 Binary files a/tests/FrameProcessor.Tests/Fixtures/expected/jarvis/landscape.png and b/tests/FrameProcessor.Tests/Fixtures/expected/jarvis/landscape.png differ diff --git a/tests/FrameProcessor.Tests/Fixtures/expected/jarvis/non-divisible.png b/tests/FrameProcessor.Tests/Fixtures/expected/jarvis/non-divisible.png index c1cd0eb..ed48bee 100644 Binary files a/tests/FrameProcessor.Tests/Fixtures/expected/jarvis/non-divisible.png and b/tests/FrameProcessor.Tests/Fixtures/expected/jarvis/non-divisible.png differ diff --git a/tests/FrameProcessor.Tests/Fixtures/expected/jarvis/portrait.png b/tests/FrameProcessor.Tests/Fixtures/expected/jarvis/portrait.png index edf479a..4b73910 100644 Binary files a/tests/FrameProcessor.Tests/Fixtures/expected/jarvis/portrait.png and b/tests/FrameProcessor.Tests/Fixtures/expected/jarvis/portrait.png differ diff --git a/tests/FrameProcessor.Tests/Fixtures/expected/stucki/asymmetric-edges.png b/tests/FrameProcessor.Tests/Fixtures/expected/stucki/asymmetric-edges.png new file mode 100644 index 0000000..c5919b5 Binary files /dev/null and b/tests/FrameProcessor.Tests/Fixtures/expected/stucki/asymmetric-edges.png differ diff --git a/tests/FrameProcessor.Tests/Fixtures/expected/stucki/landscape.png b/tests/FrameProcessor.Tests/Fixtures/expected/stucki/landscape.png index a94c2eb..cbd1362 100644 Binary files a/tests/FrameProcessor.Tests/Fixtures/expected/stucki/landscape.png and b/tests/FrameProcessor.Tests/Fixtures/expected/stucki/landscape.png differ diff --git a/tests/FrameProcessor.Tests/Fixtures/expected/stucki/non-divisible.png b/tests/FrameProcessor.Tests/Fixtures/expected/stucki/non-divisible.png index 3d3555d..d402f92 100644 Binary files a/tests/FrameProcessor.Tests/Fixtures/expected/stucki/non-divisible.png and b/tests/FrameProcessor.Tests/Fixtures/expected/stucki/non-divisible.png differ diff --git a/tests/FrameProcessor.Tests/Fixtures/expected/stucki/portrait.png b/tests/FrameProcessor.Tests/Fixtures/expected/stucki/portrait.png index face582..df04694 100644 Binary files a/tests/FrameProcessor.Tests/Fixtures/expected/stucki/portrait.png and b/tests/FrameProcessor.Tests/Fixtures/expected/stucki/portrait.png differ diff --git a/tests/FrameProcessor.Tests/Fixtures/inputs/asymmetric-edges.jpg b/tests/FrameProcessor.Tests/Fixtures/inputs/asymmetric-edges.jpg new file mode 100644 index 0000000..8677efd Binary files /dev/null and b/tests/FrameProcessor.Tests/Fixtures/inputs/asymmetric-edges.jpg differ diff --git a/tests/FrameProcessor.Tests/ImagePipelineTests.cs b/tests/FrameProcessor.Tests/ImagePipelineTests.cs index 2ec7604..035280d 100644 --- a/tests/FrameProcessor.Tests/ImagePipelineTests.cs +++ b/tests/FrameProcessor.Tests/ImagePipelineTests.cs @@ -1,6 +1,8 @@ using System.Runtime.CompilerServices; using FrameProcessor.Domain; using FrameProcessor.ImagePipeline; +using FrameProcessor.ImagePipeline.SmartCrop; +using Microsoft.Extensions.Logging.Abstractions; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Jpeg; using SixLabors.ImageSharp.Formats.Png; @@ -35,8 +37,12 @@ public class ImagePipelineTests "portrait.jpg", "tiny-1x1.png", "non-divisible.jpg", + "asymmetric-edges.jpg", }; + private static FrameProcessor.ImagePipeline.ImagePipeline CreatePipeline() + => new(new SaliencySmartCropper(NullLogger.Instance)); + public static IEnumerable AllCombinations() { foreach (var algo in Enum.GetValues()) @@ -61,7 +67,7 @@ public class ImagePipelineTests $"Missing golden fixture: {expectedPath}. Regenerate by running 'UPDATE_GOLDEN=1 dotnet test'."); var frame = LandscapeFrame with { Dithering = algorithm }; - var pipeline = new FrameProcessor.ImagePipeline.ImagePipeline(); + var pipeline = CreatePipeline(); using var stream = File.OpenRead(inputPath); var actual = pipeline.Process(stream, frame); var expected = File.ReadAllBytes(expectedPath); @@ -79,7 +85,7 @@ public class ImagePipelineTests WriteInputFixtures(); - var pipeline = new FrameProcessor.ImagePipeline.ImagePipeline(); + var pipeline = CreatePipeline(); foreach (var algorithm in Enum.GetValues()) { foreach (var input in InputNames) @@ -106,6 +112,45 @@ public class ImagePipelineTests WriteJpeg(Path.Combine(inputsDir, "portrait.jpg"), 1200, 1600); WriteJpeg(Path.Combine(inputsDir, "non-divisible.jpg"), 1234, 789); WriteTinyPng(Path.Combine(inputsDir, "tiny-1x1.png")); + WriteAsymmetricEdges(Path.Combine(inputsDir, "asymmetric-edges.jpg")); + } + + private static void WriteAsymmetricEdges(string path) + { + // 1600x900 (aspect ~1.78) processed by a 1600x1200 landscape frame + // (aspect ~1.33) requires horizontal cropping. Left half is flat gray + // (low edge energy); right half is an 8x8 black/white checkerboard + // (high edge energy). Saliency should bias the crop window toward the + // checkerboard side. + const int width = 1600; + const int height = 900; + using var image = new Image(width, height); + var gray = new Rgba32(0x80, 0x80, 0x80, 0xFF); + var black = new Rgba32(0x00, 0x00, 0x00, 0xFF); + var white = new Rgba32(0xFF, 0xFF, 0xFF, 0xFF); + image.ProcessPixelRows(accessor => + { + for (var y = 0; y < accessor.Height; y++) + { + var row = accessor.GetRowSpan(y); + for (var x = 0; x < row.Length; x++) + { + if (x < width / 2) + { + row[x] = gray; + } + else + { + var cellX = (x - width / 2) / 8; + var cellY = y / 8; + row[x] = ((cellX + cellY) & 1) == 0 ? black : white; + } + } + } + }); + var encoder = new JpegEncoder { Quality = 90 }; + using var fs = File.Create(path); + image.SaveAsJpeg(fs, encoder); } private static void WriteJpeg(string path, int width, int height) diff --git a/tests/FrameProcessor.Tests/SaliencySmartCropperTests.cs b/tests/FrameProcessor.Tests/SaliencySmartCropperTests.cs new file mode 100644 index 0000000..1f8e184 --- /dev/null +++ b/tests/FrameProcessor.Tests/SaliencySmartCropperTests.cs @@ -0,0 +1,112 @@ +using FrameProcessor.ImagePipeline.SmartCrop; +using Microsoft.Extensions.Logging.Abstractions; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; + +namespace FrameProcessor.Tests; + +public class SaliencySmartCropperTests +{ + public enum Side { Left, Right, Top, Bottom } + + private static readonly SaliencySmartCropper Cropper = new(NullLogger.Instance); + + [Fact] + public void SameAspect_ReturnsFullBounds() + { + using var image = CreateHalfCheckerboard(1600, 1200, Side.Right); + var rect = Cropper.ComputeCropRect(image, 800, 600); + Assert.Equal(image.Bounds, rect); + } + + [Theory] + [InlineData(Side.Right)] + [InlineData(Side.Left)] + public void WideSource_BiasesTowardEdgeRichSide(Side side) + { + using var image = CreateHalfCheckerboard(1600, 900, side); + var rect = Cropper.ComputeCropRect(image, 1600, 1200); + + var centeredX = (image.Width - rect.Width) / 2; + if (side == Side.Right) + { + Assert.True(rect.X > centeredX, $"Expected crop right of center, got X={rect.X}"); + } + else + { + Assert.True(rect.X < centeredX, $"Expected crop left of center, got X={rect.X}"); + } + AssertValidCrop(image, rect, 1600, 1200); + } + + [Theory] + [InlineData(Side.Bottom)] + [InlineData(Side.Top)] + public void TallSource_BiasesTowardEdgeRichSide(Side side) + { + using var image = CreateHalfCheckerboard(900, 1600, side); + var rect = Cropper.ComputeCropRect(image, 1600, 1200); + + var centeredY = (image.Height - rect.Height) / 2; + if (side == Side.Bottom) + { + Assert.True(rect.Y > centeredY, $"Expected crop below center, got Y={rect.Y}"); + } + else + { + Assert.True(rect.Y < centeredY, $"Expected crop above center, got Y={rect.Y}"); + } + AssertValidCrop(image, rect, 1600, 1200); + } + + [Fact] + public void EdgeHuggingSubject_CropReachesSourceEdge() + { + using var image = CreateHalfCheckerboard(1600, 900, Side.Right); + var rect = Cropper.ComputeCropRect(image, 1600, 1200); + Assert.Equal(image.Width, rect.Right); + } + + [Fact] + public void PortraitTargetOnLandscapeSource_ReturnsValidRect() + { + using var image = CreateHalfCheckerboard(1600, 1200, Side.Right); + var rect = Cropper.ComputeCropRect(image, 1200, 1600); + AssertValidCrop(image, rect, 1200, 1600); + } + + private static void AssertValidCrop(Image image, Rectangle rect, int targetWidth, int targetHeight) + { + Assert.True(image.Bounds.Contains(rect), $"Crop {rect} outside source bounds {image.Bounds}"); + var expectedAspect = (double)targetWidth / targetHeight; + var actualAspect = (double)rect.Width / rect.Height; + Assert.InRange(actualAspect, expectedAspect * 0.99, expectedAspect * 1.01); + } + + private static Image CreateHalfCheckerboard(int width, int height, Side side) + { + var image = new Image(width, height); + var gray = new Rgba32(0x80, 0x80, 0x80, 0xFF); + var black = new Rgba32(0x00, 0x00, 0x00, 0xFF); + var white = new Rgba32(0xFF, 0xFF, 0xFF, 0xFF); + image.ProcessPixelRows(accessor => + { + for (var y = 0; y < accessor.Height; y++) + { + var row = accessor.GetRowSpan(y); + for (var x = 0; x < row.Length; x++) + { + var edgy = side switch + { + Side.Left => x < width / 2, + Side.Right => x >= width / 2, + Side.Top => y < height / 2, + _ => y >= height / 2, + }; + row[x] = !edgy ? gray : (((x / 8) + (y / 8)) & 1) == 0 ? black : white; + } + } + }); + return image; + } +}