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
use image::{self, FilterType, GenericImageView};
use std::sync::mpsc;
use std::thread;
pub struct SimilarChecker {
threshold: usize,
compressed_w: usize,
compressed_h: usize,
}
impl Default for SimilarChecker {
fn default() -> Self {
SimilarChecker {
threshold: 10,
compressed_w: 8,
compressed_h: 8,
}
}
}
impl SimilarChecker {
pub fn new() -> Self {
SimilarChecker {
threshold: 10,
compressed_w: 8,
compressed_h: 8,
}
}
pub fn compression_size(self, width: usize, height: usize) -> Self {
SimilarChecker {
compressed_w: width,
compressed_h: height,
..self
}
}
pub fn threshold(self, threshold: usize) -> Self {
SimilarChecker { threshold, ..self }
}
pub fn is_similar(&self, img1: image::DynamicImage, img2: image::DynamicImage) -> bool {
let w = self.compressed_w;
let h = self.compressed_h;
let (tx, rx) = mpsc::channel();
let tx1 = mpsc::Sender::clone(&tx);
thread::spawn(move || {
let hash1 = get_hash(process(img1, w, h));
tx1.send(hash1).unwrap();
});
thread::spawn(move || {
let hash2 = get_hash(process(img2, w, h));
tx.send(hash2).unwrap();
});
let mut v: Vec<usize> = Vec::new();
for received in rx {
v.push(received)
}
let distance = get_distance(v[0], v[1], w*h);
distance < self.threshold
}
}
fn process(
img: image::DynamicImage,
compressed_w: usize,
compressed_h: usize,
) -> image::DynamicImage {
img.resize_exact(
compressed_w as u32,
compressed_h as u32,
FilterType::Lanczos3,
)
.grayscale()
}
pub fn get_hash(img: image::DynamicImage) -> usize {
let mut sum_pixels: usize = 0;
let mut pixels: Vec<usize> = Vec::new();
for (_x, _y, pixel) in img.pixels() {
let red = pixel[0];
sum_pixels += red as usize;
pixels.push(red as usize)
}
let (width, height) = img.dimensions();
let ave = (sum_pixels as f64) / (f64::from(width) * f64::from(height));
let mut hash: usize = 0;
let mut one: usize = 1;
for pixel in pixels {
if pixel as f64 > ave {
hash |= one;
}
one <<= 1
}
hash
}
pub fn get_distance(hash1: usize, hash2: usize, pix_num: usize) -> usize {
let mut d = 0;
for i in 0..pix_num {
let k = 1 << i;
if (hash1 & k) != (hash2 & k) {
d += 1
}
}
d
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn get_distance_1() {
assert_eq!(get_distance(2247878505465, 2488321179641, 64), 6)
}
#[test]
fn get_distance_2() {
assert_eq!(get_distance(17431013446337445887, 17431022259610337215, 64), 3)
}
}