image_hash.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import cv2
  2. import khandy
  3. import numpy as np
  4. def calc_image_ahash(image):
  5. assert khandy.is_numpy_image(image)
  6. if image.ndim == 3:
  7. image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  8. resized = cv2.resize(image, (8, 8))
  9. meanval = cv2.mean(resized)[0]
  10. hashval = int(0)
  11. for i in range(8):
  12. for j in range(8):
  13. mask = int(resized[i,j] - meanval >= 1e-5)
  14. hashval |= mask << (i * 8 + j)
  15. return hashval
  16. def calc_image_phash(image):
  17. assert khandy.is_numpy_image(image)
  18. if image.ndim == 3:
  19. image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  20. resized = cv2.resize(image, (32, 32))
  21. dft = cv2.dft(resized.astype(np.float32))
  22. meanval = cv2.mean(dft[:8,:8])[0]
  23. hashval = int(0)
  24. for i in range(8):
  25. for j in range(8):
  26. mask = int(dft[i,j] - meanval >= 1e-5)
  27. hashval |= mask << (i * 8 + j)
  28. return hashval
  29. def calc_image_dhash(image):
  30. assert khandy.is_numpy_image(image)
  31. if image.ndim == 3:
  32. image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  33. resized = cv2.resize(image, (9, 8))
  34. hashval = int(0)
  35. for i in range(8):
  36. for j in range(8):
  37. mask = int(resized[i,j] > resized[i,j+1])
  38. hashval |= mask << (i * 8 + j)
  39. return hashval