- 替换 opencv 为 image 库以简化交叉编译 - 修正 nms 逻辑中的 ArrayView 借用问题 - 增加 save_debug_image 方法用于可视化检测框 - 更新 Cargo.toml 依赖项
76 lines
2.6 KiB
Rust
76 lines
2.6 KiB
Rust
use std::fs;
|
|
use image::Rgb;
|
|
use ddddocr_rs::{DdddOcr, DdddOcrBuilder}; // 假设你的包名是这个
|
|
|
|
/// 将检测结果绘制在图像上并保存
|
|
fn save_debug_image( image_bytes: &[u8], bboxes: &Vec<Vec<i32>>, output_path: &str) -> anyhow::Result<()> {
|
|
|
|
|
|
let dynamic_img = image::load_from_memory(image_bytes)?;
|
|
let mut img = dynamic_img.to_rgb8();
|
|
let (width, height) = img.dimensions();
|
|
let red = Rgb([255u8, 0, 0]);
|
|
|
|
for bbox in bboxes {
|
|
// 基础边界检查
|
|
let x1 = bbox[0].max(0).min(width as i32 - 1) as u32;
|
|
let y1 = bbox[1].max(0).min(height as i32 - 1) as u32;
|
|
let x2 = bbox[2].max(0).min(width as i32 - 1) as u32;
|
|
let y2 = bbox[3].max(0).min(height as i32 - 1) as u32;
|
|
|
|
// 绘制横向线条
|
|
for x in x1..=x2 {
|
|
img.put_pixel(x, y1, red);
|
|
img.put_pixel(x, y2, red);
|
|
// 如果要加粗,多画一行
|
|
if y1 + 1 < height { img.put_pixel(x, y1 + 1, red); }
|
|
if y2.saturating_sub(1) > 0 { img.put_pixel(x, y2 - 1, red); }
|
|
}
|
|
// 绘制纵向线条
|
|
for y in y1..=y2 {
|
|
img.put_pixel(x1, y, red);
|
|
img.put_pixel(x2, y, red);
|
|
// 如果要加粗,多画一列
|
|
if x1 + 1 < width { img.put_pixel(x1 + 1, y, red); }
|
|
if x2.saturating_sub(1) > 0 { img.put_pixel(x2 - 1, y, red); }
|
|
}
|
|
}
|
|
|
|
img.save(output_path)?;
|
|
Ok(())
|
|
}
|
|
#[test]
|
|
fn test_full_classification() {
|
|
// 1. 初始化模型
|
|
let ocr = DdddOcrBuilder::new().build().expect("模型加载失败");
|
|
|
|
// 2. 加载测试图片
|
|
let img = image::open("samples/code3.png").expect("测试图片不存在");
|
|
|
|
// 3. 执行识别
|
|
let result = ocr.classification(&img).expect("识别过程出错");
|
|
|
|
println!("识别结果: {}", result);
|
|
assert!(!result.is_empty());
|
|
}
|
|
#[test]
|
|
fn test_det_load()->anyhow::Result<()>{
|
|
let det = DdddOcrBuilder::new().det().build()?;
|
|
let image_path = "samples/det1.png";
|
|
let image_bytes = fs::read(image_path)
|
|
.map_err(|e| anyhow::anyhow!("无法读取图片 {}: {}", image_path, e))?;
|
|
|
|
println!("图片读取成功,字节大小: {}", image_bytes.len());
|
|
let bboxes =det.detection(&image_bytes)?;
|
|
println!(":?{}",det);
|
|
println!("检测到的目标数量: {}", bboxes.len());
|
|
if bboxes.is_empty() {
|
|
println!("未检测到任何目标。");
|
|
} else {
|
|
save_debug_image(&image_bytes, &bboxes, "samples/result.jpg")?;
|
|
for (i, bbox) in bboxes.iter().enumerate() {
|
|
println!("目标 [{}]: x1={}, y1={}, x2={}, y2={}", i, bbox[0], bbox[1], bbox[2], bbox[3]);
|
|
}
|
|
}
|
|
Ok(())
|
|
} |