fast_dhash/
lib.rs

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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
//! # Fast DHash
//!
//! A fast rust implementation of the perceptual hash [*dhash*](https://www.hackerfactor.com/blog/index.php?/archives/529-Kind-of-Like-That.html).
//!
//! The main difference with other rust implementations, and the reason it is called *fast*, is that it uses multi-threading and doesn't rely internally on the [*image*](https://docs.rs/image/latest/image/index.html) crate methods.
//!
//! ### Usage
//!
//! ```
//! use fast_dhash::Dhash;
//! use image::open;
//! use std::path::Path;
//!
//! let path = Path::new("../image.jpg");
//! let image = open(path);
//!
//! if let Ok(image) = image {
//!     let hash = Dhash::new(
//!         image.as_bytes(),
//!         image.width(),
//!         image.height(),
//!         image.color().channel_count(),
//!     );
//!     println!("hash: {}", hash);
//!     // hash: d6a288ac6d5cce14
//! }
//! ```
use serde::{Deserialize, Serialize};
use std::{fmt, num, str};

#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
pub struct Dhash {
    hash: u64,
}

impl Dhash {
    pub fn new(bytes: &[u8], width: u32, heigth: u32, channel_count: u8) -> Self {
        let mut grid = [[0f64; 9]; 8];

        let width = width as usize;
        let heigth = heigth as usize;
        let channel_count = channel_count as usize;

        let cell_width = width / 9;
        let cell_height = heigth / 8;

        if channel_count >= 3 {
            // NOTE: RGB(A) images implementation
            std::thread::scope(|s| {
                let mut handles = Vec::with_capacity(9);

                for y in 0..8 {
                    handles.push(s.spawn(move || {
                        let mut row = [0f64; 9];

                        for x in 0..9 {
                            let from = x * cell_width;
                            let to = from + cell_width;

                            let mut rs = 0f64;
                            let mut gs = 0f64;
                            let mut bs = 0f64;

                            for image_x in from..to {
                                let from = y * cell_height;
                                let to = from + cell_height;

                                for image_y in from..to {
                                    let i = (image_y * width + image_x) * channel_count;

                                    unsafe {
                                        rs += *bytes.get_unchecked(i) as f64;
                                        gs += *bytes.get_unchecked(i + 1) as f64;
                                        bs += *bytes.get_unchecked(i + 2) as f64;
                                    }
                                }
                            }

                            unsafe {
                                *row.get_unchecked_mut(x) += rs * 0.299 + gs * 0.587 + bs * 0.114;
                            }
                        }

                        (y, row)
                    }));
                }

                for handle in handles {
                    let (y, row) = handle.join().unwrap();
                    grid[y] = row;
                }
            });
        } else {
            // NOTE: Grayscale images implementation
            std::thread::scope(|s| {
                let mut handles = Vec::with_capacity(9);

                for y in 0..8 {
                    handles.push(s.spawn(move || {
                        let mut row = [0f64; 9];

                        for x in 0..9 {
                            let from = x * cell_width;
                            let to = from + cell_width;

                            let mut luma = 0f64;

                            for image_x in from..to {
                                let from = y * cell_height;
                                let to = from + cell_height;

                                for image_y in from..to {
                                    let i = (image_y * width + image_x) * channel_count;

                                    unsafe {
                                        luma += *bytes.get_unchecked(i) as f64;
                                    }
                                }
                            }

                            unsafe {
                                *row.get_unchecked_mut(x) += luma;
                            }
                        }

                        (y, row)
                    }));
                }

                for handle in handles {
                    let (y, row) = handle.join().unwrap();
                    grid[y] = row;
                }
            });
        }

        let mut bits = [false; 64];

        for y in 0..8 {
            for x in 0..8 {
                bits[y * 8 + x] = grid[y][x] > grid[y][x + 1];
            }
        }

        let mut hash: u64 = 0;

        for (i, &bit) in bits.iter().enumerate() {
            if bit {
                hash += 1 << i;
            }
        }

        Self { hash }
    }

    pub fn from_u64(hash: u64) -> Self {
        Self { hash }
    }

    pub fn hamming_distance(&self, other: &Self) -> u32 {
        (self.hash ^ other.hash).count_ones()
    }

    pub fn to_u64(&self) -> u64 {
        self.hash
    }
}

impl PartialEq for Dhash {
    fn eq(&self, other: &Self) -> bool {
        self.hamming_distance(other) < 11
    }
}

impl fmt::Display for Dhash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:016x}", &self.hash)
    }
}

impl str::FromStr for Dhash {
    type Err = num::ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match u64::from_str_radix(s, 16) {
            Ok(hash) => Ok(Self { hash }),
            Err(error) => Err(error),
        }
    }
}