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.

232 lines
8.1 KiB

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