基于C++和ONNX Runtime部署YOLOv13的ONNX模型,可以遵循以下步骤:
# End-to-End ONNX
yolo export model=yolov13{n/s/m/b/l/x}.pt format=onnx opset=13 simplify
通过这些步骤,可以在C++环境中利用ONNX Runtime高效地部署YOLOv13模型,实现实时的目标检测功能。
【测试环境】
windows10 x64 vs2019 cmake==3.30.1 onnxruntime==1.16.3 opencv==4.9.0 【使用步骤】 首先cmake生成exe文件,然后将onnxruntime.dll和onnxruntime_providers_shared.dll放到exe一起,不然会提示报错0xc000007b,这是因为系统目录也有个onnxruntime.dll引发冲突,并把car.mp4也放到exe一起。运行直接输入 yolov13.exe 注意onnx路径要是你真实路径我的onnx路径是我桌面上地址
【代码调用】
注意onnxruntime使用的cpu版本库,如需使用GPU还需要修改代码才行
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <iostream>
#include <string>
#include "YOLO13.hpp"
int main() {
// Paths to the model, labels, test image, and save directory
const std::string labelsPath = "../models/coco.names";
const std::string imagePath = "../data/dog.jpg"; // Image path
const std::string savePath = "../data/dog_detections.jpg"; // Save directory
// Model path for YOLOv13
const std::string modelPath = "../models/yolov13n.onnx"; // YOLOv13
// Initialize the YOLO detector with the chosen model and labels
bool isGPU = true; // Set to false for CPU processing
YOLO13Detector detector(modelPath, labelsPath, isGPU);
// Load an image
cv::Mat image = cv::imread(imagePath);
if (image.empty()) {
std::cerr << "Error: Could not open or find the image!\n";
return -1;
}
// Detect objects in the image and measure execution time
auto start = std::chrono::high_resolution_clock::now();
std::vector<Detection> results = detector.detect(image);
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - start);
std::cout << "Detection completed in: " << duration.count() << " ms" << std::endl;
// Draw bounding boxes on the image
detector.drawBoundingBox(image, results); // Simple bounding box drawing
// detector.drawBoundingBoxMask(image, results); // Uncomment for mask drawing
// Save the processed image to the specified directory
if (cv::imwrite(savePath, image)) {
std::cout << "Processed image saved successfully at: " << savePath << std::endl;
} else {
std::cerr << "Error: Could not save the processed image to: " << savePath << std::endl;
}
// Display the image
cv::imshow("Detections", image);
cv::waitKey(0); // Wait for a key press to close the window
return 0;
}