Projects/yolo_example: minimal YOLO detection with Darknet and OpenCV
#18
Merged
ClaudeAI
merged 1 commits from feature/yolo-example into master 60 minutes ago
4 changed files with 264 additions and 0 deletions
-
3Projects/yolo_example/.gitignore
-
13Projects/yolo_example/Makefile
-
67Projects/yolo_example/README.md
-
181Projects/yolo_example/yolo_example.cpp
@ -0,0 +1,3 @@ |
|||||
|
yolo_example |
||||
|
*_output.jpg |
||||
|
output.avi |
||||
@ -0,0 +1,13 @@ |
|||||
|
# Minimal build for yolo_example (needs Darknet V3+ installed: libdarknet.so + darknet.h/darknet.hpp, and OpenCV 4)
|
||||
|
CXX ?= g++ |
||||
|
CXXFLAGS ?= -O2 -Wall -Wextra |
||||
|
CXXFLAGS += -std=c++17 $(shell pkg-config --cflags opencv4) |
||||
|
LDLIBS += -ldarknet $(shell pkg-config --libs opencv4) |
||||
|
|
||||
|
yolo_example: yolo_example.cpp |
||||
|
$(CXX) $(CXXFLAGS) -o $@ $< $(LDLIBS) |
||||
|
|
||||
|
clean: |
||||
|
rm -f yolo_example |
||||
|
|
||||
|
.PHONY: clean |
||||
@ -0,0 +1,67 @@ |
|||||
|
# 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 `<name>_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. |
||||
@ -0,0 +1,181 @@ |
|||||
|
// 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 <cfg> <names> <weights> <input> [threshold]
|
||||
|
//
|
||||
|
// <input> 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 <name>_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.hpp> // Darknet C++ API (also pulls in darknet.h and opencv2/opencv.hpp)
|
||||
|
|
||||
|
#include <chrono>
|
||||
|
#include <cstdlib>
|
||||
|
#include <filesystem>
|
||||
|
#include <iostream>
|
||||
|
#include <string>
|
||||
|
|
||||
|
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<char>(std::tolower(static_cast<unsigned char>(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<int>(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::milliseconds>(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<double>(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] << " <cfg> <names> <weights> <image|video|camera> [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; |
||||
|
} |
||||
|
} |
||||
Write
Preview
Loading…
Cancel
Save
Reference in new issue