// yolo_example.cpp - minimal YOLO object detection with Darknet (hank-ai, V3+) and OpenCV // // Build: see Makefile (g++ -std=c++17 ... $(pkg-config --cflags --libs opencv4) -ldarknet) // // Usage: // yolo_example [threshold] // // an image file (jpg/png/...), a video file, or a camera number (0, 1, ...) // // Image: detections are printed and the annotated picture is saved as _output.jpg // Video / every frame is detected and shown in a window ('q' or Esc to quit); // camera with no display (e.g. over ssh) the annotated video is written to output.avi // // Example (YOLOv4-tiny trained on COCO): // yolo_example yolov4-tiny.cfg coco.names yolov4-tiny.weights dog.jpg 0.30 #include // Darknet C++ API (also pulls in darknet.h and opencv2/opencv.hpp) #include #include #include #include #include namespace { // "0", "1", ... -> camera index bool isCameraIndex(const std::string & s) { return ! s.empty() && s.find_first_not_of("0123456789") == std::string::npos; } bool isImageFile(const std::filesystem::path & p) { std::string ext = p.extension().string(); for (auto & c : ext) c = static_cast(std::tolower(static_cast(c))); return ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tif" || ext == ".tiff" || ext == ".webp"; } // Prints one line per detected object: class, confidence and box in pixels void printPredictions(const Darknet::NetworkPtr net, const Darknet::Predictions & predictions) { const Darknet::VStr & names = Darknet::get_class_names(net); for (const auto & p : predictions) { if (p.best_class < 0) { continue; // nothing above the threshold } const float confidence = p.prob.count(p.best_class) ? p.prob.at(p.best_class) : 0.0f; std::cout << " " << names.at(p.best_class) << " " << static_cast(confidence * 100.0f + 0.5f) << "%" << " x=" << p.rect.x << " y=" << p.rect.y << " w=" << p.rect.width << " h=" << p.rect.height << std::endl; } } int runImage(Darknet::NetworkPtr net, const std::filesystem::path & file) { cv::Mat image = cv::imread(file.string()); // BGR, as Darknet expects if (image.empty()) { std::cerr << "Cannot read image " << file << std::endl; return 1; } const auto t0 = std::chrono::steady_clock::now(); const Darknet::Predictions predictions = Darknet::predict(net, image); const auto ms = std::chrono::duration_cast(std::chrono::steady_clock::now() - t0).count(); std::cout << file.filename().string() << ": " << predictions.size() << " object(s) in " << ms << " ms" << std::endl; printPredictions(net, predictions); // annotate() draws boxes and labels on the Mat it gets (and returns it) cv::Mat output = Darknet::annotate(net, predictions, image.clone()); const std::filesystem::path outFile = file.parent_path() / (file.stem().string() + "_output.jpg"); cv::imwrite(outFile.string(), output, {cv::IMWRITE_JPEG_QUALITY, 90}); std::cout << "Saved " << outFile.string() << std::endl; return 0; } int runVideo(Darknet::NetworkPtr net, const std::string & input) { cv::VideoCapture cap; if (isCameraIndex(input)) { cap.open(std::stoi(input)); } else { cap.open(input); } if (! cap.isOpened()) { std::cerr << "Cannot open video/camera " << input << std::endl; return 1; } // Without a display (DISPLAY unset), write the result to a file instead of showing it const bool haveDisplay = std::getenv("DISPLAY") != nullptr || std::getenv("WAYLAND_DISPLAY") != nullptr; cv::VideoWriter writer; cv::Mat frame; size_t frames = 0; const auto t0 = std::chrono::steady_clock::now(); while (cap.read(frame) && ! frame.empty()) { const Darknet::Predictions predictions = Darknet::predict(net, frame); Darknet::annotate(net, predictions, frame); frames++; if (haveDisplay) { cv::imshow("YOLO", frame); const int key = cv::waitKey(1); if (key == 'q' || key == 27) { break; } } else { if (! writer.isOpened()) { double fps = cap.get(cv::CAP_PROP_FPS); if (fps <= 0.0) fps = 25.0; writer.open("output.avi", cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), fps, frame.size()); std::cout << "No display: writing output.avi" << std::endl; } writer.write(frame); if (frames % 100 == 0) { std::cout << frames << " frames" << std::endl; } } } const double seconds = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); std::cout << frames << " frames, " << (seconds > 0.0 ? frames / seconds : 0.0) << " FPS" << std::endl; return 0; } } int main(int argc, char * argv[]) { if (argc < 5) { std::cerr << "Usage: " << argv[0] << " [threshold]" << std::endl; return 1; } const std::filesystem::path cfgFile = argv[1]; const std::filesystem::path namesFile = argv[2]; const std::filesystem::path weightsFile = argv[3]; const std::string input = argv[4]; const float threshold = (argc > 5) ? std::stof(argv[5]) : 0.25f; Darknet::NetworkPtr net = nullptr; try { // Darknet::set_gpu_index(0); // with a CUDA build of Darknet: select the GPU before loading net = Darknet::load_neural_network(cfgFile, namesFile, weightsFile); int w = 0, h = 0, c = 0; Darknet::network_dimensions(net, w, h, c); std::cout << "Network " << w << "x" << h << "x" << c << ", " << Darknet::get_class_names(net).size() << " classes" << std::endl; Darknet::set_detection_threshold(net, threshold); // minimum confidence (default 0.25) Darknet::set_non_maximal_suppression_threshold(net, 0.45f); // overlap for merging boxes (default 0.45) const int rc = isImageFile(input) ? runImage(net, input) : runVideo(net, input); Darknet::free_neural_network(net); return rc; } catch (const std::exception & e) { std::cerr << "Error: " << e.what() << std::endl; Darknet::free_neural_network(net); return 1; } }