分别使用了openvino,opencv_cuda进行加速。
关于演示视频及代码讲解请查看:
https://www.bilibili.com/video/bv13s4y1c7ea/
https://www.bilibili.com/video/bv1dq4y1x7r6/
https://www.bilibili.com/video/bv1kt4y1s7hz/
一、新建项目 ui设计
二、代码部分 mainwindow 类
mainwindow.h
#ifndef mainwindow_h #define mainwindow_h #include <qfiledialog> #include <qfile> #include <opencv2/opencv.hpp> #include <opencv2/dnn.hpp> #include <qmainwindow> #include <qtimer> #include <qimage> #include <qpixmap> #include <qdatetime> #include <qmutex> #include <qmutexlocker> #include <qmimedatabase> #include <iostream> #include <yolov5.h> #include <chrono> #pragma comment(lib,"c:\program files (x86)\intel\openvino_2021\opencv\lib\opencv_core453.lib") #pragma comment(lib,"c:\program files (x86)\intel\openvino_2021\opencv\lib\opencv_imgcodecs453.lib") #pragma comment(lib,"c:\program files (x86)\intel\openvino_2021\opencv\lib\opencv_imgproc453.lib") #pragma comment(lib,"c:\program files (x86)\intel\openvino_2021\opencv\lib\opencv_videoio453.lib") #pragma comment(lib,"c:\program files (x86)\intel\openvino_2021\opencv\lib\opencv_objdetect453.lib") #pragma comment(lib,"c:\program files (x86)\intel\openvino_2021\opencv\lib\opencv_dnn453.lib") #pragma comment(lib,"c:\program files (x86)\intel\openvino_2021\deployment_tools\inference_engine\lib\intel64\release\inference_engine.lib") #pragma comment(lib,"c:\program files (x86)\intel\openvino_2021\deployment_tools\inference_engine\lib\intel64\release\inference_engine_c_api.lib") #pragma comment(lib,"c:\program files (x86)\intel\openvino_2021\deployment_tools\inference_engine\lib\intel64\release\inference_engine_transformations.lib") //libs+= -l "c:program files (x86)intelopenvino_2021opencvlib*.lib" //libs+= -l "c:program files (x86)intelopenvino_2021deployment_toolsinference_enginelibintel64release*.lib" //#ifdef qt_no_debug //#pragma comment(lib,"c:program files (x86)intelopenvino_2021opencvlibopencv_core452.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_imgcodecs452.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_imgproc452.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_imgcodecs452.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_video452.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_videoio452.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_objdetect452.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_shape452.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_dnn452.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_dnn_objdetect452.lib") //#else //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_core452d.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_imgcodecs452d.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_imgproc452d.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_imgcodecs452d.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_video452d.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_videoio452d.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_objdetect452d.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_shape452d.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_dnn452d.lib") //#pragma comment(lib,"e:/opencv_build/install/x64/vc16/lib/opencv_dnn_objdetect452d.lib") //#endif //#ifdef qt_no_debug //#pragma comment(lib,"e:/opencv452_cuda/install/x64/vc16/lib/opencv_core452.lib") //#pragma comment(lib,"e:/opencv452_cuda/install/x64/vc16/lib/opencv_imgcodecs452.lib") //#pragma comment(lib,"e:/opencv452_cuda/install/x64/vc16/lib/opencv_imgproc452.lib") //#pragma comment(lib,"e:/opencv452_cuda/install/x64/vc16/lib/opencv_imgcodecs452.lib") //#pragma comment(lib,"e:/opencv452_cuda/install/x64/vc16/lib/opencv_video452.lib") //#pragma comment(lib,"e:/opencv452_cuda/install/x64/vc16/lib/opencv_videoio452.lib") //#pragma comment(lib,"e:/opencv452_cuda/install/x64/vc16/lib/opencv_objdetect452.lib") //#pragma comment(lib,"e:/opencv452_cuda/install/x64/vc16/lib/opencv_shape452.lib") //#pragma comment(lib,"e:/opencv452_cuda/install/x64/vc16/lib/opencv_dnn452.lib") //#pragma comment(lib,"e:/opencv452_cuda/install/x64/vc16/lib/opencv_dnn_objdetect452.lib") //#endif qpixmap mat2image(cv::mat src); qt_begin_namespace namespace ui { class mainwindow; } qt_end_namespace class mainwindow : public qmainwindow { q_object public: mainwindow(qwidget *parent = nullptr); void init(); ~mainwindow(); private slots: void readframe(); //自定义信号处理函数 void on_openfile_clicked(); void on_loadfile_clicked(); void on_startdetect_clicked(); void on_stopdetect_clicked(); void on_combobox_activated(const qstring &arg1); private: ui::mainwindow *ui; qtimer *timer; cv::videocapture *capture; yolov5 *yolov5; netconfig conf; netconfig *yolo_nets; std::vector<cv::rect> bboxes; int isdetect_ok = 0; }; #endif // mainwindow_h
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" mainwindow::mainwindow(qwidget *parent) : qmainwindow(parent) , ui(new ui::mainwindow) { ui->setupui(this); setwindowtitle(qstringliteral("yolov5目标检测软件")); timer = new qtimer(this); timer->setinterval(33); connect(timer,signal(timeout()),this,slot(readframe())); ui->startdetect->setenabled(false); ui->stopdetect->setenabled(false); init(); } mainwindow::~mainwindow() { capture->release(); delete capture; delete [] yolo_nets; delete yolov5; delete ui; } void mainwindow::init() { capture = new cv::videocapture(); yolo_nets = new netconfig[4]{ {0.5, 0.5, 0.5, "yolov5s"}, {0.6, 0.6, 0.6, "yolov5m"}, {0.65, 0.65, 0.65, "yolov5l"}, {0.75, 0.75, 0.75, "yolov5x"} }; conf = yolo_nets[0]; yolov5 = new yolov5(); yolov5->initialization(conf); ui->texteditlog->append(qstringliteral("默认模型类别:yolov5s args: %1 %2 %3") .arg(conf.nmsthreshold) .arg(conf.objthreshold) .arg(conf.confthreshold)); } void mainwindow::readframe() { cv::mat frame; capture->read(frame); if (frame.empty()) return; auto start = std::chrono::steady_clock::now(); yolov5->detect(frame); auto end = std::chrono::steady_clock::now(); std::chrono::duration<double, std::milli> elapsed = end - start; ui->texteditlog->append(qstring("cost_time: %1 ms").arg(elapsed.count())); // double t0 = static_cast<double>(cv::gettickcount()); // yolov5->detect(frame); // double t1 = static_cast<double>(cv::gettickcount()); // ui->texteditlog->append(qstringliteral("cost_time: %1 ").arg((t1 - t0) / cv::gettickfrequency())); cv::cvtcolor(frame, frame, cv::color_bgr2rgb); qimage rawimage = qimage((uchar*)(frame.data),frame.cols,frame.rows,frame.step,qimage::format_rgb888); ui->label->setpixmap(qpixmap::fromimage(rawimage)); } void mainwindow::on_openfile_clicked() { qstring filename = qfiledialog::getopenfilename(this,qstringliteral("打开文件"),".","*.mp4 *.avi;;*.png *.jpg *.jpeg *.bmp"); if(!qfile::exists(filename)){ return; } ui->statusbar->showmessage(filename); qmimedatabase db; qmimetype mime = db.mimetypeforfile(filename); if (mime.name().startswith("image/")) { cv::mat src = cv::imread(filename.tolatin1().data()); if(src.empty()){ ui->statusbar->showmessage("图像不存在!"); return; } cv::mat temp; if(src.channels()==4) cv::cvtcolor(src,temp,cv::color_bgra2rgb); else if (src.channels()==3) cv::cvtcolor(src,temp,cv::color_bgr2rgb); else cv::cvtcolor(src,temp,cv::color_gray2rgb); auto start = std::chrono::steady_clock::now(); yolov5->detect(temp); auto end = std::chrono::steady_clock::now(); std::chrono::duration<double, std::milli> elapsed = end - start; ui->texteditlog->append(qstring("cost_time: %1 ms").arg(elapsed.count())); qimage img = qimage((uchar*)(temp.data),temp.cols,temp.rows,temp.step,qimage::format_rgb888); ui->label->setpixmap(qpixmap::fromimage(img)); ui->label->resize(ui->label->pixmap()->size()); filename.clear(); }else if (mime.name().startswith("video/")) { capture->open(filename.tolatin1().data()); if (!capture->isopened()){ ui->texteditlog->append("fail to open mp4!"); return; } isdetect_ok +=1; if (isdetect_ok ==2) ui->startdetect->setenabled(true); ui->texteditlog->append(qstring::fromutf8("open video: %1 succesfully!").arg(filename)); //获取整个帧数qstringliteral long totalframe = capture->get(cv::cap_prop_frame_count); ui->texteditlog->append(qstringliteral("整个视频共 %1 帧").arg(totalframe)); ui->label->resize(qsize(capture->get(cv::cap_prop_frame_width), capture->get(cv::cap_prop_frame_height))); //设置开始帧() long frametostart = 0; capture->set(cv::cap_prop_pos_frames, frametostart); ui->texteditlog->append(qstringliteral("从第 %1 帧开始读").arg(frametostart)); //获取帧率 double rate = capture->get(cv::cap_prop_fps); ui->texteditlog->append(qstringliteral("帧率为: %1 ").arg(rate)); } } void mainwindow::on_loadfile_clicked() { qstring onnxfile = qfiledialog::getopenfilename(this,qstringliteral("选择模型"),".","*.onnx"); if(!qfile::exists(onnxfile)){ return; } ui->statusbar->showmessage(onnxfile); if (!yolov5->loadmodel(onnxfile.tolatin1().data())){ ui->texteditlog->append(qstringliteral("加载模型失败!")); return; } isdetect_ok +=1; ui->texteditlog->append(qstring::fromutf8("open onnxfile: %1 succesfully!").arg(onnxfile)); if (isdetect_ok ==2) ui->startdetect->setenabled(true); } void mainwindow::on_startdetect_clicked() { timer->start(); ui->startdetect->setenabled(false); ui->stopdetect->setenabled(true); ui->openfile->setenabled(false); ui->loadfile->setenabled(false); ui->combobox->setenabled(false); ui->texteditlog->append(qstringliteral("================n" " 开始检测n" "================n")); } void mainwindow::on_stopdetect_clicked() { ui->startdetect->setenabled(true); ui->stopdetect->setenabled(false); ui->openfile->setenabled(true); ui->loadfile->setenabled(true); ui->combobox->setenabled(true); timer->stop(); ui->texteditlog->append(qstringliteral("================n" " 停止检测n" "================n")); } void mainwindow::on_combobox_activated(const qstring &arg1) { if (arg1.contains("s")){ conf = yolo_nets[0]; }else if (arg1.contains("m")) { conf = yolo_nets[1]; }else if (arg1.contains("l")) { conf = yolo_nets[2]; }else if (arg1.contains("x")) { conf = yolo_nets[3];} yolov5->initialization(conf); ui->texteditlog->append(qstringliteral("使用模型类别:%1 args: %2 %3 %4") .arg(arg1) .arg(conf.nmsthreshold) .arg(conf.objthreshold) .arg(conf.confthreshold)); }
yolov5类
yolov5.h
#ifndef yolov5_h #define yolov5_h #include <opencv2/opencv.hpp> #include <opencv2/dnn.hpp> #include <fstream> #include <sstream> #include <iostream> #include <exception> #include <qmessagebox> struct netconfig { float confthreshold; // class confidence threshold float nmsthreshold; // non-maximum suppression threshold float objthreshold; //object confidence threshold std::string netname; }; class yolov5 { public: yolov5(){} void initialization(netconfig conf); bool loadmodel(const char* onnxfile); void detect(cv::mat& frame); private: const float anchors[3][6] = {{10.0, 13.0, 16.0, 30.0, 33.0, 23.0}, {30.0, 61.0, 62.0, 45.0, 59.0, 119.0},{116.0, 90.0, 156.0, 198.0, 373.0, 326.0}}; const float stride[3] = { 8.0, 16.0, 32.0 }; std::string classes[80] = {"person", "bicycle", "car", "motorbike", "aeroplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "sofa", "pottedplant", "bed", "diningtable", "toilet", "tvmonitor", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush"}; const int inpwidth = 640; const int inpheight = 640; float confthreshold; float nmsthreshold; float objthreshold; cv::mat blob; std::vector<cv::mat> outs; std::vector<int> classids; std::vector<float> confidences; std::vector<cv::rect> boxes; cv::dnn::net net; void drawpred(int classid, float conf, int left, int top, int right, int bottom, cv::mat& frame); void sigmoid(cv::mat* out, int length); }; static inline float sigmoid_x(float x) { return static_cast<float>(1.f / (1.f + exp(-x))); } #endif // yolov5_h
yolov5.cpp
#include "yolov5.h" using namespace std; using namespace cv; void yolov5::initialization(netconfig conf) { this->confthreshold = conf.confthreshold; this->nmsthreshold = conf.nmsthreshold; this->objthreshold = conf.objthreshold; classids.reserve(20); confidences.reserve(20); boxes.reserve(20); outs.reserve(3); } bool yolov5::loadmodel(const char *onnxfile) { try { this->net = cv::dnn::readnetfromonnx(onnxfile); return true; } catch (exception& e) { qmessagebox::critical(null,"error",qstringliteral("模型加载出错,请检查重试!n %1").arg(e.what()),qmessagebox::yes,qmessagebox::yes); return false; } this->net.setpreferablebackend(cv::dnn::dnn_backend_inference_engine); this->net.setpreferabletarget(cv::dnn::dnn_target_cpu); // this->net.setpreferablebackend(cv::dnn::dnn_backend_cuda); // this->net.setpreferabletarget(cv::dnn::dnn_target_cuda); // try { // this->net.setpreferablebackend(cv::dnn::dnn_backend_cuda); // this->net.setpreferabletarget(cv::dnn::dnn_target_cuda); // } catch (exception& e2) { // this->net.setpreferablebackend(cv::dnn::dnn_backend_default); // this->net.setpreferabletarget(cv::dnn::dnn_target_cpu); // qmessagebox::warning(null,"warning",qstringliteral("正在使用cpu推理!n %1").arg(e2.what()),qmessagebox::yes,qmessagebox::yes); // return false; // } } void yolov5::detect(cv::mat &frame) { cv::dnn::blobfromimage(frame, blob, 1 / 255.0, size(this->inpwidth, this->inpheight), scalar(0, 0, 0), true, false); this->net.setinput(blob); this->net.forward(outs, this->net.getunconnectedoutlayersnames()); /generate proposals classids.clear(); confidences.clear(); boxes.clear(); float ratioh = (float)frame.rows / this->inpheight, ratiow = (float)frame.cols / this->inpwidth; int n = 0, q = 0, i = 0, j = 0, nout = 8 + 5, c = 0; for (n = 0; n < 3; n++) ///尺度 { int num_grid_x = (int)(this->inpwidth / this->stride[n]); int num_grid_y = (int)(this->inpheight / this->stride[n]); int area = num_grid_x * num_grid_y; this->sigmoid(&outs[n], 3 * nout * area); for (q = 0; q < 3; q++) ///anchor数 { const float anchor_w = this->anchors[n][q * 2]; const float anchor_h = this->anchors[n][q * 2 + 1]; float* pdata = (float*)outs[n].data + q * nout * area; for (i = 0; i < num_grid_y; i++) { for (j = 0; j < num_grid_x; j++) { float box_score = pdata[4 * area + i * num_grid_x + j]; if (box_score > this->objthreshold) { float max_class_socre = 0, class_socre = 0; int max_class_id = 0; for (c = 0; c < 80; c++) get max socre { class_socre = pdata[(c + 5) * area + i * num_grid_x + j]; if (class_socre > max_class_socre) { max_class_socre = class_socre; max_class_id = c; } } if (max_class_socre > this->confthreshold) { float cx = (pdata[i * num_grid_x + j] * 2.f - 0.5f + j) * this->stride[n]; ///cx float cy = (pdata[area + i * num_grid_x + j] * 2.f - 0.5f + i) * this->stride[n]; ///cy float w = powf(pdata[2 * area + i * num_grid_x + j] * 2.f, 2.f) * anchor_w; ///w float h = powf(pdata[3 * area + i * num_grid_x + j] * 2.f, 2.f) * anchor_h; ///h int left = (cx - 0.5*w)*ratiow; int top = (cy - 0.5*h)*ratioh; ///坐标还原到原图上 classids.push_back(max_class_id); confidences.push_back(max_class_socre); boxes.push_back(rect(left, top, (int)(w*ratiow), (int)(h*ratioh))); } } } } } } // perform non maximum suppression to eliminate redundant overlapping boxes with // lower confidences vector<int> indices; cv::dnn::nmsboxes(boxes, confidences, this->confthreshold, this->nmsthreshold, indices); for (size_t i = 0; i < indices.size(); ++i) { int idx = indices[i]; rect box = boxes[idx]; this->drawpred(classids[idx], confidences[idx], box.x, box.y, box.x + box.width, box.y + box.height, frame); } } void yolov5::drawpred(int classid, float conf, int left, int top, int right, int bottom, mat &frame) { rectangle(frame, point(left, top), point(right, bottom), scalar(0, 0, 255), 3); string label = format("%.2f", conf); label = this->classes[classid] + ":" + label; int baseline; size labelsize = gettextsize(label, font_hershey_simplex, 0.5, 1, &baseline); top = max(top, labelsize.height); puttext(frame, label, point(left, top), font_hershey_simplex, 0.75, scalar(0, 255, 0), 1); } void yolov5::sigmoid(mat *out, int length) { float* pdata = (float*)(out->data); int i = 0; for (i = 0; i < length; i++) { pdata[i] = 1.0 / (1 + expf(-pdata[i])); } }
三、效果演示
到此这篇关于qt结合opencv部署yolov5的实现的文章就介绍到这了,更多相关qt opencv部署yolov5内容请搜索<计算机技术网(www.ctvol.com)!!>以前的文章或继续浏览下面的相关文章希望大家以后多多支持<计算机技术网(www.ctvol.com)!!>!
需要了解更多c/c++开发分享Qt结合OpenCV部署yolov5的实现,都可以关注C/C++技术分享栏目—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/1076924.html