Skip to content

Commit

Permalink
Use image density for mosaic
Browse files Browse the repository at this point in the history
  • Loading branch information
twitu committed Apr 18, 2024
1 parent 96c182a commit 9da66ee
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 15 deletions.
52 changes: 37 additions & 15 deletions spritefire/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type Fxd = FixedU8<U0>;
#[derive(Serialize, Deserialize, Debug)]
pub struct EmojiDatabase {
kdtree: KdTree<Fxd, u32, 3, 32, u32>,
symbols: Vec<String>,
symbols: Vec<(u64, String)>,
}

impl EmojiDatabase {
Expand All @@ -31,17 +31,23 @@ impl EmojiDatabase {
pub fn from_emojis(emojis: Vec<Emoji>) -> Self {
let (symbols, colors): (Vec<_>, Vec<_>) = emojis
.into_iter()
.map(|Emoji { symbol, color }| {
let [r, g, b] = color;
(
symbol,
[
FixedU8::from_num(r),
FixedU8::from_num(g),
FixedU8::from_num(b),
],
)
})
.map(
|Emoji {
symbol,
color,
density: transparent,
}| {
let [r, g, b] = color;
(
(transparent, symbol),
[
FixedU8::from_num(r),
FixedU8::from_num(g),
FixedU8::from_num(b),
],
)
},
)
.unzip();

let mut kdtree = KdTree::new();
Expand All @@ -52,17 +58,33 @@ impl EmojiDatabase {
Self { symbols, kdtree }
}

pub fn lookup_closest_dense_emoji(&self, rgb: Rgb<u8>) -> &str {
let point = [
FixedU8::from_num(rgb[0]),
FixedU8::from_num(rgb[1]),
FixedU8::from_num(rgb[2]),
];

let nearest = self.kdtree.nearest_n::<SquaredEuclidean>(&point, 5);
let (_, symbol) = nearest
.iter()
.map(|item| &self.symbols[item.item as usize])
.max()
.unwrap();
symbol
}

pub fn lookup_closest_emoji(&self, rgb: Rgb<u8>) -> &str {
let point = [
FixedU8::from_num(rgb[0]),
FixedU8::from_num(rgb[1]),
FixedU8::from_num(rgb[2]),
];

let nearest = self.kdtree.nearest_one::<SquaredEuclidean>(&point);
let index = nearest.item as usize;
&self.symbols[index]
let index: usize = self.kdtree.nearest_one::<SquaredEuclidean>(&point).item as usize;
&self.symbols[index].1
}

pub fn new_from_directory(dir_path: PathBuf) -> Self {
let emojis = read_emojis_from_directory(dir_path);
EmojiDatabase::from_emojis(emojis)
Expand Down
3 changes: 3 additions & 0 deletions spritefire/src/emoji.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ pub struct Emoji {
pub symbol: String,
/// Average color for emoji
pub color: [u8; 3],
/// More pixels with color make for a more dense emoji image
pub density: u64,
}

impl From<(DynamicImage, String)> for Emoji {
Expand Down Expand Up @@ -43,6 +45,7 @@ impl From<(DynamicImage, String)> for Emoji {
Self {
symbol,
color: [avg_r as u8, avg_g as u8, avg_b as u8],
density: pix_count,
}
}
}

0 comments on commit 9da66ee

Please sign in to comment.