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.

67 lines
2.3 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. # yolo_example
  2. Minimal YOLO object detection with the Darknet C++ API (hank-ai Darknet/YOLO V3+) and OpenCV 4.
  3. ## Build
  4. Needs Darknet installed (`libdarknet.so`, `darknet.h`, `darknet.hpp`) and OpenCV 4 (`libopencv-dev`):
  5. ```bash
  6. make
  7. ```
  8. or directly:
  9. ```bash
  10. g++ -std=c++17 -O2 yolo_example.cpp -o yolo_example $(pkg-config --cflags --libs opencv4) -ldarknet
  11. ```
  12. ## Model files
  13. A network is three files:
  14. | File | What it is |
  15. |---|---|
  16. | `.cfg` | network architecture |
  17. | `.names` | one class name per line |
  18. | `.weights` | trained weights |
  19. For a quick test:
  20. - **COCO (80 classes) with YOLOv4-tiny:**
  21. - `cfg/yolov4-tiny.cfg` and `cfg/coco.names` come from the Darknet source tree;
  22. - `yolov4-tiny.weights` comes from the Darknet/YOLO releases.
  23. - **Your own network:** use the `.cfg`, `.names` and `.weights` produced by `darknet detector train`.
  24. ## Run
  25. ```bash
  26. ./yolo_example yolov4-tiny.cfg coco.names yolov4-tiny.weights dog.jpg 0.30
  27. ```
  28. The last argument is the detection threshold (default 0.25). The input can be:
  29. - **an image file** (`jpg`/`png`/...): the detections are printed, and the annotated image is saved as `<name>_output.jpg`;
  30. - **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`.
  31. Sample output:
  32. ```
  33. Network 416x416x3, 80 classes
  34. dog.jpg: 3 object(s) in 21 ms
  35. dog 92% x=124 y=219 w=196 h=321
  36. bicycle 88% x=118 y=124 w=452 h=313
  37. truck 76% x=462 y=76 w=232 h=94
  38. Saved dog_output.jpg
  39. ```
  40. ## How it works
  41. 1. `Darknet::load_neural_network(cfg, names, weights)` loads the network.
  42. 2. `set_detection_threshold()` and `set_non_maximal_suppression_threshold()` tune the filtering.
  43. 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:
  44. - `best_class`: the class index;
  45. - `prob`: the probability for each class;
  46. - `rect`: the box in image pixels.
  47. 4. `Darknet::annotate(net, predictions, mat)` draws the boxes and labels.
  48. 5. `Darknet::free_neural_network(net)` frees the network.
  49. For a CUDA build of Darknet, call `Darknet::set_gpu_index(0)` before loading the network.