You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.9 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package com.sothr.imagetools.engine.hash
  2. import grizzled.slf4j.Logging
  3. /**
  4. * DHash algorithm class
  5. *
  6. * Created by Drew on 1/22/14.
  7. */
  8. object DHash extends PerceptualHasher with Logging {
  9. def getHash(imageData: Array[Array[Int]]): Long = {
  10. //debug("Generating DHash")
  11. val width = imageData.length
  12. val height = imageData(0).length
  13. //debug(s"Image data size: ${width}x${height}")
  14. //calculate dhash
  15. var hash = 0L
  16. var previousPixel = imageData(height - 1)(width - 1)
  17. var previousLocation = (height - 1, width - 1)
  18. if (height % 2 == 0) {
  19. previousPixel = imageData(height - 1)(0)
  20. previousLocation = (height - 1, 0)
  21. }
  22. for (row <- 0 until height by 2) {
  23. //process each column
  24. for (col <- 0 until width by 1) {
  25. hash <<= 1
  26. val pixel = imageData(row)(col)
  27. //debug(s"previousPixel: $previousPixel currentPixel: $pixel previousLocation: $previousLocation currentLocation: (${row},${col})")
  28. //binary of the current bit based on whether the value
  29. //of the current pixel is greater or equal to the previous pixel
  30. if (pixel >= previousPixel) hash |= 1 else hash |= 0
  31. //debug(s"(${row},${col})=$pixel hash=${hash.toBinaryString}")
  32. previousPixel = pixel
  33. previousLocation = (row, col)
  34. }
  35. if ((row + 1) < width) {
  36. val nextRow = row + 1
  37. //process each column
  38. for (col <- (width - 1) to 0 by -1) {
  39. hash <<= 1
  40. val pixel = imageData(nextRow)(col)
  41. //debug(s"previousPixel: $previousPixel currentPixel: $pixel previousLocation: $previousLocation currentLocation: (${nextRow},${col})")
  42. if (pixel >= previousPixel) hash |= 1 else hash |= 0
  43. //debug(s"(${row},${col})=$pixel hash=${hash.toBinaryString}")
  44. previousPixel = pixel
  45. previousLocation = (nextRow, col)
  46. }
  47. }
  48. }
  49. //debug(s"Computed DHash: $hash from ${width * height} pixels")
  50. hash
  51. }
  52. }