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.

68 lines
2.1 KiB

8 years ago
8 years ago
8 years ago
  1. // Copyright 2016 Drew Short <drew@sothr.com>.
  2. //
  3. // Licensed under the MIT license<LICENSE-MIT or http://opensource.org/licenses/MIT>.
  4. // This file may not be copied, modified, or distributed except according to those terms.
  5. extern crate image;
  6. use std::path::Path;
  7. use cache::Cache;
  8. use super::{HashType, PerceptualHash, Precision, PreparedImage};
  9. use super::prepare_image;
  10. use self::image::{GenericImage, GenericImageView};
  11. pub struct AHash<'a> {
  12. prepared_image: Box<PreparedImage<'a>>,
  13. }
  14. impl<'a> AHash<'a> {
  15. pub fn new(path: &'a Path, precision: &Precision, cache: &Option<Cache>) -> Self {
  16. AHash {
  17. prepared_image: Box::new(prepare_image(&path, &HashType::AHash, &precision, cache)),
  18. }
  19. }
  20. }
  21. impl<'a> PerceptualHash for AHash<'a> {
  22. /**
  23. * Calculate the ahash of the provided prepared image.
  24. *
  25. * # Returns
  26. *
  27. * A u64 representing the value of the hash
  28. */
  29. fn get_hash(&self, _: &Option<Cache>) -> u64 {
  30. match self.prepared_image.image {
  31. Some(ref image) => {
  32. let (width, height) = image.dimensions();
  33. // calculating the average pixel value
  34. let mut total = 0u64;
  35. for (_, _, pixel) in image.pixels() {
  36. total += pixel.0[0] as u64;
  37. }
  38. let mean = total / (height * width) as u64;
  39. // println!("Mean for {} is {}", prepared_image.orig_path, mean);
  40. // Calculating a hash based on the mean
  41. let mut hash = 0u64;
  42. for (_, _, pixel) in image.pixels() {
  43. if pixel.0[0] as u64 >= mean {
  44. hash |= 1;
  45. // println!("Pixel {} is >= {} therefore {:b}", pixel_sum, mean, hash);
  46. } else {
  47. hash |= 0;
  48. // println!("Pixel {} is < {} therefore {:b}", pixel_sum, mean, hash);
  49. }
  50. hash <<= 1;
  51. }
  52. // println!("Hash for {} is {}", prepared_image.orig_path, hash);
  53. hash
  54. }
  55. None => 0u64,
  56. }
  57. }
  58. }