Skip to content

Instantly share code, notes, and snippets.

@lp6m
Created January 16, 2022 16:23
Show Gist options
  • Save lp6m/23da2e4048d4545d0bbdb661f6a7e355 to your computer and use it in GitHub Desktop.
Save lp6m/23da2e4048d4545d0bbdb661f6a7e355 to your computer and use it in GitHub Desktop.
run darknet inference using libdarknet.so
//g++ -std=c++11 libdarknet.so test.cpp `pkg-config --libs --cflags opencv
#include "include/darknet.h"
#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
using namespace std;
using namespace cv;
struct mybbox{
int best_class;
float prob;
float x;
float y;
float w;
float h;
mybbox(int cls, float prob, float x, float y, float w, float h){
this->best_class = cls;
this->prob = prob;
this->x = x;
this->y = y;
this->w = w;
this->h = h;
}
};
int main(){
cv::Mat img = cv::imread("video_19_530.jpg");
network net = *load_network_custom("./signate_yolov4_tiny/yolov4-tiny-custom.cfg", "./signate_yolov4_tiny/yolov4-tiny-custom_best.weights", 0, 1);
image im = load_image_color("video_19_530.jpg", 0, 0);
image sized = resize_image(im, net.w, net.h);
int nboxes = 0;
int letter_box = 0;
float thresh = 0.5f;
float hier_thresh = 0.5f;
network_predict(net, sized.data);
detection *dets = get_network_boxes(&net, im.w, im.h, thresh, hier_thresh, 0, 1, &nboxes, letter_box);
float nms = 0.4f;
layer l = net.layers[net.n - 1];
do_nms_sort(dets, nboxes, l.classes, nms);
//remove negatives (cf darknet.py)
cout << "classses:" << l.classes << endl;
vector<mybbox> final_results;
for(int i = 0; i < nboxes; i++){
detection det = dets[i];
for(int j = 0; j < l.classes; j++){
if(det.prob[j] > 0){
final_results.push_back(mybbox(j, det.prob[j], det.bbox.x, det.bbox.y, det.bbox.w, det.bbox.h));
}
}
}
cout << "nboxes " << nboxes << " final bboxes " << final_results.size() << endl;
for(mybbox box : final_results){
cout << box.best_class << " " << box.x << " " << box.y << " " << box.w << " " << box.h << " " << box.prob << endl;
float xmin = (box.x - box.w / 2) * img.cols;
float xmax = (box.x + box.w / 2) * img.cols;
float ymin = (box.y - box.h / 2) * img.rows;
float ymax = (box.y + box.h / 2) * img.rows;
rectangle(img, Point(xmin, ymin), Point(xmax, ymax),
Scalar(0, 255, 0), 3, 1, 0);
}
cv::imwrite("myresult.jpg", img);
free_detections(dets, nboxes);
free_image(im);
free_image(sized);
free_network(net);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment