Add saliency-based smart crop before resize

Replace the center-crop cover resize with a Sobel edge-density search
that picks the target-aspect window with the most edge energy, so a
subject off-center isn't sliced when the input aspect differs from the
frame's. Failures fall back to the centered crop. Golden fixtures are
regenerated and an asymmetric-edges input exercises the bias.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
zyberzeroandClaude Opus 5.5 committed 2026-11-03 19:03:22 +01:00
1 parent 675d206234
commit ac9a0b43a8
24 files changed
+340 -24

No files matched your search

+32 -9
View File
@@ -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<Color> 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<Rgba32>(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<DitherAlgorithm, IDither>`.
4. **Remap** each pixel from `DisplayColor` → `DeviceColor`. Build a `Dictionary<Rgba32, Rgba32>` 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<Rgba32, Rgba32>` 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 a target-aspect window over the downscaled image at three sizes (100%, 85%, 70% of the max-fitting size) with an 8 px step, pick the position with maximum total edge energy.
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.