YOLOv3在OpenCV4.0.0/OpenCV3.4.2上的C++ demo实现

2018年11月20日 15:53:05 Andyoyo007 阅读数:1650

参考:

[1] https://pjreddie.com/darknet/yolo/

[2] https://www.learnopencv.com/deep-learning-based-object-detection-using-yolov3-with-opencv-python-c/

1. 运行环境:

Ubuntu16.04+OpenCV3.4.2/OpenCV4.0.0

Intel® Core™ i7-8700K CPU @ 3.70GHz × 12

GeForce GTX 1060 5GB/PCIe/SSE2

注:未使用GPU,在CPU上运行,大约160ms/帧图像,貌似OpenCV对其做了优化,我尝试过直接编译darknet的源码用CPU运行,每张图片需要30s+。

2. yolo_opencv.cpp

对参考网址上的代码进行了整合和修改,能够读取图片、视频文件、摄像头。

 
  1. //YOLOv3 on OpenCV

  2. //reference:https://www.learnopencv.com/deep-learning-based-object-detection-using-yolov3-with-opencv-python-c/

  3. //by:Andyoyo@swust

  4. //data:2018.11.20

  5. #include <opencv2/opencv.hpp>

  6. #include <opencv2/dnn.hpp>

  7. #include <opencv2/dnn/shape_utils.hpp>

  8. #include <opencv2/imgproc.hpp>

  9. #include <opencv2/highgui.hpp>

  10. #include <iostream>

  11. #include <fstream>

  12. // Remove the bounding boxes with low confidence using non-maxima suppression

  13. void postprocess(cv::Mat& frame, std::vector<cv::Mat>& outs);

  14. // Get the names of the output layers

  15. std::vector<cv::String> getOutputsNames(const cv::dnn::Net& net);

  16. // Draw the predicted bounding box

  17. void drawPred(int classId, float conf, int left, int top, int right, int bottom, cv::Mat& frame);

  18. // Initialize the parameters

  19. float confThreshold = 0.5; // Confidence threshold

  20. float nmsThreshold = 0.4; // Non-maximum suppression threshold

  21. int inpWidth = 416; // Width of network's input image

  22. int inpHeight = 416; // Height of network's input image

  23. static const char* about =

  24. "This sample uses You only look once (YOLO)-Detector (https://arxiv.org/abs/1612.08242) to detect objects on camera/video/image.\n"

  25. "Models can be downloaded here: https://pjreddie.com/darknet/yolo/\n"

  26. "Default network is 416x416.\n"

  27. "Class names can be downloaded here: https://github.com/pjreddie/darknet/tree/master/data\n";

  28. static const char* params =

  29. "{ help | false | ./yolo_opencv -source=../data/3.avi }"

  30. "{ source | ../data/dog.jpg | image or video for detection }"

  31. "{ device | 0 | video for detection }"

  32. "{ save | false | save result }";

  33. std::vector<std::string> classes;

  34. int main(int argc, char** argv)

  35. {

  36. cv::CommandLineParser parser(argc, argv, params);

  37. // Load names of classes

  38. std::string classesFile = "../coco.names";

  39. std::ifstream classNamesFile(classesFile.c_str());

  40. if (classNamesFile.is_open())

  41. {

  42. std::string className = "";

  43. while (std::getline(classNamesFile, className))

  44. classes.push_back(className);

  45. }

  46. else{

  47. std::cout<<"can not open classNamesFile"<<std::endl;

  48. }

  49. // Give the configuration and weight files for the model

  50. cv::String modelConfiguration = "../yolov3.cfg";

  51. cv::String modelWeights = "../yolov3.weights";

  52. // Load the network

  53. cv::dnn::Net net = cv::dnn::readNetFromDarknet(modelConfiguration, modelWeights);

  54. std::cout<<"Read Darknet..."<<std::endl;

  55. net.setPreferableBackend(cv::dnn::DNN_BACKEND_OPENCV);

  56. net.setPreferableTarget(cv::dnn::DNN_TARGET_CPU);

  57. cv::String outputFile = "../data/yolo_out_cpp.avi";

  58. std::string str;

  59. cv::VideoCapture cap;

  60. double frame_count;

  61. if (parser.get<bool>("help"))

  62. {

  63. std::cout << about << std::endl;

  64. parser.printMessage();

  65. return 0;

  66. }

  67. if (parser.get<cv::String>("source").empty())

  68. {

  69. int cameraDevice = parser.get<int>("device");

  70. cap = cv::VideoCapture(cameraDevice);

  71. if (!cap.isOpened())

  72. {

  73. std::cout << "Couldn't find camera: " << cameraDevice << std::endl;

  74. return -1;

  75. }

  76. }

  77. else

  78. {

  79. str=parser.get<cv::String>("source");

  80. cap.open(str);

  81. if (!cap.isOpened())

  82. {

  83. std::cout << "Couldn't open image or video: " << parser.get<cv::String>("video") << std::endl;

  84. return -1;

  85. }

  86. frame_count=cap.get(cv::CAP_PROP_FRAME_COUNT);

  87. std::cout<<"frame_count:"<<frame_count<<std::endl;

  88. }

  89. // Get the video writer initialized to save the output video

  90. cv::VideoWriter video;

  91. if (parser.get<bool>("save"))

  92. {

  93. if(frame_count>1)

  94. {

  95. video.open(outputFile, cv::VideoWriter::fourcc('M','J','P','G'), 28, cv::Size(cap.get(cv::CAP_PROP_FRAME_WIDTH),cap.get(cv::CAP_PROP_FRAME_HEIGHT)));

  96. }

  97. else

  98. {

  99. str.replace(str.end()-4, str.end(), "_yolo_out.jpg");

  100. outputFile = str;

  101. }

  102. }

  103. // Process frames.

  104. std::cout <<"Processing..."<<std::endl;

  105. cv::Mat frame;

  106. while (1)

  107. {

  108. // get frame from the video

  109. cap >> frame;

  110. // Stop the program if reached end of video

  111. if (frame.empty()) {

  112. std::cout << "Done processing !!!" << std::endl;

  113. if(parser.get<bool>("save"))

  114. std::cout << "Output file is stored as " << outputFile << std::endl;

  115. std::cout << "Please enter Esc to quit!" << std::endl;

  116. if(cv::waitKey(0)==27)

  117. break;

  118. }

  119. //show frame

  120. cv::imshow("frame",frame);

  121. // Create a 4D blob from a frame.

  122. cv::Mat blob;

  123. cv::dnn::blobFromImage(frame, blob, 1/255.0, cv::Size(inpWidth, inpHeight), cv::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. std::vector<cv::Mat> outs;

  128. net.forward(outs, getOutputsNames(net));

  129. // Remove the bounding boxes with low confidence

  130. postprocess(frame, 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. std::vector<double> layersTimes;

  134. double freq = cv::getTickFrequency() / 1000;

  135. double t = net.getPerfProfile(layersTimes) / freq;

  136. std::string label = cv::format("Inference time for a frame : %.2f ms", t);

  137. cv::putText(frame, label, cv::Point(0, 15), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 255));

  138. // Write the frame with the detection boxes

  139. cv::Mat detectedFrame;

  140. frame.convertTo(detectedFrame, CV_8U);

  141. //show detectedFrame

  142. cv::imshow("detectedFrame",detectedFrame);

  143. //save result

  144. if(parser.get<bool>("save"))

  145. {

  146. if(frame_count>1)

  147. {

  148. video.write(detectedFrame);

  149. }

  150. else

  151. {

  152. cv::imwrite(outputFile, detectedFrame);

  153. }

  154. }

  155. if(cv::waitKey(10)==27)

  156. {

  157. break;

  158. }

  159. }

  160. std::cout<<"Esc..."<<std::endl;

  161. return 0;

  162. }

  163. // Get the names of the output layers

  164. std::vector<cv::String> getOutputsNames(const cv::dnn::Net& net)

  165. {

  166. static std::vector<cv::String> names;

  167. if (names.empty())

  168. {

  169. //Get the indices of the output layers, i.e. the layers with unconnected outputs

  170. std::vector<int> outLayers = net.getUnconnectedOutLayers();

  171. //get the names of all the layers in the network

  172. std::vector<cv::String> layersNames = net.getLayerNames();

  173. // Get the names of the output layers in names

  174. names.resize(outLayers.size());

  175. for (size_t i = 0; i < outLayers.size(); ++i)

  176. names[i] = layersNames[outLayers[i] - 1];

  177. }

  178. return names;

  179. }

  180. // Remove the bounding boxes with low confidence using non-maxima suppression

  181. void postprocess(cv::Mat& frame, std::vector<cv::Mat>& outs)

  182. {

  183. std::vector<int> classIds;

  184. std::vector<float> confidences;

  185. std::vector<cv::Rect> boxes;

  186. for (size_t i = 0; i < outs.size(); ++i)

  187. {

  188. // Scan through all the bounding boxes output from the network and keep only the

  189. // ones with high confidence scores. Assign the box's class label as the class

  190. // with the highest score for the box.

  191. float* data = (float*)outs[i].data;

  192. for (int j = 0; j < outs[i].rows; ++j, data += outs[i].cols)

  193. {

  194. cv::Mat scores = outs[i].row(j).colRange(5, outs[i].cols);

  195. cv::Point classIdPoint;

  196. double confidence;

  197. // Get the value and location of the maximum score

  198. cv::minMaxLoc(scores, 0, &confidence, 0, &classIdPoint);

  199. if (confidence > confThreshold)

  200. {

  201. int centerX = (int)(data[0] * frame.cols);

  202. int centerY = (int)(data[1] * frame.rows);

  203. int width = (int)(data[2] * frame.cols);

  204. int height = (int)(data[3] * frame.rows);

  205. int left = centerX - width / 2;

  206. int top = centerY - height / 2;

  207. classIds.push_back(classIdPoint.x);

  208. confidences.push_back((float)confidence);

  209. boxes.push_back(cv::Rect(left, top, width, height));

  210. }

  211. }

  212. }

  213. // Perform non maximum suppression to eliminate redundant overlapping boxes with

  214. // lower confidences

  215. std::vector<int> indices;

  216. cv::dnn::NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, indices);

  217. for (size_t i = 0; i < indices.size(); ++i)

  218. {

  219. int idx = indices[i];

  220. cv::Rect box = boxes[idx];

  221. drawPred(classIds[idx], confidences[idx], box.x, box.y,

  222. box.x + box.width, box.y + box.height, frame);

  223. }

  224. }

  225. // Draw the predicted bounding box

  226. void drawPred(int classId, float conf, int left, int top, int right, int bottom, cv::Mat& frame)

  227. {

  228. //Draw a rectangle displaying the bounding box

  229. cv::rectangle(frame, cv::Point(left, top), cv::Point(right, bottom), cv::Scalar(0, 0, 255));

  230. //Get the label for the class name and its confidence

  231. std::string label = cv::format("%.2f", conf);

  232. if (!classes.empty())

  233. {

  234. CV_Assert(classId < (int)classes.size());

  235. label = classes[classId] + ":" + label;

  236. }

  237. else

  238. {

  239. std::cout<<"classes is empty..."<<std::endl;

  240. }

  241. //Display the label at the top of the bounding box

  242. int baseLine;

  243. cv::Size labelSize = cv::getTextSize(label, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);

  244. top = std::max(top, labelSize.height);

  245. cv::putText(frame, label, cv::Point(left, top), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255,255,255));

  246. }

