用opencv c++推理yolo v5模型,输出带矩形检测框的图片
时间: 2023-05-25 07:06:03 浏览: 181
基于opencv和yolo v5的目标检测模型项目
以下是用OpenCV和Yolo V5模型进行推理,并输出带矩形检测框的图片的示例代码:
```c++
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/dnn.hpp>
using namespace cv;
using namespace cv::dnn;
using namespace std;
int main()
{
// 加载模型和权重文件
String model_file = "/path/to/yolov5s.onnx";
Net net = readNetFromONNX(model_file);
// 加载图片
Mat img = imread("/path/to/image.jpg");
// 调整图片尺寸,使其符合模型输入要求
Mat input_blob;
int input_width = net.getLayer(0).getInputShape()[3];
int input_height = net.getLayer(0).getInputShape()[2];
resize(img, input_blob, Size(input_width,input_height));
// 将图片输入模型
blobFromImage(input_blob, input_blob, 1/255.0, Size(input_width,input_height), Scalar(0,0,0), true, false);
net.setInput(input_blob);
// 进行推理
Mat detection = net.forward();
// 解析检测结果
vector<float> confidence;
vector<int> class_id;
vector<Rect> bbox;
float* data = (float*)detection.data;
for(int i=0; i<detection.rows; ++i, data+=detection.cols)
{
Point class_id_point;
double max_val=0;
for(int j=0; j<num_classes; ++j)
{
if(data[j]>max_val)
{
max_val = data[j];
class_id_point.x = j;
}
}
if(max_val>confidence_threshold)
{
int center_x = (int)(data[num_classes]*img.cols);
int center_y = (int)(data[num_classes+1]*img.rows);
int width = (int)(data[num_classes+2]*img.cols);
int height = (int)(data[num_classes+3]*img.rows);
int left = center_x - width/2;
int top = center_y - height/2;
confidence.push_back(data[class_id_point.x]*100);
class_id.push_back(class_id_point.x);
bbox.push_back(Rect(left, top, width, height));
}
}
// 绘制检测框和标签
for(int i=0; i<bbox.size(); ++i)
{
rectangle(img, bbox[i], Scalar(0,0,255), 2);
String label = format("%.2f %%", confidence[i]);
putText(img, label, Point(bbox[i].x, bbox[i].y-5), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0,0,255), 2);
}
// 显示图片
namedWindow("detections", WINDOW_NORMAL);
resizeWindow("detections", 800, 600);
imshow("detections", img);
waitKey(0);
return 0;
}
```
此代码中,我们首先加载了Yolo V5模型和权重文件,在内存中构建了神经网络。然后,我们加载要进行检测的图像,并缩放到适合模型输入的尺寸。接下来,我们调用`net.setInput()`方法将缩放后的图像输入给模型进行推理,并获取检测结果。最后,我们解析检测结果,绘制矩形和标签,在原图上显示检测结果。
阅读全文