legit-hashes 0.2.0

Versioned similarity hashes of images and text, and MinHash set signatures, with index keys for finding near matches
Documentation
//! `average-v1` and `difference-v1`, the integer image hashes.

use crate::luma::downscale;
use crate::{Algorithm, Hash, Luma};

/// Hash an image with `average-v1`, the average hash.
///
/// The definition, frozen:
///
/// 1. Reduce the image to 8×8 with [`Luma::downscale_v1`].
/// 2. For each of the 64 pixels, row by row from the top left, the bit is set when
///    `pixel * 64 > sum of all 64 pixels`: when the pixel is strictly brighter than the mean, in
///    exact integer arithmetic.
///
/// The first bit is the most significant bit of the hash. A flat image hashes to all zeros.
///
/// ```
/// use legit_hashes::{Luma, average_v1};
///
/// // Dark on the left, light on the right...
/// let pixels: Vec<u8> = (0..64).map(|i| if i % 8 < 4 { 0 } else { 255 }).collect();
/// let hash = average_v1(Luma::new(8, 8, &pixels)?);
/// assert_eq!(hash.to_hex(), "0f0f0f0f0f0f0f0f");
/// # Ok::<(), legit_hashes::Error>(())
/// ```
#[must_use]
pub fn average_v1(image: Luma<'_>) -> Hash {
    let pixels = downscale(image, 8, 8);
    let sum: u32 = pixels.iter().map(|&pixel| u32::from(pixel)).sum();
    let bits = pixels
        .iter()
        .fold(0, |bits, &pixel| bits << 1 | u64::from(u32::from(pixel) * 64 > sum));
    Hash::from_bits(Algorithm::AverageV1, bits)
}

/// Hash an image with `difference-v1`, the difference hash.
///
/// The definition, frozen:
///
/// 1. Reduce the image to 9 wide by 8 high with [`Luma::downscale_v1`].
/// 2. For each row from the top, and each column `col` from 0 to 7, the bit is set when
///    `pixel[row][col + 1] > pixel[row][col]`: when the right neighbour is strictly brighter.
///
/// The first bit is the most significant bit of the hash. A flat image hashes to all zeros.
///
/// ```
/// use legit_hashes::{Luma, difference_v1};
///
/// // Brighter to the right on every row...
/// let pixels: Vec<u8> = (0..72).map(|i| (i % 9 * 20) as u8).collect();
/// let hash = difference_v1(Luma::new(9, 8, &pixels)?);
/// assert_eq!(hash.to_hex(), "ffffffffffffffff");
/// # Ok::<(), legit_hashes::Error>(())
/// ```
#[must_use]
pub fn difference_v1(image: Luma<'_>) -> Hash {
    let pixels = downscale(image, 9, 8);
    let (rows, _) = pixels.as_chunks::<9>();
    let bits = rows
        .iter()
        .flat_map(|row| row.windows(2))
        .fold(0, |bits, pair| bits << 1 | u64::from(pair[1] > pair[0]));
    Hash::from_bits(Algorithm::DifferenceV1, bits)
}