1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
use crate::{
    convert::Convert,
    math::{dct2_over_matrix, median, Axis},
    ImageHash, ImageHasher,
};

pub struct PerceptualHasher {
    /// The target width of the matrix
    pub width: u32,

    /// The target height of the matrix
    pub height: u32,

    /// The factor for the DCT matrix. We will rescale the image to (width * height) * 4
    /// before we calculate the DCT on it.
    pub factor: u32,
}

impl ImageHasher for PerceptualHasher {
    fn hash_from_img(&self, img: &image::DynamicImage) -> ImageHash {
        let high_freq = self.convert(img, self.width * self.factor, self.height * self.factor);

        // convert the higher frequency image to a matrix of f64
        let high_freq_bytes = high_freq.as_bytes().to_vec();
        let high_freq_matrix: Vec<Vec<f64>> = high_freq_bytes
            .chunks((self.width * self.factor) as usize)
            .map(|x| x.iter().map(|x| *x as f64).collect::<Vec<f64>>())
            .collect();

        // now we compute the DCT for each column and then for each row
        let dct_matrix = dct2_over_matrix(
            &dct2_over_matrix(&high_freq_matrix, Axis::Column),
            Axis::Row,
        );

        // now we crop the dct matrix to the actual target width and height
        let scaled_matrix: Vec<Vec<f64>> = dct_matrix
            .iter()
            .take(self.height as usize)
            .map(|row| row.iter().take(self.width as usize).cloned().collect())
            .collect();

        // compute the median over the flattend matrix
        let flattened: Vec<f64> = scaled_matrix.iter().flatten().copied().collect();
        let median = median(&flattened).unwrap();

        // compare each pixel of our scaled image to the mean
        let mut bits = vec![vec![false; self.width as usize]; self.height as usize];
        for (i, row) in scaled_matrix.iter().enumerate() {
            for (j, pixel) in row.iter().enumerate() {
                bits[i][j] = *pixel > median;
            }
        }

        ImageHash { matrix: bits }
    }
}

impl Default for PerceptualHasher {
    fn default() -> Self {
        PerceptualHasher {
            width: 8,
            height: 8,
            factor: 4,
        }
    }
}

impl Convert for PerceptualHasher {}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use image::io::Reader as ImageReader;

    use super::*;

    const TEST_IMG: &str = "./data/img/test.png";
    const TXT_FILE: &str = "./data/misc/test.txt";

    #[test]
    fn test_perceptual_hash_from_img() {
        // Arrange
        let img = ImageReader::open(Path::new(TEST_IMG))
            .unwrap()
            .decode()
            .unwrap();

        let hasher = PerceptualHasher {
            ..Default::default()
        };

        // Act
        let hash = hasher.hash_from_img(&img);

        // Assert
        assert_eq!(hash.encode(), "157d1d1b193c7c1c")
    }

    #[test]
    fn test_perceptual_hash_from_path() {
        // Arrange
        let hasher = PerceptualHasher {
            ..Default::default()
        };

        // Act
        let hash = hasher.hash_from_path(Path::new(TEST_IMG));

        // Assert
        match hash {
            Ok(hash) => assert_eq!(hash.encode(), "157d1d1b193c7c1c"),
            Err(err) => panic!("could not read image: {:?}", err),
        }
    }

    #[test]
    fn test_perceptual_hash_from_nonexisting_path() {
        // Arrange
        let hasher = PerceptualHasher {
            ..Default::default()
        };

        // Act
        let hash = hasher.hash_from_path(Path::new("./does/not/exist.png"));

        // Assert
        match hash {
            Ok(hash) => panic!("found hash for non-existing image: {:?}", hash),
            Err(_) => (),
        }
    }

    #[test]
    fn test_perceptual_hash_from_txt_file() {
        // Arrange
        let hasher = PerceptualHasher {
            ..Default::default()
        };

        // Act
        let hash = hasher.hash_from_path(Path::new(TXT_FILE));

        // Assert
        match hash {
            Ok(hash) => panic!("found hash for non-existing image: {:?}", hash),
            Err(_) => (),
        }
    }
}