Skip to content

Instantly share code, notes, and snippets.

@angeligareta
Last active December 31, 2023 17:06
Show Gist options
  • Save angeligareta/144d9809b9020794a64ec4370452b217 to your computer and use it in GitHub Desktop.
Save angeligareta/144d9809b9020794a64ec4370452b217 to your computer and use it in GitHub Desktop.
DHash Image Hashing algorithm with z-transformation
# Inspired from https://github.com/JohannesBuchner/imagehash repository
import imagehash
from PIL import Image
def alpharemover(image):
if image.mode != 'RGBA':
return image
canvas = Image.new('RGBA', image.size, (255,255,255,255))
canvas.paste(image, mask=image)
return canvas.convert('RGB')
def with_ztransform_preprocess(hashfunc, hash_size=8):
def function(path):
image = alpharemover(Image.open(path))
image = image.convert("L").resize((hash_size, hash_size), Image.ANTIALIAS)
data = image.getdata()
quantiles = np.arange(100)
quantiles_values = np.percentile(data, quantiles)
zdata = (np.interp(data, quantiles_values, quantiles) / 100 * 255).astype(np.uint8)
image.putdata(zdata)
return hashfunc(image)
return function
dhash_z_transformed = with_ztransform_preprocess(imagehash.dhash, hash_size = 8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment