image_hash.py 1.2 KB

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