Files
Febe/src/Febe.Core/Library/PerceptualHash.cs
T
Alby96andClaude Opus 5.5 7e8296e790 Correzioni della revisione dei codec di casa (C1)
Correggo i difetti confermati dalla revisione di funzione/codec-immagini e
aggiungo le prove che li avrebbero trovati.

- JPEG: una tabella di Huffman con troppi codici corti dava
  ArgumentOutOfRangeException invece di ImageDecodeException, e un file
  rovinato faceva fallire importazione e ricostruzione; ora il controllo si
  fa prima di scrivere le voci. La prova che diceva di coprirlo cadeva invece
  su «tabella troncata»: ora tiene il totale giusto e controlla il messaggio.
- JPEG: il troncamento delle scansioni di Huffman si vede a ogni riga di MCU,
  non dopo l'ultimo MCU (un file tagliato dopo le intestazioni costava 6,7 s).
- JPEG: IDCT ridotta a 1/2 e 1/4 calcolata dai coefficienti; miniatura di una
  foto 4000x3000 da 126 a 59 ms in Release. Il predittore senza perdita non
  cerca più l'indice della componente a ogni campione.
- WebP: con livello del filtro del fotogramma 0 il filtro è spento, come nei
  decodificatori di riferimento; VP8L costruisce solo i gruppi nominati dai
  meta codici (prima fino a 335 MB di tabelle da 160 KB di file).
- BMP OS/2: altezza senza segno e sempre dal basso.
- Array di lavoro dei codec oltre 16 MiB fuori dal pool condiviso, che li
  avrebbe tenuti dopo l'uso.
- Conversione: profilo ICC copiato solo se RGB, profondità oltre 8 bit e
  blocchi gAMA/cHRM/sRGB dichiarati in NotCarried, Lossy vero quando si perde
  precisione.
- Impronta e misure di una foto da una sola lettura e decodifica; ReadSize
  legge solo l'inizio di JPEG, GIF e BMP.
- docs: decisioni (righe aggiunte, con la correzione dei 2,0 MB del set di
  riferimento) e windows.md (Febe.exe rimisurato: 85,6 MB, a capo sistemato).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 16:52:17 +01:00

