Similarity hashes of images and text, built to be stored

A Rust library that turns an image, or a piece of text, into a short string of bits, so that things which look or read alike get bits that mostly agree.

You store the bits. Later you compare them, and never open the files again.

Good crates already do this. This one is for the case where the hash is stored. Each algorithm is a written definition with a version in its name, and a released definition never changes its output: the same picture gives the same bits on every machine, this year and later. Each is tested, bit for bit, against the implementation it names.

Version
0.2.0, on crates.io
Reference
docs.rs/legit-hashes
Source
github.com/mferrara/legit-rs
Licence
MIT
Needs
Rust 1.99 or newer. Two small dependencies, siphasher and sha1; the image crate only if you ask for it.

One hash, taken apart

This is the simplest of the eight definitions, average-v1, on a picture that is dark on its left half and bright on its right.

1. Reduced to 8×8 pixels 2. Brighter than the mean? 0000111100001111000011110000111100001111000011110000111100001111 3. Each row, as hex 0000 1111→0f0000 1111→0f0000 1111→0f0000 1111→0f0000 1111→0f0000 1111→0f0000 1111→0f0000 1111→0f
The picture and its hash are one of the crate's own tests.
  1. The picture is reduced to 8×8 grey pixels. Here 32 of them have the value 10 and 32 have the value 200.
  2. The mean of the 64 values is 105. A pixel brighter than the mean is a 1, and any other is a 0.
  3. The bits are read row by row from the top left. Each row of eight bits is two hex digits.

The hash, as it would be stored:

average-v1:0f0f0f0f0f0f0f0f

The name in front is part of the value. Comparing it with a hash from another definition, or another version, is an error and never a number.

The eight definitions

Five for pictures, three for text
Name Gives What it is Agrees with
average-v164 bitsIs each pixel of the 8×8 picture brighter than the mean?Python ImageHash
difference-v164 bitsIs each pixel of the 9×8 picture darker than its right-hand neighbour?Python ImageHash
perceptual-v164 bitsIs each of the 64 lowest frequencies of the 32×32 picture above their median?Python ImageHash
pdq-v1256 bits and a quality scoreMeta's PDQ: 256 frequencies of a blurred 64×64 picture, each against their medianMeta's C++ reference
blockhash-v1256 bitsIs each of 16×16 blocks brighter than the median of its band? It sees transparency.blockhash-python
simhash-v164 bitsFor text: each bit is a vote among the words, or runs of characters, that have it setits own written definition
minhash-v1128 numbersFor text and other sets: the share of numbers two signatures have in common estimates their overlapdatasketch 2
minhash-legacy-v1128 numbersThe same, as datasketch computed it before its version 2datasketch before 2

The guide says which to choose. The evaluation shows the agreement being checked.

Using it

cargo add legit-hashes

Add --features image to hash PNG and JPEG files.

A picture, from a file or from pixels you already have:

use legit_hashes::{Algorithm, Hash, LumaBuf, perceptual_v1};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // From a PNG or JPEG file, with the `image` feature...
    let file = std::fs::read("upload.jpg")?;
    let hash = Algorithm::PerceptualV1.hash_encoded(&file)?;

    // ...or from RGB pixels, three bytes a pixel.
    let (width, height, rgb) = (2, 1, [255, 0, 0, 0, 0, 255]);
    let from_pixels = perceptual_v1(
        LumaBuf::from_rgb8_v1(width, height, &rgb)?.view(),
    );

    // Store the string form; it names the definition and its version.
    let stored = hash.to_string(); // "perceptual-v1:…"

    let earlier: Hash = stored.parse()?;
    if from_pixels.distance(&earlier)? <= 8 {
        println!("a near match");
    }
    Ok(())
}

The 8 in that example is only an example. Where to draw the line is the guide's longest section.

PDQ, with its quality score:

use legit_hashes::{RgbaBuf, pdq_v1};

fn main() -> legit_hashes::Result<()> {
    let (width, height) = (64, 48);
    let rgb: Vec<u8> = (0..width * height * 3)
        .map(|i| (i * 7 % 251) as u8)
        .collect();
    let image = RgbaBuf::from_rgb8(width, height, &rgb)?;

    let pdq = pdq_v1(image.view());
    if pdq.quality > 49 {
        println!("{}", pdq.hash); // "pdq-v1:…", 64 hex digits
    }
    Ok(())
}

Two short texts, by how much of them is shared:

use legit_hashes::minhash_v1_shingles;

fn main() -> legit_hashes::Result<()> {
    let first = minhash_v1_shingles(
        "your parcel is waiting: confirm your address today", 5,
    )?;
    let second = minhash_v1_shingles(
        "your parcel is waiting: confirm your adress today!", 5,
    )?;
    println!("about {:.2} shared", first.similarity(&second)?);

    let keys = first.band_keys_i64(32)?; // 32 keys for indexed columns
    println!("{}", keys.len());
    Ok(())
}

What it does not do

The README has the full definitions, the credits, and why this was written when good crates exist.

The square beside the crate's name is simhash-v1:b606786c6db3f4d9, the hash of this page's opening sentence, computed by the crate as the page was served. Each page here has its own.