c++ yolov8 推理
时间: 2023-09-08 22:09:43 浏览: 67
暂时没有 YOLOv8 这个版本,YOLO目前最新的版本是 YOLOv5。以下是在C++中使用YOLOv5进行推理的示例代码:
1. 加载模型:
```
#include <opencv2/dnn/dnn.hpp>
cv::dnn::Net net = cv::dnn::readNetFromDarknet("yolov5.cfg", "yolov5.weights");
```
2. 图像预处理:
```
cv::Mat image = cv::imread("image.jpg");
cv::dnn::blobFromImage(image, inputBlob, 1 / 255.0, cv::Size(640, 640), cv::Scalar(), true, false, CV_32F);
net.setInput(inputBlob);
```
3. 执行推理:
```
std::vector<cv::Mat> detections;
net.forward(detections, net.getUnconnectedOutLayersNames());
```
4. 解析结果:
```
float confidenceThreshold = 0.5;
std::vector<int> classIds;
std::vector<float> confidences;
std::vector<cv::Rect> boxes;
for (auto& output : detections) {
auto* data = (float*)output.data;
for (int i = 0; i < output.rows; ++i, data += output.cols) {
cv::Mat scores = output.row(i).colRange(5, output.cols);
cv::Point classIdPoint;
double confidence;
cv::minMaxLoc(scores, 0, &confidence, 0, &classIdPoint);
if (confidence > confidenceThreshold) {
int centerX = (int)(data[0] * image.cols);
int centerY = (int)(data[1] * image.rows);
int width = (int)(data[2] * image.cols);
int height = (int)(data[3] * image.rows);
int left = centerX - width / 2;
int top = centerY - height / 2;
classIds.push_back(classIdPoint.x);
confidences.push_back((float)confidence);
boxes.emplace_back(left, top, width, height);
}
}
}
```
以上是使用YOLOv5进行推理的示例代码,其中推理结果包括检测到的物体的类别、置信度和边界框。可以根据需要对推理结果进行后处理,例如NMS抑制等操作。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)