You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

181 lines
6.0 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. // yolo_example.cpp - minimal YOLO object detection with Darknet (hank-ai, V3+) and OpenCV
  2. //
  3. // Build: see Makefile (g++ -std=c++17 ... $(pkg-config --cflags --libs opencv4) -ldarknet)
  4. //
  5. // Usage:
  6. // yolo_example <cfg> <names> <weights> <input> [threshold]
  7. //
  8. // <input> an image file (jpg/png/...), a video file, or a camera number (0, 1, ...)
  9. //
  10. // Image: detections are printed and the annotated picture is saved as <name>_output.jpg
  11. // Video / every frame is detected and shown in a window ('q' or Esc to quit);
  12. // camera with no display (e.g. over ssh) the annotated video is written to output.avi
  13. //
  14. // Example (YOLOv4-tiny trained on COCO):
  15. // yolo_example yolov4-tiny.cfg coco.names yolov4-tiny.weights dog.jpg 0.30
  16. #include <darknet.hpp> // Darknet C++ API (also pulls in darknet.h and opencv2/opencv.hpp)
  17. #include <chrono>
  18. #include <cstdlib>
  19. #include <filesystem>
  20. #include <iostream>
  21. #include <string>
  22. namespace
  23. {
  24. // "0", "1", ... -> camera index
  25. bool isCameraIndex(const std::string & s)
  26. {
  27. return ! s.empty() && s.find_first_not_of("0123456789") == std::string::npos;
  28. }
  29. bool isImageFile(const std::filesystem::path & p)
  30. {
  31. std::string ext = p.extension().string();
  32. for (auto & c : ext) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
  33. return ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tif" || ext == ".tiff" || ext == ".webp";
  34. }
  35. // Prints one line per detected object: class, confidence and box in pixels
  36. void printPredictions(const Darknet::NetworkPtr net, const Darknet::Predictions & predictions)
  37. {
  38. const Darknet::VStr & names = Darknet::get_class_names(net);
  39. for (const auto & p : predictions)
  40. {
  41. if (p.best_class < 0)
  42. {
  43. continue; // nothing above the threshold
  44. }
  45. const float confidence = p.prob.count(p.best_class) ? p.prob.at(p.best_class) : 0.0f;
  46. std::cout << " " << names.at(p.best_class)
  47. << " " << static_cast<int>(confidence * 100.0f + 0.5f) << "%"
  48. << " x=" << p.rect.x << " y=" << p.rect.y
  49. << " w=" << p.rect.width << " h=" << p.rect.height << std::endl;
  50. }
  51. }
  52. int runImage(Darknet::NetworkPtr net, const std::filesystem::path & file)
  53. {
  54. cv::Mat image = cv::imread(file.string()); // BGR, as Darknet expects
  55. if (image.empty())
  56. {
  57. std::cerr << "Cannot read image " << file << std::endl;
  58. return 1;
  59. }
  60. const auto t0 = std::chrono::steady_clock::now();
  61. const Darknet::Predictions predictions = Darknet::predict(net, image);
  62. const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - t0).count();
  63. std::cout << file.filename().string() << ": " << predictions.size() << " object(s) in " << ms << " ms" << std::endl;
  64. printPredictions(net, predictions);
  65. // annotate() draws boxes and labels on the Mat it gets (and returns it)
  66. cv::Mat output = Darknet::annotate(net, predictions, image.clone());
  67. const std::filesystem::path outFile = file.parent_path() / (file.stem().string() + "_output.jpg");
  68. cv::imwrite(outFile.string(), output, {cv::IMWRITE_JPEG_QUALITY, 90});
  69. std::cout << "Saved " << outFile.string() << std::endl;
  70. return 0;
  71. }
  72. int runVideo(Darknet::NetworkPtr net, const std::string & input)
  73. {
  74. cv::VideoCapture cap;
  75. if (isCameraIndex(input))
  76. {
  77. cap.open(std::stoi(input));
  78. }
  79. else
  80. {
  81. cap.open(input);
  82. }
  83. if (! cap.isOpened())
  84. {
  85. std::cerr << "Cannot open video/camera " << input << std::endl;
  86. return 1;
  87. }
  88. // Without a display (DISPLAY unset), write the result to a file instead of showing it
  89. const bool haveDisplay = std::getenv("DISPLAY") != nullptr || std::getenv("WAYLAND_DISPLAY") != nullptr;
  90. cv::VideoWriter writer;
  91. cv::Mat frame;
  92. size_t frames = 0;
  93. const auto t0 = std::chrono::steady_clock::now();
  94. while (cap.read(frame) && ! frame.empty())
  95. {
  96. const Darknet::Predictions predictions = Darknet::predict(net, frame);
  97. Darknet::annotate(net, predictions, frame);
  98. frames++;
  99. if (haveDisplay)
  100. {
  101. cv::imshow("YOLO", frame);
  102. const int key = cv::waitKey(1);
  103. if (key == 'q' || key == 27)
  104. {
  105. break;
  106. }
  107. }
  108. else
  109. {
  110. if (! writer.isOpened())
  111. {
  112. double fps = cap.get(cv::CAP_PROP_FPS);
  113. if (fps <= 0.0) fps = 25.0;
  114. writer.open("output.avi", cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), fps, frame.size());
  115. std::cout << "No display: writing output.avi" << std::endl;
  116. }
  117. writer.write(frame);
  118. if (frames % 100 == 0)
  119. {
  120. std::cout << frames << " frames" << std::endl;
  121. }
  122. }
  123. }
  124. const double seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
  125. std::cout << frames << " frames, " << (seconds > 0.0 ? frames / seconds : 0.0) << " FPS" << std::endl;
  126. return 0;
  127. }
  128. }
  129. int main(int argc, char * argv[])
  130. {
  131. if (argc < 5)
  132. {
  133. std::cerr << "Usage: " << argv[0] << " <cfg> <names> <weights> <image|video|camera> [threshold]" << std::endl;
  134. return 1;
  135. }
  136. const std::filesystem::path cfgFile = argv[1];
  137. const std::filesystem::path namesFile = argv[2];
  138. const std::filesystem::path weightsFile = argv[3];
  139. const std::string input = argv[4];
  140. const float threshold = (argc > 5) ? std::stof(argv[5]) : 0.25f;
  141. Darknet::NetworkPtr net = nullptr;
  142. try
  143. {
  144. // Darknet::set_gpu_index(0); // with a CUDA build of Darknet: select the GPU before loading
  145. net = Darknet::load_neural_network(cfgFile, namesFile, weightsFile);
  146. int w = 0, h = 0, c = 0;
  147. Darknet::network_dimensions(net, w, h, c);
  148. std::cout << "Network " << w << "x" << h << "x" << c << ", "
  149. << Darknet::get_class_names(net).size() << " classes" << std::endl;
  150. Darknet::set_detection_threshold(net, threshold); // minimum confidence (default 0.25)
  151. Darknet::set_non_maximal_suppression_threshold(net, 0.45f); // overlap for merging boxes (default 0.45)
  152. const int rc = isImageFile(input) ? runImage(net, input) : runVideo(net, input);
  153. Darknet::free_neural_network(net);
  154. return rc;
  155. }
  156. catch (const std::exception & e)
  157. {
  158. std::cerr << "Error: " << e.what() << std::endl;
  159. Darknet::free_neural_network(net);
  160. return 1;
  161. }
  162. }