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
2.0 KiB

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