use crate::{imageops::ImageOps, ColorSpace, ImageHash, ImageHasher};
#[derive(Debug, Clone)]
pub struct AverageHasher {
pub width: u32,
pub height: u32,
pub color_space: ColorSpace,
}
impl ImageHasher for AverageHasher {
fn hash_from_img(&self, img: &image::DynamicImage) -> ImageHash {
let converted = self.convert(img, self.width, self.height, self.color_space);
let mean = converted
.as_bytes()
.iter()
.fold(0, |acc, x| acc + *x as usize)
/ (self.width as usize * self.height as usize);
ImageHash::from_bool_iter(
converted.as_bytes().iter().map(|&p| p as usize > mean),
self.width,
self.height,
)
}
}
impl Default for AverageHasher {
fn default() -> Self {
AverageHasher {
width: 8,
height: 8,
color_space: ColorSpace::REC601,
}
}
}
impl ImageOps for AverageHasher {}
#[cfg(test)]
mod tests {
use std::path::Path;
use image::ImageReader;
use super::*;
const TEST_IMG: &str = "./data/img/test.png";
const TXT_FILE: &str = "./data/misc/test.txt";
const REC_601_HASH: &str = "ffffff0e00000301";
const REC_709_HASH: &str = "ffffff0e00000301";
#[test]
fn test_average_hash_from_img() {
let img = ImageReader::open(Path::new(TEST_IMG))
.unwrap()
.decode()
.unwrap();
let hasher = AverageHasher {
..Default::default()
};
let hash = hasher.hash_from_img(&img);
assert_eq!(hash.encode(), REC_601_HASH)
}
#[test]
fn test_average_hash_from_img_with_rec_709() {
let img = ImageReader::open(Path::new(TEST_IMG))
.unwrap()
.decode()
.unwrap();
let hasher = AverageHasher {
color_space: ColorSpace::REC709,
..Default::default()
};
let hash = hasher.hash_from_img(&img);
assert_eq!(hash.encode(), REC_709_HASH)
}
#[test]
fn test_average_hash_from_path() {
let hasher = AverageHasher {
..Default::default()
};
let hash = hasher.hash_from_path(Path::new(TEST_IMG));
match hash {
Ok(hash) => assert_eq!(hash.encode(), REC_601_HASH),
Err(err) => panic!("could not read image: {:?}", err),
}
}
#[test]
fn test_average_hash_from_nonexisting_path() {
let hasher = AverageHasher {
..Default::default()
};
let hash = hasher.hash_from_path(Path::new("./does/not/exist.png"));
match hash {
Ok(hash) => panic!("found hash for non-existing image: {:?}", hash),
Err(_) => (),
}
}
#[test]
fn test_average_hash_from_txt_file() {
let hasher = AverageHasher {
..Default::default()
};
let hash = hasher.hash_from_path(Path::new(TXT_FILE));
match hash {
Ok(hash) => panic!("found hash for non-existing image: {:?}", hash),
Err(_) => (),
}
}
}