image_hash.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import cv2
  2. import khandy
  3. import numpy as np
  4. def _convert_bool_matrix_to_int(bool_mat):
  5. hash_val = int(0)
  6. for item in bool_mat.flatten():
  7. hash_val |= int(item)
  8. hash_val <<= 1
  9. hash_val >>= 1
  10. return hash_val
  11. def calc_image_ahash(image):
  12. """Average Hashing
  13. References:
  14. http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html
  15. """
  16. assert khandy.is_numpy_image(image)
  17. if image.ndim == 3:
  18. image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  19. resized = cv2.resize(image, (8, 8))
  20. mean_val = np.mean(resized)
  21. hash_mat = resized >= mean_val
  22. hash_val = _convert_bool_matrix_to_int(hash_mat)
  23. return hash_val
  24. def calc_image_dhash(image):
  25. """Difference Hashing
  26. References:
  27. http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html
  28. """
  29. assert khandy.is_numpy_image(image)
  30. if image.ndim == 3:
  31. image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  32. resized = cv2.resize(image, (9, 8))
  33. hash_mat = resized[:,:-1] >= resized[:,1:]
  34. hash_val = _convert_bool_matrix_to_int(hash_mat)
  35. return hash_val
  36. def calc_image_phash(image):
  37. """Perceptual Hashing
  38. References:
  39. http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html
  40. """
  41. assert khandy.is_numpy_image(image)
  42. if image.ndim == 3:
  43. image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  44. resized = cv2.resize(image, (32, 32))
  45. dct_coeff = cv2.dct(resized.astype(np.float32))
  46. reduced_dct_coeff = dct_coeff[:8, :8]
  47. # median of coefficients excluding the DC term (0th term)
  48. # mean_val = np.mean(reduced_dct_coeff.flatten()[1:])
  49. median_val = np.median(reduced_dct_coeff.flatten()[1:])
  50. hash_mat = reduced_dct_coeff >= median_val
  51. hash_val = _convert_bool_matrix_to_int(hash_mat)
  52. return hash_val