3. CMakeLists.txt

本人使用的环境安装了OpenCV3.4.2和4.0.0两个版本,均调试通过,不用修改源码,只需在CMakeLists.txt文件中指定OpenCV版本即可。

 
  1. cmake_minimum_required(VERSION 2.8)

  2. #OpenCV4 must enable c++11

  3. add_definitions(-std=c++11)

  4. #setOpenCV_DIR

  5. #set(OpenCV_DIR "/home/andyoyo/opencv/opencv-4.0.0-beta/build")

  6. project(yolo_opencv)

  7. find_package(OpenCV 4 REQUIRED)

  8. #print OpenCV_VERSION on terminal

  9. message(STATUS "OpenCV_VERSION:" ${OpenCV_VERSION})

  10. file(GLOB native_srcs "src/*.cpp")

  11. add_executable(${PROJECT_NAME} ${native_srcs})

  12. target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS} )

4. 其他说明

运行前先下载yolov3的配置文件等,包括:coco.names,yolov3.cfg,yolov3.weights三个文件,可通过wget下载。

 
  1. wget https://github.com/pjreddie/darknet/blob/master/data/coco.names?raw=true -O ./coco.names

  2. wget https://github.com/pjreddie/darknet/blob/master/cfg/yolov3.cfg?raw=true -O ./yolov3.cfg

  3. wget https://pjreddie.com/media/files/yolov3.weights

