Create mod.rs

This commit is contained in:
SirTalksalot75 2023-06-11 18:09:22 +02:00 committed by GitHub
parent 5385da2039
commit 010f2b4fcd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 69 additions and 0 deletions

69
src/Feature/mod.rs Normal file
View File

@ -0,0 +1,69 @@
use std::collections::HashMap;
fn extract_color_distribution(image_data: &[u8]) -> HashMap<u32, f32> {
let mut color_distribution: HashMap<u32, f32> = HashMap::new();
let total_pixels = image_data.len() as f32 / 4.0;//für 4 Werte
for pixel in image_data.chunks_exact(4) {
let r = pixel[0] as u32;
let g = pixel[1] as u32;
let b = pixel[2] as u32;
let a = pixel[3] as u32;
let rgba = (r << 24) | (g << 16) | (b << 8) | a;
*color_distribution.entry(rgba).or_insert(0.0) += 1.0;
}
for (_, count) in &mut color_distribution {
*count /= total_pixels;
}
color_distribution
}
fn extract_average_brightness(image: &[u8]) -> u8 {
let mut sum: u32 = 0;
let mut count: u32 = 0;
for i in (0..image.len()).step_by(4) {
let r = image[i] as u32;
let g = image[i + 1] as u32;
let b = image[i + 2] as u32;
// (0.299 * R) + (0.587 * G) + (0.114 * B)
let brightness = ((0.299 * r as f32) + (0.587 * g as f32) + (0.114 * b as f32)).round() as u32;
sum += brightness;
count += 1;
}
let average_brightness = (sum / count) as u8;
average_brightness
}
fn main() {
test2();
}
fn test2(){
let image_data: Vec<(u8, u8, u8, u8)> = vec![
(255, 0, 0, 255), // Red
(0, 255, 0, 255), // Green
(0, 0, 255, 255), // Blue
];
//convert image data to useable &u8 slice
let byte_slice: &[u8] = unsafe {
std::slice::from_raw_parts(
image_data.as_ptr() as *const u8,
image_data.len() * 4,
)
};
let color_distribution = extract_color_distribution(&byte_slice);
let color_distribution_vec: Vec<f32> = color_distribution.values().cloned().collect();
let average_brightness = extract_average_brightness(&byte_slice);
println!("{:?}", average_brightness);
println!("{:?}", color_distribution_vec);
}