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.

235 lines
8.2 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::dft;
  10. use super::dft::Transform;
  11. use super::image::Pixel;
  12. use super::prepare_image;
  13. use self::image::{DynamicImage, GenericImage, GenericImageView};
  14. pub struct PHash<'a> {
  15. prepared_image: Box<PreparedImage<'a>>,
  16. }
  17. impl<'a> PHash<'a> {
  18. pub fn new(path: &'a Path, precision: &Precision, cache: &Option<Cache>) -> Self {
  19. PHash {
  20. prepared_image: Box::new(prepare_image(&path, &HashType::PHash, &precision, cache)),
  21. }
  22. }
  23. }
  24. impl<'a> PerceptualHash for PHash<'a> {
  25. /**
  26. * Calculate the phash of the provided prepared image
  27. *
  28. * # Return
  29. *
  30. * Returns a u64 representing the value of the hash
  31. */
  32. fn get_hash(&self, cache: &Option<Cache>) -> u64 {
  33. match self.prepared_image.image {
  34. Some(ref image) => {
  35. // Get the image data into a vector to perform the DFT on.
  36. let (width, height) = image.dimensions();
  37. // Get 2d data to 2d FFT/DFT
  38. // Either from the cache or calculate it
  39. // Pretty fast already, so caching doesn't make a huge difference
  40. // Atleast compared to opening and processing the images
  41. let data_matrix: Vec<Vec<f64>> = match *cache {
  42. Some(ref c) => {
  43. match c.get_matrix_from_cache(&Path::new(self.prepared_image.orig_path),
  44. width as u32) {
  45. Some(matrix) => matrix,
  46. None => {
  47. let matrix = create_data_matrix(width, height, &image);
  48. match c.put_matrix_in_cache(&Path::new(self.prepared_image.orig_path),
  49. width as u32,
  50. &matrix) {
  51. Ok(_) => {}
  52. Err(e) => println!("Unable to store matrix in cache. {}", e),
  53. };
  54. matrix
  55. }
  56. }
  57. }
  58. None => create_data_matrix(width, height, &image),
  59. };
  60. // Only need the top left quadrant
  61. let target_width = (width / 4) as usize;
  62. let target_height = (height / 4) as usize;
  63. let dft_width = (width / 4) as f64;
  64. let dft_height = (height / 4) as f64;
  65. // Calculate the mean
  66. let mut total = 0f64;
  67. for x in 0..target_width {
  68. for y in 0..target_height {
  69. total += data_matrix[x][y];
  70. }
  71. }
  72. let mean = total / (dft_width * dft_height);
  73. // Calculating a hash based on the mean
  74. let mut hash = 0u64;
  75. for x in 0..target_width {
  76. for y in 0..target_height {
  77. if data_matrix[x][y] >= mean {
  78. hash |= 1;
  79. } else {
  80. hash |= 0;
  81. }
  82. hash <<= 1;
  83. }
  84. }
  85. hash
  86. }
  87. None => 0u64,
  88. }
  89. }
  90. }
  91. fn create_data_matrix(width: u32,
  92. height: u32,
  93. image: &DynamicImage)
  94. -> Vec<Vec<f64>> {
  95. let mut data_matrix: Vec<Vec<f64>> = Vec::new();
  96. // Preparing the results
  97. for x in 0..width as usize {
  98. data_matrix.push(Vec::new());
  99. for y in 0..height {
  100. let pos_x = x as u32;
  101. let pos_y = y as u32;
  102. data_matrix[x].push(image.get_pixel(pos_x, pos_y).channels()[0] as f64);
  103. }
  104. }
  105. // Perform the 2D DFT operation on our matrix
  106. calculate_2d_dft(&mut data_matrix);
  107. data_matrix
  108. }
  109. // Use a 1D DFT to cacluate the 2D DFT.
  110. //
  111. // This is achieved by calculating the DFT for each row, then calculating the
  112. // DFT for each column of DFT row data. This means that a 32x32 image with have
  113. // 1024 1D DFT operations performed on it. (Slightly caclulation intensive)
  114. //
  115. // This operation is in place on the data in the provided vector
  116. //
  117. // Inspired by:
  118. // http://www.inf.ufsc.br/~visao/khoros/html-dip/c5/s2/front-page.html
  119. //
  120. // Checked with:
  121. // http://calculator.vhex.net/post/calculator-result/2d-discrete-fourier-transform
  122. //
  123. fn calculate_2d_dft(data_matrix: &mut Vec<Vec<f64>>) {
  124. // println!("{:?}", data_matrix);
  125. let width = data_matrix.len();
  126. let height = data_matrix[0].len();
  127. let mut complex_data_matrix = Vec::with_capacity(width);
  128. // Perform DCT on the columns of data
  129. for x in 0..width {
  130. let mut column: Vec<f64> = Vec::with_capacity(height);
  131. for y in 0..height {
  132. column.push(data_matrix[x][y]);
  133. }
  134. // Perform the DCT on this column
  135. // println!("column[{}] before: {:?}", x, column);
  136. let forward_plan = dft::Plan::new(dft::Operation::Forward, column.len());
  137. column.transform(&forward_plan);
  138. let complex_column = dft::unpack(&column);
  139. // println!("column[{}] after: {:?}", x, complex_column);
  140. complex_data_matrix.push(complex_column);
  141. }
  142. // Perform DCT on the rows of data
  143. for y in 0..height {
  144. let mut row = Vec::with_capacity(width);
  145. for x in 0..width {
  146. row.push(complex_data_matrix[x][y]);
  147. }
  148. // Perform DCT on the row
  149. // println!("row[{}] before: {:?}", y, row);
  150. let forward_plan = dft::Plan::new(dft::Operation::Forward, row.len());
  151. row.transform(&forward_plan);
  152. // println!("row[{}] after: {:?}", y, row);
  153. // Put the row values back
  154. for x in 0..width {
  155. data_matrix[x][y] = round_float(row[x].re);
  156. }
  157. }
  158. }
  159. fn round_float(f: f64) -> f64 {
  160. if f >= super::FLOAT_PRECISION_MAX_1 || f <= super::FLOAT_PRECISION_MIN_1 {
  161. f
  162. } else if f >= super::FLOAT_PRECISION_MAX_2 || f <= super::FLOAT_PRECISION_MIN_2 {
  163. (f * 10_f64).round() / 10_f64
  164. } else if f >= super::FLOAT_PRECISION_MAX_3 || f <= super::FLOAT_PRECISION_MIN_3 {
  165. (f * 100_f64).round() / 100_f64
  166. } else if f >= super::FLOAT_PRECISION_MAX_4 || f <= super::FLOAT_PRECISION_MIN_4 {
  167. (f * 1000_f64).round() / 1000_f64
  168. } else if f >= super::FLOAT_PRECISION_MAX_5 || f <= super::FLOAT_PRECISION_MIN_5 {
  169. (f * 10000_f64).round() / 10000_f64
  170. } else {
  171. (f * 100000_f64).round() / 100000_f64
  172. }
  173. }
  174. #[test]
  175. fn test_2d_dft() {
  176. let mut test_matrix: Vec<Vec<f64>> = Vec::new();
  177. test_matrix.push(vec![1f64, 1f64, 1f64, 3f64]);
  178. test_matrix.push(vec![1f64, 2f64, 2f64, 1f64]);
  179. test_matrix.push(vec![1f64, 2f64, 2f64, 1f64]);
  180. test_matrix.push(vec![3f64, 1f64, 1f64, 1f64]);
  181. println!("{:?}", test_matrix[0]);
  182. println!("{:?}", test_matrix[1]);
  183. println!("{:?}", test_matrix[2]);
  184. println!("{:?}", test_matrix[3]);
  185. println!("Performing 2d DFT");
  186. calculate_2d_dft(&mut test_matrix);
  187. println!("{:?}", test_matrix[0]);
  188. println!("{:?}", test_matrix[1]);
  189. println!("{:?}", test_matrix[2]);
  190. println!("{:?}", test_matrix[3]);
  191. assert!(test_matrix[0][0] == 24_f64);
  192. assert!(test_matrix[0][1] == 0_f64);
  193. assert!(test_matrix[0][2] == 0_f64);
  194. assert!(test_matrix[0][3] == 0_f64);
  195. assert!(test_matrix[1][0] == 0_f64);
  196. assert!(test_matrix[1][1] == 0_f64);
  197. assert!(test_matrix[1][2] == -2_f64);
  198. assert!(test_matrix[1][3] == 2_f64);
  199. assert!(test_matrix[2][0] == 0_f64);
  200. assert!(test_matrix[2][1] == -2_f64);
  201. assert!(test_matrix[2][2] == -4_f64);
  202. assert!(test_matrix[2][3] == -2_f64);
  203. assert!(test_matrix[3][0] == 0_f64);
  204. assert!(test_matrix[3][1] == 2_f64);
  205. assert!(test_matrix[3][2] == -2_f64);
  206. assert!(test_matrix[3][3] == 0_f64);
  207. }