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
use crate::*;
const HASH_SIZE: usize = 16;
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord)]
pub struct Hash(Vec<bool>);
impl std::fmt::Display for Hash {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(fmt, "{:x}", self)
}
}
fn to_byte(b: &[bool]) -> u8 {
let mut dest = 0;
for (i, x) in b.iter().enumerate() {
if *x {
dest |= 1 << i;
}
}
dest
}
impl std::fmt::LowerHex for Hash {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
for c in self.0.chunks(8).map(to_byte) {
write!(fmt, "{:02x}", c)?
}
Ok(())
}
}
impl Hash {
pub fn diff(&self, other: &Hash) -> usize {
let mut diff = 0;
for (i, x) in self.0.iter().enumerate() {
if other.0[i] != *x {
diff += 1;
}
}
diff
}
}
impl From<Hash> for String {
fn from(hash: Hash) -> String {
format!("{}", hash)
}
}
impl From<Hash> for Vec<bool> {
fn from(hash: Hash) -> Vec<bool> {
hash.0
}
}
impl<T: Type, C: Color> Image<T, C> {
pub fn hash(&self) -> Hash {
let small: Image<T, C> = self.resize((HASH_SIZE, HASH_SIZE));
let mut hash = vec![false; HASH_SIZE * HASH_SIZE];
let mut index = 0;
let mut px = Pixel::new();
let mut c = C::CHANNELS;
if C::ALPHA.is_some() {
c -= 1;
}
let mut sum: f64 = 0.;
for j in 0..HASH_SIZE {
for i in 0..HASH_SIZE {
for c in 0..c {
sum += small.get_f((i, j), c);
}
}
}
let avg = sum / (HASH_SIZE * HASH_SIZE * c) as f64;
for j in 0..HASH_SIZE {
for i in 0..HASH_SIZE {
small.pixel_at((i, j), &mut px);
if px.iter().sum::<f64>() / c as f64 > avg {
hash[index] = true;
}
index += 1
}
}
Hash(hash)
}
}