5.运行效果:

YOLOv3在OpenCV4.0.0/OpenCV3.4.2上的C++ demo实现相关推荐

  1. ubuntu16.0.4 opencv4.0.0 yolov3测试

    https://github.com/spmallick/learnopencv/tree/master/ObjectDetection-YOLO 硬件信息 8 Intel® Core™ i7-479 ...

  2. Ros noetic opencv4.2.0 cv_bridge 冲突 适配Opencv3.2.0完成自己的USB_Camera 跑通 Orb_slam2

    前言: 本文附上使用自己的USB_Cam 跑通Orb_Slam2 算法的过程,以及解决cv_bridge冲突的方案 Orb_Slam2 需要opencv3.2.0 的cv版本 但是ubantu20.0 ...

  3. VS2019中配置opencv4.3.0(亲测有效)

    写在前面:之前一直使用vs2017+opencv的配置,现在体验vs2019+opencv 4.3.0的配置.由于之前的配置相隔很久,忘记很多东西,如今重新配置还是踩了很多坑,记录如下,希望对读者有帮 ...

  4. Qt Creator5.12配置OpenCV4.3.0和opencv_contrib扩展包(亲测有效)

    本文结构 第一部分 只安装Qt Creator和配置OpenCV 1.Qt Creator5.12.2下载与安装 2.Cmake下载与安装 3.OpenCV下载 4.编译OpenCV 5.测试Qt程序 ...

  5. linux下安装opencv4.4.0

    简介 opencv4.4.0和opencv_contrib-4.4.0以及编译过程中缺少的文件 链接:https://pan.baidu.com/s/11D6G3TbRY_-oNYlP4FDnTA  ...

  6. Anaconda Python3.6 OpenCV4.1.0 Ubuntu 16.04源码编译

    Anaconda Python3.6 OpenCV4.1.0 Ubuntu 16.04源码编译 转载于:https://blog.csdn.net/phdsky/article/details/782 ...

  7. opencv:centos7中安装opencv4.3.0环境

    准备 安装依赖 sudo yum -y install epel-release # 安装epel扩展源 sudo yum -y install git gcc gcc-c++ cmake3 sudo ...

  8. windows11编译OpenCV4.5.0 with CUDA(附注意事项)

    windows11编译OpenCV4.5.0 with CUDA 从OpenCV4.2.0 版本开始允许使用 Nvidia GPU 来加速推理.本文介绍最近使用windows11系统编译带CUDA的O ...

  9. 【安装教程】Ubuntu18.04中用CMake-gui安装OpenCV4.1.0和OpenCV_contrib-4.1.0(图文)

    目录 一.简要说明 二.下载和添加依赖包 三.配置OpenCV 四.配置环境变量 新建一个 opecv.pc (勾选了就跳过此步骤,勾选生成的opencv4.pc 我印象中好像不用修改的,不放心可以打 ...

最新文章

  1. 【强化学习篇】--强化学习从初识到应用
  2. OpenOffce在Centos7安装和使用
  3. 使用 Bamboo 构建项目的 CICD 过程文档
  4. C++直接初始化与复制初始化的区别深入解析
  5. spring中AOP动态代理的两种方式
  6. 图表插件Highcharts的动态化赋值,实现图表数据的动态化设置显示
  7. has_a php,PHP has encountered a Stack overflow问题解决方法
  8. android:showAsAction 无效
  9. 7-161 梅森数 (20 分)
  10. 页面中动态画有超连接的图
  11. 每天一道剑指offer-二叉搜索数的后序遍历序列
  12. 2021-05-15 SqlServer面试题 通用篇
  13. Facebook全新数字货币Libra引发关注 数字货币国际化逐渐发展
  14. 《MLB棒球创造营》:走近棒球运动·纽约扬基队
  15. python学习第二天——编写名片
  16. 打破定制化语音技术落地怪圈?从讲一口标准英音的语音助手说起
  17. java affinity_sched_setaffinity()如何工作?
  18. Pytorch构建Transformer实现英文翻译
  19. win10系统日语输入法只能打出英文字母无法切换微软输入法无法使用
  20. 最小均方算法二分类(基于双月数据集)

热门文章

  1. OpenStack在dashboard界面点击管理员网络,服务器页面出错
  2. 最大似然估计学习总结
  3. hadoop启动页面_轻松搞定Windows下的Hadoop环境安装
  4. linux通过tftp下载的文件大小为0,linux 通过 tftp下载文件
  5. java 文本压缩_[Java基础]Java使用GZIP进行文本压缩
  6. easyexcel导入固定sheet_easyexcel指定多个sheet导excel数据
  7. Linux安装redis最新版5.0.8
  8. 2020黑群晖最稳定版本_打造完美6.2.3黑群晖,正确显示 CPU,支持Nvme缓存
  9. 计算机word做课程表实验报告,word制作课程表.doc
  10. 线程 信号量 java_JAVA多线程-Semaphore信号量