use crate::prelude::BBox;
use image::{imageops::crop_imm, DynamicImage, GenericImageView, Rgba};
use imageproc::{drawing::draw_hollow_rect_mut, rect::Rect};
use ndarray::{Array1, Array2};
mod evaluate;
pub use evaluate::evaluate_accuracy;
pub use evaluate::evaluate_precision;
mod generate_annotations;
pub use generate_annotations::add_hard_negative_samples;
pub use generate_annotations::generate_annotations;
pub use generate_annotations::generate_negative_samples;
pub fn crop_bbox(image: &DynamicImage, bbox: &BBox) -> DynamicImage {
let cropped = crop_imm(image, bbox.x as u32, bbox.y as u32, bbox.width, bbox.height).to_image();
DynamicImage::ImageRgba8(cropped)
}
pub fn draw_bboxes(image: &mut DynamicImage, bboxes: &[BBox]) {
let (width, height) = image.dimensions();
let color = Rgba([255, 0, 0, 255]);
for bbox in bboxes {
let (x1, y1, x2, y2) = (
bbox.x.max(0),
bbox.y.max(0),
(bbox.x + bbox.width as i32).min(width as i32 - 1),
(bbox.y + bbox.height as i32).min(height as i32 - 1),
);
draw_hollow_rect_mut(
image,
Rect::at(x1, y1).of_size((x2 - x1) as u32, (y2 - y1) as u32),
color,
);
}
}
pub fn extract_data<X, Y>(features: Vec<Vec<X>>, labels: Vec<Y>) -> (Array2<X>, Array1<Y>) {
assert_eq!(features.len(), labels.len());
let (x, y) = (
labels.len(),
match features.first() {
Some(x) => x.len(),
None => 0,
},
);
let features = features.into_iter().flatten().collect();
let features_array = Array2::from_shape_vec((x, y), features).unwrap();
let labels_array = Array1::from_shape_vec(labels.len(), labels).unwrap();
(features_array, labels_array)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_crop_bbox() {
let image = DynamicImage::new_rgba8(100, 100);
let bbox = BBox {
x: 25,
y: 25,
width: 50,
height: 50,
};
let cropped_image = crop_bbox(&image, &bbox);
assert_eq!(cropped_image.width(), 50);
assert_eq!(cropped_image.height(), 50);
}
#[test]
fn test_draw_bboxes() {
let mut image = DynamicImage::new_rgb8(100, 100);
let bboxes = vec![BBox::new(10, 10, 10, 10), BBox::new(30, 30, 40, 40)];
draw_bboxes(&mut image, &bboxes);
assert_eq!(image.get_pixel(9, 9), image::Rgba([0, 0, 0, 255]));
assert_eq!(image.get_pixel(10, 10), image::Rgba([255, 0, 0, 255]));
assert_eq!(image.get_pixel(29, 29), image::Rgba([0, 0, 0, 255]));
assert_eq!(image.get_pixel(30, 30), image::Rgba([255, 0, 0, 255]));
}
#[test]
fn test_extract_data() {
let features = vec![vec![1, 0], vec![2, 0], vec![3, 0], vec![4, 0], vec![5, 0]];
let labels = vec![true, false, true, false, true];
let expected_labels_array = Array1::from_shape_vec(5, labels.clone()).unwrap();
let (actual_features_array, actual_labels_array) = extract_data(features, labels);
assert_eq!(actual_features_array.dim().0, actual_labels_array.len());
assert_eq!(expected_labels_array, actual_labels_array);
}
}