src/
├── lib.rs # 主要公開 API
├── main.rs # 示範應用程式
├── model.rs # YOLOv8 模型核心邏輯
├── ort_backend.rs # ONNX Runtime 後端整合
├── yolo_result.rs # 結果資料結構
├── config.rs # 配置管理
├── nms.rs # 非極大值抑制演算法
└── color.rs # 可視化色彩工具
graph TD
A[輸入影像] --> B[前處理]
B --> C[模型推論]
C --> D[後處理]
D --> E[NMS 過濾]
E --> F[結果輸出]
套件名稱 | 用途 | 版本 |
---|---|---|
ort |
ONNX Runtime 整合 | 1.16.3 |
opencv |
圖像處理 | 0.93.7 |
ndarray |
多維陣列運算 | 0.15.6 |
image |
影像格式處理 | 0.24.7 |
clap |
命令列參數解析 | 4.2.4 |
use ort_tutorial::YOLOv8;
use ort_tutorial::config;
// 建立配置
let config = config::Config {
model: "model_weight/onnx/version/yolo11s.onnx".to_string(),
height: 640,
width: 640,
conf: 0.3,
iou: 0.45,
..Default::default()
};
// 初始化模型
let mut model = YOLOv8::new(config)?;
// 載入影像
let img = opencv::imgcodecs::imread("test.jpg", opencv::imgcodecs::IMREAD_COLOR)?;
// 執行推論
let results = model.run_mat(&vec![img])?;
// 處理結果
if let Some(result) = results.get(0) {
if let Some(bboxes) = &result.bboxes {
println!("偵測到 {} 個物體", bboxes.len());
for bbox in bboxes {
println!("類別: {}, 信心度: {:.2}", bbox.id(), bbox.confidence());
}
}
}
// 開啟視訊檔案
let mut cap = opencv::videoio::VideoCapture::from_file("input.mp4", opencv::videoio::CAP_ANY)?;
// 設定輸出視訊寫入器
let fourcc = opencv::videoio::VideoWriter::fourcc('m', 'p', '4', 'v')?;
let mut writer = opencv::videoio::VideoWriter::new(
"output.mp4",
fourcc,
30.0,
opencv::core::Size::new(640, 480),
true,
)?;
// 處理每一幀
let mut frame = opencv::core::Mat::default();
while cap.read(&mut frame)? {
if frame.empty() { break; }
// 執行物件偵測
let results = model.run_mat(&vec![frame.clone()])?;
// 在影像上繪製結果
// ... 繪圖程式碼 ...
// 寫入輸出視訊
writer.write(&frame)?;
}
pub struct YOLOv8 {
pub engine: OrtBackend, // ONNX Runtime 引擎
pub nc: u32, // 類別數量
pub nk: u32, // 關鍵點數量
pub nm: u32, // 遮罩數量
pub height: u32, // 輸入高度
pub width: u32, // 輸入寬度
pub task: YOLOTask, // 任務類型
// ... 其他欄位
}
new(config: Config) -> Result<Self>
建立新的 YOLOv8 模型實例。
run_mat(xs: &Vec<Mat>) -> Result<Vec<YOLOResult>>
處理 OpenCV Mat 影像並返回偵測結果。
pub struct YOLOResult {
pub probs: Option<Embedding>, // 分類機率
pub bboxes: Option<Vec<Bbox>>, // 邊界框
pub keypoints: Option<Vec<Vec<Point2>>>, // 關鍵點
pub masks: Option<Vec<Vec<u8>>>, // 分割遮罩
}
pub struct Bbox {
xmin: f32, ymin: f32, // 左上角座標
width: f32, height: f32, // 寬度和高度
id: usize, // 類別 ID
confidence: f32, // 信心度分數
}
pub struct Config {
pub model: String, // ONNX 模型檔案路徑
pub cuda: bool, // 是否使用 CUDA
pub height: u32, // 輸入影像高度
pub width: u32, // 輸入影像寬度
pub device_id: u32, // GPU 裝置 ID
pub batch: u32, // 批次大小
pub conf: f32, // 信心度閾值 (0.0-1.0)
pub iou: f32, // IoU 閾值 (0.0-1.0)
pub kconf: f32, // 關鍵點信心度閾值
pub window_view: bool, // 是否顯示視窗
pub profile: bool, // 是否啟用效能分析
// ... 其他選項
}
提供者 | 描述 | 適用場景 |
---|---|---|
CPU | 中央處理器 | 開發測試、資源受限環境 |
CUDA | NVIDIA GPU | 高效能推論 |
TensorRT | NVIDIA TensorRT | 最佳化生產部署 |
let config = config::Config {
profile: true, // 啟用效能分析
// ... 其他配置
};
[Model Preprocess]: 2.34ms
[Model Inference]: 15.67ms
[Model Postprocess]: 1.23ms
Total processing time: 19.24ms
專案使用 HSV 色彩空間生成鮮豔的隨機色彩,每個類別都會獲得獨特的顏色,並在整個運行過程中保持一致。
use ort_tutorial::color;
// 獲取類別色彩
let color = color::get_class_color(class_id);
ndarray
進行高效能陣列運算