Skip to content

Instantly share code, notes, and snippets.

@marcan
Created August 19, 2021 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcan/1ced459c5f501323ce588f6f1402e08d to your computer and use it in GitHub Desktop.
Save marcan/1ced459c5f501323ce588f6f1402e08d to your computer and use it in GitHub Desktop.
import numpy, math
N = 32 # image size
M = 8 # number of DCT coefficients
def dcthash(data):
k = math.sqrt(2.0 / N)
dct_k = numpy.matrix([
[k * math.cos((math.pi / 2 / N) * y * (2 * x + 1)) for x in range(N)]
for y in range(M)
])
dct_k_t = numpy.transpose(dct_k)
coefs = numpy.array(dct_k * data * dct_k_t).flatten()
h = sum((1<<i) for i,j in enumerate(coefs) if j > 0)
return h
if __name__ == "__main__":
import sys
from PIL import Image
im = Image.open(sys.argv[1])
rim = im.convert("L").resize((N, N), resample=Image.BILINEAR)
data = numpy.array(rim)
print("%016x" % dcthash(data))
import timeit
t=timeit.timeit(lambda: im.convert("L").resize((N, N), resample=Image.BILINEAR), number=1000)
print(f"Resize: {1000/t}/sec")
t2=timeit.timeit(lambda: dcthash(data), number=1000)
print(f"Hash: {1000/t2}/sec")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment