当前位置:   article > 正文

OpenCV DNN模块官方教程(二)YoloV4目标检测实例_cv::dnn::nmsboxes

cv::dnn::nmsboxes

OpenCV DNN模块官方教程地址如下,可以查看各个对应的使用方法https://docs.opencv.org/4.4.0/d2/d58/tutorial_table_of_content_dnn.html

    今天介绍第五部分:加载darknet框架的YoloV4模型做目标检测,相较于官方文档更易理解,之所以选YoloV4,是因为YoloV4现已很流行,同时YoloV4和YoloV3在OpenCV DNN模块的使用方法相似,下面的代码只需要改动YoloV3对应的权重和配置文件就可以。

String config = "./model/yolov4.cfg";String weights = "./model/yolov4.weights";string classesFile = "./model/coco.names";

    上面三个文件的下载地址分别是:

https://raw.githubusercontent.com/AlexeyAB/darknet/master/cfg/yolov4.cfg

https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v3_optimal/yolov4.weights

https://github.com/pjreddie/darknet/blob/master/data/coco.names​​​​​​​

// 加载darknet网络Net net = readNetFromDarknet(config, weights);

    OpenCV DNN模块支持常见深度学习框架如TensorFlowCaffe、Darknet等,对应的函数:readNetFromTensorflow、readNetFromCaffe.

     下面是OpenCV DNN读取YoloV4模型进行图片检测代码和效果:  

  1. // DNN_YOLO_V4.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
  2. #include "pch.h"
  3. #include<opencv2/opencv.hpp>
  4. #include<opencv2/dnn.hpp>
  5. #include <iostream>
  6. #include <fstream>
  7. #include<istream>
  8. #include<string>
  9. using namespace std;
  10. using namespace cv;
  11. using namespace dnn;
  12. // 初始化参数
  13. float confThreshold = 0.5; // 置信度阈值
  14. float nmsThreshold = 0.4; // 非极大值抑制(NMS)阈值
  15. int inpWidth = 416; // 网络输入图像宽度
  16. int inpHeight = 416; // 网络输入图像高度
  17. // 加载类别名称文件
  18. vector<string>classes;
  19. // Load names of classes
  20. string classesFile = "./model/coco.names";
  21. ifstream ifs(classesFile.c_str());
  22. // 设置模型配置文件和权重
  23. String config = "./model/yolov4.cfg";
  24. String weights = "./model/yolov4.weights";
  25. // 加载网络
  26. Net net = readNetFromDarknet(config, weights);
  27. // 获取输出层名称
  28. vector<String> getOutputsNames(const Net& net)
  29. {
  30. static vector<String> names;
  31. if (names.empty())
  32. {
  33. //Get the indices of the output layers, i.e. the layers with unconnected outputs
  34. vector<int> outLayers = net.getUnconnectedOutLayers();
  35. //get the names of all the layers in the network
  36. vector<String> layersNames = net.getLayerNames();
  37. // Get the names of the output layers in names
  38. names.resize(outLayers.size());
  39. for (size_t i = 0; i < outLayers.size(); ++i)
  40. names[i] = layersNames[outLayers[i] - 1];
  41. }
  42. return names;
  43. }
  44. // Draw the predicted bounding box
  45. void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame)
  46. {
  47. //Draw a rectangle displaying the bounding box
  48. rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 0, 255), 2);
  49. //Get the label for the class name and its confidence
  50. string label = format("%.2f", conf);
  51. if (!classes.empty())
  52. {
  53. CV_Assert(classId < (int)classes.size());
  54. label = classes[classId] + ":" + label;
  55. }
  56. //Display the label at the top of the bounding box
  57. int baseLine;
  58. Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.8, 1, &baseLine);
  59. top = max(top, labelSize.height);
  60. putText(frame, label, Point(left, top), FONT_HERSHEY_SIMPLEX, 0.8, Scalar(0, 255, 0), 2);
  61. }
  62. // Remove the bounding boxes with low confidence using non-maxima suppression
  63. void postprocess(Mat& frame, const vector<Mat>& outs)
  64. {
  65. vector<int> classIds;
  66. vector<float> confidences;
  67. vector<Rect> boxes;
  68. for (size_t i = 0; i < outs.size(); ++i)
  69. {
  70. // Scan through all the bounding boxes output from the network and keep only the
  71. // ones with high confidence scores. Assign the box's class label as the class
  72. // with the highest score for the box.
  73. float* data = (float*)outs[i].data;
  74. for (int j = 0; j < outs[i].rows; ++j, data += outs[i].cols)
  75. {
  76. Mat scores = outs[i].row(j).colRange(5, outs[i].cols);
  77. Point classIdPoint;
  78. double confidence;
  79. // Get the value and location of the maximum score
  80. minMaxLoc(scores, 0, &confidence, 0, &classIdPoint);
  81. if (confidence > confThreshold)
  82. {
  83. int centerX = (int)(data[0] * frame.cols);
  84. int centerY = (int)(data[1] * frame.rows);
  85. int width = (int)(data[2] * frame.cols);
  86. int height = (int)(data[3] * frame.rows);
  87. int left = centerX - width / 2;
  88. int top = centerY - height / 2;
  89. classIds.push_back(classIdPoint.x);
  90. confidences.push_back((float)confidence);
  91. boxes.push_back(Rect(left, top, width, height));
  92. }
  93. }
  94. }
  95. // Perform non maximum suppression to eliminate redundant overlapping boxes with
  96. // lower confidences
  97. vector<int> indices;
  98. NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, indices);
  99. for (size_t i = 0; i < indices.size(); ++i)
  100. {
  101. int idx = indices[i];
  102. Rect box = boxes[idx];
  103. drawPred(classIds[idx], confidences[idx], box.x, box.y,
  104. box.x + box.width, box.y + box.height, frame);
  105. }
  106. }
  107. int main()
  108. {
  109. Mat img = imread("./1.jpg");
  110. if (img.empty())
  111. {
  112. cout << "Image read error, please check again!" << endl;
  113. }
  114. string line;
  115. while (getline(ifs, line))
  116. {
  117. classes.push_back(line);
  118. }
  119. net.setPreferableBackend(DNN_BACKEND_OPENCV);
  120. net.setPreferableTarget(DNN_TARGET_CPU);
  121. // Create a 4D blob from a frame.
  122. Mat blob;
  123. blobFromImage(img, blob, 1 / 255.0, Size(inpWidth, inpHeight), Scalar(0, 0, 0), true, false);
  124. //Sets the input to the network
  125. net.setInput(blob);
  126. // Runs the forward pass to get output of the output layers
  127. vector<Mat> outs;
  128. net.forward(outs, getOutputsNames(net));
  129. // Remove the bounding boxes with low confidence
  130. postprocess(img, outs);
  131. // Put efficiency information. The function getPerfProfile returns the
  132. // overall time for inference(t) and the timings for each of the layers(in layersTimes)
  133. vector<double> layersTimes;
  134. double freq = getTickFrequency() / 1000;
  135. double t = net.getPerfProfile(layersTimes) / freq;
  136. string label = format("Inference time for a frame : %.2f ms", t);
  137. putText(img, label, Point(0, 20), FONT_HERSHEY_SIMPLEX, 0.8, Scalar(255, 255, 0), 2);
  138. namedWindow("OpenCV_YoloV4_Demo", WINDOW_NORMAL);
  139. imshow("OpenCV_YoloV4_Demo", img);
  140. waitKey(0);
  141. return 0;
  142. }

