Skip to content

Commit

Permalink
Refactor avg color function
Browse files Browse the repository at this point in the history
  • Loading branch information
twitu committed Apr 27, 2024
1 parent ea6c76d commit e4c6f0d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 27 deletions.
31 changes: 4 additions & 27 deletions spritefire/spritefire/src/emoji.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use image::{self, DynamicImage, GenericImageView};
use serde::{Deserialize, Serialize};

use crate::avg_color_and_density;

/// Emoji symbol with the average color of its picture
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Emoji {
Expand All @@ -14,34 +16,9 @@ pub struct Emoji {

impl From<(DynamicImage, String)> for Emoji {
fn from(value: (DynamicImage, String)) -> Self {
let (image, symbol) = value;

// use thumbnail technique to find average color
let mut avg_r = 0;
let mut avg_g = 0;
let mut avg_b = 0;
let mut pix_count = 0;

let (x_dim, y_dim) = image.dimensions();

for y in 0..y_dim {
for x in 0..x_dim {
let pixel = image.get_pixel(x, y).0;

// Consider pixel if it is not transparent
if pixel[3] > 0 {
pix_count += 1;

avg_r += pixel[0] as u64;
avg_g += pixel[1] as u64;
avg_b += pixel[2] as u64;
}
}
}
let (img, symbol) = value;

let avg_r = avg_r as f64 / pix_count as f64;
let avg_g = avg_g as f64 / pix_count as f64;
let avg_b = avg_b as f64 / pix_count as f64;
let [avg_r, avg_g, avg_b, pix_count] = avg_color_and_density(&img);

Self {
symbol,
Expand Down
33 changes: 33 additions & 0 deletions spritefire/spritefire/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,35 @@
use image::{DynamicImage, GenericImageView};

pub mod db;
pub mod emoji;

pub fn avg_color_and_density(img: &DynamicImage) -> [u64; 4] {
// use thumbnail technique to find average color
let mut avg_r = 0;
let mut avg_g = 0;
let mut avg_b = 0;
let mut pix_count = 0;

let (x_dim, y_dim) = img.dimensions();

for y in 0..y_dim {
for x in 0..x_dim {
let pixel = img.get_pixel(x, y).0;

// Consider pixel if it is not transparent
if pixel[3] > 0 {
pix_count += 1;

avg_r += pixel[0] as u64;
avg_g += pixel[1] as u64;
avg_b += pixel[2] as u64;
}
}
}

let avg_r = avg_r as f64 / pix_count as f64;
let avg_g = avg_g as f64 / pix_count as f64;
let avg_b = avg_b as f64 / pix_count as f64;

[avg_r as u64, avg_g as u64, avg_b as u64, pix_count]
}

0 comments on commit e4c6f0d

Please sign in to comment.