1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
| use image::{imageops::FilterType, GenericImageView}; use ndarray::{s, Array, Axis, IxDyn}; use ort::{Environment, SessionBuilder, Value}; use std::{path::Path, sync::Arc, vec, fs::File, io::Read}; use opencv::imgcodecs::{imread, imwrite};
pub async fn detect() -> String {
let file = match File::open("assets/LevelScal/origin.jpg") { Err(why) => panic!("couldn't open origin.jpg: {:?}", why), Ok(file) => file, };
let buf = file.bytes().map(|x| x.unwrap()).collect::<Vec<u8>>();
println!("buf.len:{}", buf.len()); let boxes = detect_objects_on_image(buf); println!("boxes.len:{}",boxes.len()); println!("{:#}",serde_json::to_string(&boxes).unwrap_or_default()); return serde_json::to_string(&boxes).unwrap_or_default() }
fn detect_objects_on_image(buf: Vec<u8>) -> Vec<(f32, f32, f32, f32, &'static str, f32)> { let (input, img_width, img_height) = prepare_input(buf); let output = run_model(input); return process_output(output, img_width, img_height); }
fn prepare_input(buf: Vec<u8>) -> (Array<f32, IxDyn>, u32, u32) { let img = image::load_from_memory(&buf).unwrap(); let (img_width, img_height) = (img.width(), img.height()); let img = img.resize_exact(640, 640, FilterType::CatmullRom); let mut input = Array::zeros((1, 3, 640, 640)).into_dyn(); for pixel in img.pixels() { let x = pixel.0 as usize; let y = pixel.1 as usize; let [r, g, b, _] = pixel.2 .0; input[[0, 0, y, x]] = (r as f32) / 255.0; input[[0, 1, y, x]] = (g as f32) / 255.0; input[[0, 2, y, x]] = (b as f32) / 255.0; } return (input, img_width, img_height); }
fn run_model(input: Array<f32, IxDyn>) -> Array<f32, IxDyn> { let env = Arc::new(Environment::builder().with_name("YOLOv8").build().unwrap()); let model = SessionBuilder::new(&env) .unwrap() .with_model_from_file("assets/models/yolov8x_best.onnx") .unwrap(); let input_as_values = &input.as_standard_layout(); let model_inputs = vec![Value::from_array(model.allocator(), input_as_values).unwrap()]; let outputs = model.run(model_inputs).unwrap(); let output = outputs .get(0) .unwrap() .try_extract::<f32>() .unwrap() .view() .t() .into_owned(); return output; }
fn process_output( output: Array<f32, IxDyn>, img_width: u32, img_height: u32, ) -> Vec<(f32, f32, f32, f32, &'static str, f32)> { let mut boxes = Vec::new(); let output = output.slice(s![.., .., 0]); for row in output.axis_iter(Axis(0)) { let row: Vec<_> = row.iter().map(|x| *x).collect(); let (class_id, prob) = row .iter() .skip(4) .enumerate() .map(|(index, value)| (index, *value)) .reduce(|accum, row| if row.1 > accum.1 { row } else { accum }) .unwrap(); if prob < 0.5 { continue; } let label = YOLO_CLASSES[class_id]; let xc = row[0] / 640.0 * (img_width as f32); let yc = row[1] / 640.0 * (img_height as f32); let w = row[2] / 640.0 * (img_width as f32); let h = row[3] / 640.0 * (img_height as f32); let x1 = xc - w / 2.0; let x2 = xc + w / 2.0; let y1 = yc - h / 2.0; let y2 = yc + h / 2.0; boxes.push((x1, y1, x2, y2, label, prob)); } boxes.sort_by(|box1, box2| box2.5.total_cmp(&box1.5)); let mut result = Vec::new(); while boxes.len() > 0 { result.push(boxes[0]); boxes = boxes .iter() .filter(|box1| iou(&boxes[0], box1) < 0.7) .map(|x| *x) .collect() } return result; }
fn iou( box1: &(f32, f32, f32, f32, &'static str, f32), box2: &(f32, f32, f32, f32, &'static str, f32), ) -> f32 { return intersection(box1, box2) / union(box1, box2); }
fn union( box1: &(f32, f32, f32, f32, &'static str, f32), box2: &(f32, f32, f32, f32, &'static str, f32), ) -> f32 { let (box1_x1, box1_y1, box1_x2, box1_y2, _, _) = *box1; let (box2_x1, box2_y1, box2_x2, box2_y2, _, _) = *box2; let box1_area = (box1_x2 - box1_x1) * (box1_y2 - box1_y1); let box2_area = (box2_x2 - box2_x1) * (box2_y2 - box2_y1); return box1_area + box2_area - intersection(box1, box2); }
fn intersection( box1: &(f32, f32, f32, f32, &'static str, f32), box2: &(f32, f32, f32, f32, &'static str, f32), ) -> f32 { let (box1_x1, box1_y1, box1_x2, box1_y2, _, _) = *box1; let (box2_x1, box2_y1, box2_x2, box2_y2, _, _) = *box2; let x1 = box1_x1.max(box2_x1); let y1 = box1_y1.max(box2_y1); let x2 = box1_x2.min(box2_x2); let y2 = box1_y2.min(box2_y2); return (x2 - x1) * (y2 - y1); }
const YOLO_CLASSES: [&str; 10] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
|