在win10+opencv4.4.0+opencv_contrib4.4.0+cuda10.2环境下部署yolov5模型
编译过程参考了这一篇博客
https://blog.csdn.net/hai_fellow_Z/article/details/116002203
主要有两个代码yolo.h和main_yolo.cpp
主程序为main_yolo.cpp文件
以下代码main函数可以分别实现图片、视频、摄像头的调用
#include "yolo.h"
#include <opencv2/opencv.hpp>
using namespace cv;
YOLO::YOLO(Net_config config)
{
cout << "Net use " << config.netname << endl;
this->confThreshold = config.confThreshold;
this->nmsThreshold = config.nmsThreshold;
this->objThreshold = config.objThreshold;
strcpy_s(this->netname, config.netname.c_str());
ifstream ifs(this->classesFile.c_str());
string line;
while (getline(ifs, line)) this->classes.push_back(line);
string modelFile = this->netname;
modelFile += ".onnx";
modelFile = "F:\\code\\a14-yolov5-dnn-opencv\\x64\\Release\\yolov5s.onnx";
this->net = readNet(modelFile);
// 调用GPU
net.setPreferableTarget(DNN_TARGET_CUDA);
net.setPreferableBackend(DNN_BACKEND_CUDA);
// 调用CPU
/*net.setPreferableTarget(DNN_TARGET_CPU);
net.setPreferableBackend(DNN_BACKEND_OPENCV);*/
}
void YOLO::drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat & frame) // Draw the predicted bounding box
{
//Draw a rectangle displaying the bounding box 蓝色框画左上和右下
rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 0, 255), 3);
//Get the label for the class name and its confidence
string label = format("%.2f", conf);
label = this->classes[classId] + ":" + label;
//Display the label at the top of the bounding box
int baseLine;
Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
top = max(top, labelSize.height);
//rectangle(frame, Point(left, top - int(1.5 * labelSize.height)), Point(left + int(1.5 * labelSize.width), top + baseLine), Scalar(0, 255, 0), FILLED);
putText(frame, label, Point(left, top), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0, 255, 0), 1);
}
void YOLO