242 lines
8.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Numerics;
using Febe.Core.Codecs.Images;
namespace Febe.Core.Library;
/// <summary>
/// 64-bit perceptual hash of photos (spec §8.4, «impronta visiva»): the classic DCT pHash.
/// <list type="number">
/// <item>the image is decoded upright and reduced to 32×32 grey levels by area averaging (aspect ratio is not kept:
/// resizing does not change the hash);</item>
/// <item>a 2-D DCT-II is computed and the 8×8 lowest frequencies are kept;</item>
/// <item>each of the 64 coefficients gives a bit: 1 when above the median of the 64.</item>
/// </list>
/// Two photos are probable duplicates when the Hamming distance of their hashes is at most
/// <see cref="DuplicateThreshold"/>. Videos have no perceptual hash: for them only SHA-256 counts (spec §9.3).
/// </summary>
public static class PerceptualHash
{
/// <summary>
/// Maximum Hamming distance (out of 64 bits) for two photos to be probable duplicates.
/// <para>
/// Calibrated on 2026-10-13 by <c>Febe.Tests.Library.PerceptualHashTests</c> on 24 generated scenes (gradients,
/// shapes, lines and grain; 1200×900 and 900×1200), each compared with its variants:
/// <list type="bullet">
/// <item>resized to 50%, 25%, 8% (96 px) and 150%, recompressed as JPEG at quality 95, 70, 40 and 20, resized to a
/// third and recompressed twice, saved as PNG: largest distance <b>4</b> (only the 96-px reduction; all others ≤ 2);</item>
/// <item>cropped — central 80%, 75% and 60% of each side, one side cut by 10% or 25%, top third removed, square and
/// 4:5 crops, a corner quarter: smallest distance <b>8</b>;</item>
/// <item>different scenes: smallest distance <b>20</b> (average 31).</item>
/// </list>
/// Every hash has exactly 32 bits set (median split), so distances are always even: 6 sits in the middle of the
/// gap between 4 and 8. A very light crop (5% on every side) measured 6–18 and may be proposed as a duplicate:
/// the pair is only shown to Alberto, never resolved automatically (rule 12).
/// </para>
/// </summary>
public const int DuplicateThreshold = 6;
private const int Size = 32;
private const int Low = 8;
/// <summary>A JPEG is decoded reduced, but never below this long side.</summary>
private const int MinDecodedSide = 256;
private static readonly double[,] Cosines = BuildCosines();
/// <summary>Hamming distance between two hashes (0–64).</summary>
public static int Distance(ulong a, ulong b) => BitOperations.PopCount(a ^ b);
/// <summary>True when two hashes are within <see cref="DuplicateThreshold"/>.</summary>
public static bool AreSimilar(ulong a, ulong b, int threshold = DuplicateThreshold) => Distance(a, b) <= threshold;
/// <summary>Hash of an encoded image; null when the content is not a decodable image.</summary>
public static ulong? Compute(Stream encodedImage)
{
ArgumentNullException.ThrowIfNull(encodedImage);
using var image = ImageDecoding.DecodeUpright(encodedImage, minLongSide: MinDecodedSide);
return image is null ? null : Compute(image);
}
/// <summary>Hash of an image file; null when it is not a decodable image.</summary>
public static ulong? ComputeFromFile(string path)
{
using var stream = File.OpenRead(path);
return Compute(stream);
}
/// <summary>
/// Hash and size as shown of an encoded image from one decode of the same bytes; each null when it cannot be had
/// (a damaged file may still give its size).
/// </summary>
internal static (ulong? Hash, (int Width, int Height)? Size) ComputeWithSize(ReadOnlyMemory<byte> encodedImage)
{
using var image = ImageDecoding.DecodeUpright(encodedImage, MinDecodedSide, out var size);
return (image is null ? null : Compute(image), size);
}
/// <summary>Like <see cref="ComputeWithSize(ReadOnlyMemory{byte})"/> for a file, read once.</summary>
internal static (ulong? Hash, (int Width, int Height)? Size) ComputeWithSizeFromFile(string path)
{
byte[]? data;
using (var stream = File.OpenRead(path))
{
data = ImageDecoding.ReadAll(stream);
}
return data is null ? (null, null) : ComputeWithSize(data);
}
/// <summary>Hash of a decoded image (any size), upright as it is shown.</summary>
internal static ulong Compute(RgbaImage image)
{
ArgumentNullException.ThrowIfNull(image);
return HashOf(AreaResample(image, Size, Size));
}
/// <summary>The hash of a 32×32 grey image (row-major).</summary>
internal static ulong HashOf(double[] pixels)
{
// Separable DCT-II, only the 8 lowest frequencies in each direction.
var rows = new double[Size * Low];
for (var y = 0; y < Size; y++)
{
for (var u = 0; u < Low; u++)
{
double sum = 0;
for (var x = 0; x < Size; x++)
{
sum += pixels[(y * Size) + x] * Cosines[u, x];
}
rows[(y * Low) + u] = sum;
}
}
var coefficients = new double[Low * Low];
for (var v = 0; v < Low; v++)
{
for (var u = 0; u < Low; u++)
{
double sum = 0;
for (var y = 0; y < Size; y++)
{
sum += rows[(y * Low) + u] * Cosines[v, y];
}
coefficients[(v * Low) + u] = sum;
}
}
var sorted = (double[])coefficients.Clone();
Array.Sort(sorted);
var median = (sorted[31] + sorted[32]) / 2;
ulong hash = 0;
for (var i = 0; i < coefficients.Length; i++)
{
if (coefficients[i] > median)
{
hash |= 1UL << i;
}
}
return hash;
}
/// <summary>
/// The grey levels (0–255, over white: <see cref="ImageGray.LumaOverWhite"/>) of an image reduced to dw × dh by area
/// averaging, one source row at a time (memory: one row and dw × source height values).
/// </summary>
internal static double[] AreaResample(RgbaImage image, int dw, int dh)
{
var sw = image.Width;
var sh = image.Height;
var xs = Weights(sw, dw);
var horizontal = new double[dw * sh];
var grey = new double[sw];
for (var y = 0; y < sh; y++)
{
ImageGray.LumaOverWhite(image.GetRow(y), grey);
for (var dx = 0; dx < dw; dx++)
{
double sum = 0;
foreach (var (index, weight) in xs[dx])
{
sum += grey[index] * weight;
}
horizontal[(y * dw) + dx] = sum;
}
}
return Vertical(horizontal, sh, dw, dh);
}
private static double[] Vertical(double[] horizontal, int sh, int dw, int dh)
{
var result = new double[dw * dh];
var ys = Weights(sh, dh);
for (var dy = 0; dy < dh; dy++)
{
for (var dx = 0; dx < dw; dx++)
{
double sum = 0;
foreach (var (index, weight) in ys[dy])
{
sum += horizontal[(index * dw) + dx] * weight;
}
result[(dy * dw) + dx] = sum;
}
}
return result;
}
/// <summary>For each target cell, the source cells it covers and their normalized weights.</summary>
private static List<(int Index, double Weight)>[] Weights(int sourceLength, int targetLength)
{
var scale = (double)sourceLength / targetLength;
var weights = new List<(int, double)>[targetLength];
for (var t = 0; t < targetLength; t++)
{
var start = t * scale;
var end = start + scale;
var list = new List<(int, double)>();
if (scale <= 1)
{
// Enlarging: nearest source cell by centre.
list.Add((Math.Min(sourceLength - 1, (int)((t + 0.5) * scale)), 1.0));
}
else
{
for (var s = (int)Math.Floor(start); s < Math.Ceiling(end) && s < sourceLength; s++)
{
var overlap = Math.Min(end, s + 1) - Math.Max(start, s);
if (overlap > 0)
{
list.Add((s, overlap / scale));
}
}
}
weights[t] = list;
}
return weights;
}
private static double[,] BuildCosines()
{
var table = new double[Low, Size];
for (var u = 0; u < Low; u++)
{
for (var x = 0; x < Size; x++)
{
table[u, x] = Math.Cos(((2 * x) + 1) * u * Math.PI / (2 * Size));
}
}
return table;
}
}