下面是OpenCV DNN读取YoloV4模型进行视频检测代码和效果演示:

  1. int main()
  2. {
  3. string line;
  4. while (getline(ifs, line))
  5. {
  6. classes.push_back(line);
  7. }
  8. VideoCapture cap("./cars.mp4");
  9. Mat frame;
  10. while (1)
  11. {
  12. if (!cap.isOpened())
  13. {
  14. cout << "Video open failed, please check!" << endl;
  15. break;
  16. }
  17. cap.read(frame);
  18. if (frame.empty())
  19. {
  20. cout << "frame is empty, please check!" << endl;
  21. break;
  22. }
  23. net.setPreferableBackend(DNN_BACKEND_OPENCV);
  24. net.setPreferableTarget(DNN_TARGET_CPU);
  25. // Create a 4D blob from a frame.
  26. Mat blob;
  27. blobFromImage(frame, blob, 1 / 255.0, Size(inpWidth, inpHeight), Scalar(0, 0, 0), true, false);
  28. //Sets the input to the network
  29. net.setInput(blob);
  30. // Runs the forward pass to get output of the output layers
  31. vector<Mat> outs;
  32. net.forward(outs, getOutputsNames(net));
  33. // Remove the bounding boxes with low confidence
  34. postprocess(frame, outs);
  35. // Put efficiency information. The function getPerfProfile returns the
  36. // overall time for inference(t) and the timings for each of the layers(in layersTimes)
  37. vector<double> layersTimes;
  38. double freq = getTickFrequency() / 1000;
  39. double t = net.getPerfProfile(layersTimes) / freq;
  40. string label = format("Inference time for a frame : %.2f ms", t);
  41. putText(frame, label, Point(0, 20), FONT_HERSHEY_SIMPLEX, 0.8, Scalar(255, 255, 0), 2);
  42. namedWindow("OpenCV_YoloV4_Demo", WINDOW_NORMAL);
  43. imshow("OpenCV_YoloV4_Demo", frame);
  44. int c = waitKey(1);
  45. if (c == 27)
  46. break;
  47. }
  48. return 0;
  49. }

使用net.setPreferableBackend()函数还可以设置OpenVINO加速,后续有机会再做介绍,

更多资讯请关注公众号:OpenCV与AI深度学习

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/599326
推荐阅读
相关标签
  

闽ICP备14008679号