imagehash Documentation

repository·master·Indexed 26 days ago

https://github.com/johannesbuchner/imagehash

A Python library for generating image fingerprints (hashes) to find visually similar images. It provides several algorithms including average_hash, phash, dhash, whash, colorhash, and crop_resistant_hash, allowing for hash comparison via Hamming distance.

Tokens
767
Snippets
3
Records
4
Agent score
37%

What's inside imagehash

  1. Basic usage of image hashing algorithms

    master

    Use imagehash to generate hashes from PIL Image objects. You can compare hashes using the == operator or calculate the Hamming distance using the - operator. Most algorithms allow adjusting the hashsize to increase sensitivity to detail.

    from PIL import Image
    import imagehash
    
    hash = imagehash.average_hash(Image.open('tests/data/imagehash.png'))
    print(hash)
    
    otherhash = imagehash.average_hash(Image.open('tests/data/peppers.png'))
    print(otherhash)
    
    # Check if identical
    print(hash == otherhash)
    
    # Calculate hamming distance
    print(hash - otherhash)
  2. Convert hashes to strings and back

    master

    To store hashes in a database or text format, convert them to strings using str(). To restore them, use the specific restoration function corresponding to the algorithm used:

    • For single perceptual hashes: imagehash.hex_to_hash(string)
    • For crop-resistant hashes: imagehash.hex_to_multihash(string)
    • For color hashes: imagehash.hex_to_flathash(string, hashsize=...)
    # Perceptual hash
    original_hash = imagehash.phash(Image.open('tests/data/imagehash.png'))
    hash_as_str = str(original_hash)
    restored_hash = imagehash.hex_to_hash(hash_as_str)
    
    # Crop-resistant hash
    original_hash = imagehash.crop_resistant_hash(Image.open('tests/data/imagehash.png'), min_segment_size=500, segmentation_image_size=1000)
    hash_as_str = str(original_hash)
    restored_hash = imagehash.hex_to_multihash(hash_as_str)
    
    # Color hash
    original_hash = imagehash.colorhash(Image.open('tests/data/imagehash.png'), binbits=3)
    hash_as_str = str(original_hash)
    restored_hash = imagehash.hex_to_flathash(hash_as_str, hashsize=3)
  3. Available hashing algorithms

    master

    The library provides several algorithms for image fingerprinting:

    • average_hash: Average hashing
    • phash: Perceptual hashing
    • dhash: Difference hashing
    • whash: Wavelet hashing
    • colorhash: HSV color hashing (uses binbits parameter)
    • crop_resistant_hash: Crop-resistant hashing