Created
December 1, 2022 17:58
-
-
Save rom1504/68e62921b1728f9e0539df7345eed8a8 to your computer and use it in GitHub Desktop.
phash.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from scipy.fftpack import dct | |
def hash_algo(pil_img, size=10): | |
""" | |
Get perceptual hash of the input image. | |
Args: | |
image_array: numpy array that corresponds to the image. | |
Returns: | |
A string representing the perceptual hash of the image. | |
""" | |
image_array = np.array(pil_img) | |
dct_coef = dct(dct(image_array, axis=0), axis=1) | |
dct_reduced_coef = dct_coef[:size, :size] | |
median_coef_val = np.median(np.ndarray.flatten(dct_reduced_coef)[1:]) | |
hash_mat = dct_reduced_coef >= median_coef_val | |
return hash_mat | |
def str_image_hash(pil_image): | |
hash_str = hash_algo(np.array(pil_image)) | |
return ''.join([str(v) for v in hash_str.astype('int').reshape(-1)]) | |
def bin_to_hex_hash_sim(bin_hash_str): | |
n = 4 | |
sub_strings = [format(int(bin_hash_str[i:i+n], 2), 'x') for i in range(0, len(bin_hash_str), n)] | |
return "".join(sub_strings) | |
def hex_to_bin_hash_sim(hex_hash_str): | |
n = 1 | |
sub_strings = [format(int(hex_hash_str[i:i+n], 16), 'b').zfill(4) for i in range(0, len(hex_hash_str), n)] | |
return "".join(sub_strings) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment