Skip to content

Instantly share code, notes, and snippets.

@chak10
Last active October 27, 2024 10:59
Show Gist options
  • Save chak10/6a6a001fb907993470f93c61bf5937a0 to your computer and use it in GitHub Desktop.
Save chak10/6a6a001fb907993470f93c61bf5937a0 to your computer and use it in GitHub Desktop.
La funzione `combine_hashes_mode` è progettata per combinare hash di immagini utilizzando la modalità per ciascun bit. Questa funzione consente di gestire diversi hash generati da immagini simili, identificando anche immagini completamente nere o bianche.

README: combine_hashes_mode

Description

The combine_hashes_mode function is designed to combine image hashes using the mode for each bit. This function allows handling multiple hashes generated from similar images while also identifying completely black or white images.

Features

  • Combines image hashes: Uses the mode to generate a combined hash from multiple image hashes.
  • Checks for black and white images: Identifies if a hash represents a completely black or white image and reports it.
  • Error handling: The function includes robust checks to ensure that inputs are valid, raising appropriate exceptions in case of issues.

Parameters

The function accepts a variable number of arguments:

  • *hashes (ImageHash): Hash objects to combine. All hashes must have the same dimensions and must be of type ImageHash.

Returns

  • Returns a new ImageHash object that represents the combined hash of the provided images.

Interpretable

  • Distance 0: The images are identical.
  • Distance between 1 and 63: The images are similar but not identical. The greater the distance, the lesser the similarity.
  • Distance 64: The images have no similarity.

Exceptions

  • ValueError: If no hashes are provided or if the hashes do not have the same dimensions.
  • TypeError: If any input is not an ImageHash object.

Example Usage

hash1 = imagehash.phash(Image.open("path/to/image1.jpg"))
hash2 = imagehash.phash(Image.open("path/to/image2.jpg"))
combined_hash = combine_hashes_mode(hash1, hash2)
print("Combined hash:", combined_hash)
import imagehash
from PIL import Image
import numpy as np
def combine_hashes_mode(*hashes):
"""
Combina più hash di immagini utilizzando la modalità per ciascun bit.
Controlla anche se un'immagine è completamente nera o bianca.
Parameters:
*hashes (ImageHash): Gli oggetti hash da combinare.
Returns:
ImageHash: Un nuovo hash combinato secondo la modalità dei bit.
Raises:
ValueError: Se gli hash non hanno la stessa dimensione o se nessun hash è fornito.
TypeError: Se un input non è un oggetto ImageHash.
"""
# Controlla che ci siano hash forniti
if not hashes:
raise ValueError("Almeno un hash deve essere fornito per la combinazione.")
# Controlla che tutti gli hash abbiano la stessa dimensione e siano oggetti ImageHash
hash_shape = hashes[0].hash.shape
if not all(isinstance(h, imagehash.ImageHash) for h in hashes):
raise TypeError("Tutti gli input devono essere oggetti ImageHash.")
if not all(h.hash.shape == hash_shape for h in hashes):
raise ValueError("Tutti gli hash devono avere la stessa dimensione.")
# Converte gli hash in un array di interi
hash_arrays = np.array([h.hash.flatten() for h in hashes], dtype=int)
# Verifica se uno degli hash è di un'immagine nera o bianca
for idx, img_hash in enumerate(hashes):
if np.all(img_hash.hash == 0):
print(f"Hash per il frame {idx + 1} è Nera.")
elif np.all(img_hash.hash == 1):
print(f"Hash per il frame {idx + 1} è Bianca.")
# Calcola la modalità dei bit usando un approccio più veloce
combined_bits = (np.mean(hash_arrays, axis=0) > 0.5).astype(int)
# Ricrea l'hash come ImageHash nella forma originale
combined_hash = imagehash.ImageHash(combined_bits.reshape(hash_shape))
return combined_hash
Pillow==9.5.0
imagehash==4.3.1
numpy==1.23.5
scipy==1.10.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment