当前位置:网站首页>Source code | opencv DNN + yolov7 target detection
Source code | opencv DNN + yolov7 target detection
2022-07-25 04:24:00 【Opencv school】
Click on the blue words above to follow us
author : Wang Bo , Polar view technology algorithm researcher WeChat official account :OpenCV School Focus on getting more computer vision and deep learning knowledge
Briefly explain
Separate use OpenCV、ONNXRuntime Deploy YOLOV7 object detection , It includes 12 individual onnx Model , Still contains C++ and Python Two versions of the program .
Write this set YOLOV7 The program , It is the same as that written before YOLOV6 The program , Most of the source code is the same , The difference is only that the process of image preprocessing is different .YOLOV7 The image preprocessing of is BGR2RGB+ Do not maintain the aspect ratio resize+ Divide 255
because onnx too many files , Unable to upload directly to the warehouse , You need to download from Baidu cloud disk ,
link : https://pan.baidu.com/s/1FoC0n7qMz4Fz0RtDGpI6xQ password : 7mhsAfter downloading, put models The directory is placed in the directory of the main program file , Compile operation
Use opencv Deployed programs , There is a problem to be optimized .onnxruntime Read .onnx File can get the shape information of the input tensor , however opencv Of dnn Module read .onnx The file cannot obtain the shape information of the input tensor , Now it's based on .onnx File name to parse the string to get the height and width of the input tensor .
YOLOV7 The training source code is :
https://github.com/WongKinYiu/yolov7Follow YOLOR It's from the same author .
OpenCV+YOLOv7
The reasoning process is the same as before YOLO A series of deployment code can be mostly reused ! I'm not going to repeat it here , See the source code in detail as follows : The output part directly parses the last output layer !
The detailed implementation code is as follows :
#include <fstream>
#include <sstream>
#include <iostream>
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
using namespace cv;
using namespace dnn;
using namespace std;
struct Net_config
{
float confThreshold; // Confidence threshold
float nmsThreshold; // Non-maximum suppression threshold
string modelpath;
};
class YOLOV7
{
public:
YOLOV7(Net_config config);
void detect(Mat& frame);
private:
int inpWidth;
int inpHeight;
vector<string> class_names;
int num_class;
float confThreshold;
float nmsThreshold;
Net net;
void drawPred(float conf, int left, int top, int right, int bottom, Mat& frame, int classid);
};
YOLOV7::YOLOV7(Net_config config)
{
this->confThreshold = config.confThreshold;
this->nmsThreshold = config.nmsThreshold;
this->net = readNet(config.modelpath);
ifstream ifs("coco.names");
string line;
while (getline(ifs, line)) this->class_names.push_back(line);
this->num_class = class_names.size();
size_t pos = config.modelpath.find("_");
int len = config.modelpath.length() - 6 - pos;
string hxw = config.modelpath.substr(pos + 1, len);
pos = hxw.find("x");
string h = hxw.substr(0, pos);
len = hxw.length() - pos;
string w = hxw.substr(pos + 1, len);
this->inpHeight = stoi(h);
this->inpWidth = stoi(w);
}
void YOLOV7::drawPred(float conf, int left, int top, int right, int bottom, Mat& frame, int classid) // Draw the predicted bounding box
{
//Draw a rectangle displaying the bounding box
rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 0, 255), 2);
//Get the label for the class name and its confidence
string label = format("%.2f", conf);
label = this->class_names[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 YOLOV7::detect(Mat& frame)
{
Mat blob = blobFromImage(frame, 1 / 255.0, Size(this->inpWidth, this->inpHeight), Scalar(0, 0, 0), true, false);
this->net.setInput(blob);
vector<Mat> outs;
this->net.forward(outs, this->net.getUnconnectedOutLayersNames());
int num_proposal = outs[0].size[0];
int nout = outs[0].size[1];
if (outs[0].dims > 2)
{
num_proposal = outs[0].size[1];
nout = outs[0].size[2];
outs[0] = outs[0].reshape(0, num_proposal);
}
/////generate proposals
vector<float> confidences;
vector<Rect> boxes;
vector<int> classIds;
float ratioh = (float)frame.rows / this->inpHeight, ratiow = (float)frame.cols / this->inpWidth;
int n = 0, row_ind = 0; ///cx,cy,w,h,box_score,class_score
float* pdata = (float*)outs[0].data;
for (n = 0; n < num_proposal; n++) ///ÌØÕ÷ͼ³ß¶È
{
float box_score = pdata[4];
if (box_score > this->confThreshold)
{
Mat scores = outs[0].row(row_ind).colRange(5, nout);
Point classIdPoint;
double max_class_socre;
// Get the value and location of the maximum score
minMaxLoc(scores, 0, &max_class_socre, 0, &classIdPoint);
max_class_socre *= box_score;
if (max_class_socre > this->confThreshold)
{
const int class_idx = classIdPoint.x;
float cx = pdata[0] * ratiow; ///cx
float cy = pdata[1] * ratioh; ///cy
float w = pdata[2] * ratiow; ///w
float h = pdata[3] * ratioh; ///h
int left = int(cx - 0.5 * w);
int top = int(cy - 0.5 * h);
confidences.push_back((float)max_class_socre);
boxes.push_back(Rect(left, top, (int)(w), (int)(h)));
classIds.push_back(class_idx);
}
}
row_ind++;
pdata += nout;
}
// Perform non maximum suppression to eliminate redundant overlapping boxes with
// lower confidences
vector<int> indices;
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(confidences[idx], box.x, box.y,
box.x + box.width, box.y + box.height, frame, classIds[idx]);
}
}
int main()
{
Net_config YOLOV7_nets = { 0.3, 0.5, "models/yolov7_736x1280.onnx" }; ////choices=["models/yolov7_736x1280.onnx", "models/yolov7-tiny_384x640.onnx", "models/yolov7_480x640.onnx", "models/yolov7_384x640.onnx", "models/yolov7-tiny_256x480.onnx", "models/yolov7-tiny_256x320.onnx", "models/yolov7_256x320.onnx", "models/yolov7-tiny_256x640.onnx", "models/yolov7_256x640.onnx", "models/yolov7-tiny_480x640.onnx", "models/yolov7-tiny_736x1280.onnx", "models/yolov7_256x480.onnx"]
YOLOV7 net(YOLOV7_nets);
string imgpath = "images/dog.jpg";
Mat srcimg = imread(imgpath);
net.detect(srcimg);
static const string kWinName = "Deep learning object detection in OpenCV";
namedWindow(kWinName, WINDOW_NORMAL);
imshow(kWinName, srcimg);
waitKey(0);
destroyAllWindows();
}Run the tests as follows :
The author of this article github Home page :
https://github.com/hpc203/yolov7-opencv-onnxrun-cpp-pyReading is better than reading
The heart wants to be specialized, not miscellaneous
Scan the code to check OpenCV+OpenVIO+Pytorch Systematic learning roadmap
Recommended reading
CV The full stack developer said - From traditional algorithm to deep learning, how to practice
2022 Pit depth learning , I choose Pytorch frame !
Pytorch Easily achieve classic visual tasks
Tutorial recommendation | Pytorch frame CV Development - From introduction to practice
OpenCV4 C++ Study Essential basic grammar knowledge 3
OpenCV4 C++ Study Essential basic grammar knowledge 2
OpenCV4.5.4 Face detection + Five o'clock landmark New functional testing
OpenCV4.5.4 Detailed explanation of face recognition and code demonstration
OpenCV Of binary image analysis Blob Analyze and find the circle
OpenCV4.5.x DNN + YOLOv5 C++ Reasoning
OpenCV4.5.4 Direct support for YOLOv5 6.1 Version model reasoning
OpenVINO2021.4+YOLOX Target detection model deployment test
Than YOLOv5 Not bad YOLOX coming , Official support OpenVINO Reasoning
边栏推荐
- Dig deep into data dividends, Intel and industry accelerate the implementation of digital economy
- Debezium series: optimize cluster parameters and support personalized settings of debezium connector
- Eve-ng lab simulator Cisco, H3C test host alias
- Kubesphere 3.3.0 offline installation tutorial
- Creativity: Modern Art anonymous oil painting AI works presentation
- (cvpr2020) reading of learning texture transformer network for image super resolution
- The difference between apply, call and bind
- Sudden! Britain accuses Huawei of major defects in its equipment (with report)
- [matlab] solve the mex error there was a problem creating the mex file for real time execution, please ensure y
- Es- retrieve the selected field from the search
猜你喜欢

Day008 select structure (switch statement)

Unity3d learning note 9 - loading textures

Maker concept design to adapt to popular education

Cluster clock synchronization configuration

Infinite connection · infinite collaboration | the first global enterprise communication cloud conference WECC is coming

数据中台建设(一):数据中台出现的背景

Eve-ng lab simulator Cisco, H3C test host alias

Analyze the exploration in high-quality steam Education
![[laser principle and application -5]: laser diode LD (laser diode) and laser diode driver (LD driver)](/img/1f/4e8ea92a93ed16d8e7944d4a5d22c9.png)
[laser principle and application -5]: laser diode LD (laser diode) and laser diode driver (LD driver)

Chapter 3 business function development (modify the remarks of market activities)
随机推荐
Win11 experience
Implementing DDD based on ABP -- domain logic and application logic
Infinite connection · infinite collaboration | the first global enterprise communication cloud conference WECC is coming
Advanced numbers | [calculus of multivariate function] chain derivation method, implicit function derivation method, total differential form invariance, multivariate function extremum
Internship in 2022
Optimize bubble sorting
Multithreading advanced Step2
What causes the wait event of TCP socket (kgas) in oracle?
LVGL 8.2 Tabview
Creativity: presentation of AI oil paintings with high imitation mineral pigments
Divide candy Huawei od JS
I want to ask you a question. I want to synchronize the database, but I think it is synchronized according to MySQL binlog. If it is a large table, one
Installation and tutorial of MATLAB curling simulation game
Analytic hierarchy process of MATLAB
Deeply understand the connection state and reliable mechanism of TCP protocol
GetData table table data join MySQL method
CVPR 2022 | content aware text logo image generation method
Kubesphere 3.3.0 offline installation tutorial
DOM event flow
TS learning (VII): interface and type compatibility of TS