# yolo_example Minimal YOLO object detection with the Darknet C++ API (hank-ai Darknet/YOLO V3+) and OpenCV 4. ## Build Needs Darknet installed (`libdarknet.so`, `darknet.h`, `darknet.hpp`) and OpenCV 4 (`libopencv-dev`): ```bash make ``` or directly: ```bash g++ -std=c++17 -O2 yolo_example.cpp -o yolo_example $(pkg-config --cflags --libs opencv4) -ldarknet ``` ## Model files A network is three files: | File | What it is | |---|---| | `.cfg` | network architecture | | `.names` | one class name per line | | `.weights` | trained weights | For a quick test: - **COCO (80 classes) with YOLOv4-tiny:** - `cfg/yolov4-tiny.cfg` and `cfg/coco.names` come from the Darknet source tree; - `yolov4-tiny.weights` comes from the Darknet/YOLO releases. - **Your own network:** use the `.cfg`, `.names` and `.weights` produced by `darknet detector train`. ## Run ```bash ./yolo_example yolov4-tiny.cfg coco.names yolov4-tiny.weights dog.jpg 0.30 ``` The last argument is the detection threshold (default 0.25). The input can be: - **an image file** (`jpg`/`png`/...): the detections are printed, and the annotated image is saved as `_output.jpg`; - **a video file or a camera number** (`0`, `1`, ...): every frame is detected and shown in a window. Press `q` or Esc to quit. Without a display (e.g. over ssh), the annotated video is written to `output.avi`. Sample output: ``` Network 416x416x3, 80 classes dog.jpg: 3 object(s) in 21 ms dog 92% x=124 y=219 w=196 h=321 bicycle 88% x=118 y=124 w=452 h=313 truck 76% x=462 y=76 w=232 h=94 Saved dog_output.jpg ``` ## How it works 1. `Darknet::load_neural_network(cfg, names, weights)` loads the network. 2. `set_detection_threshold()` and `set_non_maximal_suppression_threshold()` tune the filtering. 3. `Darknet::predict(net, mat)` runs YOLO on a BGR `cv::Mat` (as read by OpenCV). Darknet resizes the image to the network size and scales the boxes back. The result is a vector of `Prediction`, with these fields: - `best_class`: the class index; - `prob`: the probability for each class; - `rect`: the box in image pixels. 4. `Darknet::annotate(net, predictions, mat)` draws the boxes and labels. 5. `Darknet::free_neural_network(net)` frees the network. For a CUDA build of Darknet, call `Darknet::set_gpu_index(0)` before loading the network.