1 #ifndef YOLO_V2_CLASS_HPP
2 #define YOLO_V2_CLASS_HPP
3
4 #ifndef LIB_API
5 #ifdef LIB_EXPORTS
6 #if defined(_MSC_VER)
7 #define LIB_API __declspec(dllexport)
8 #else
9 #define LIB_API __attribute__((visibility("default")))
10 #endif
11 #else
12 #if defined(_MSC_VER)
13 #define LIB_API
14 #else
15 #define LIB_API
16 #endif
17 #endif
18 #endif
19
20 #define C_SHARP_MAX_OBJECTS 1000
21
22 struct bbox_t {
23 unsigned int x, y, w, h; // (x,y) - top-left corner, (w, h) - width & height of bounded box
24 float prob; // confidence - probability that the object was found correctly
25 unsigned int obj_id; // class of object - from range [0, classes-1]
26 unsigned int track_id; // tracking id for video (0 - untracked, 1 - inf - tracked object)
27 unsigned int frames_counter; // counter of frames on which the object was detected
28 float x_3d, y_3d, z_3d; // center of object (in Meters) if ZED 3D Camera is used
29 };
30
31 struct image_t {
32 int h; // height
33 int w; // width
34 int c; // number of chanels (3 - for RGB)
35 float *data; // pointer to the image data
36 };
37
38 struct bbox_t_container {
39 bbox_t candidates[C_SHARP_MAX_OBJECTS];
40 };
41
42 #ifdef __cplusplus
43 #include <memory>
44 #include <vector>
45 #include <deque>
46 #include <algorithm>
47 #include <chrono>
48 #include <string>
49 #include <sstream>
50 #include <iostream>
51 #include <cmath>
52
53 #ifdef OPENCV
54 #include <opencv2/opencv.hpp> // C++
55 #include <opencv2/highgui/highgui_c.h> // C
56 #include <opencv2/imgproc/imgproc_c.h> // C
57 #endif
58
59 extern "C" LIB_API int init(const char *configurationFilename, const char *weightsFilename, int gpu);
60 extern "C" LIB_API int detect_image(const char *filename, bbox_t_container &container);
61 extern "C" LIB_API int detect_mat(const uint8_t* data, const size_t data_length, bbox_t_container &container);
62 extern "C" LIB_API int dispose();
63 extern "C" LIB_API int get_device_count();
64 extern "C" LIB_API int get_device_name(int gpu, char* deviceName);
65 extern "C" LIB_API bool built_with_cuda();
66 extern "C" LIB_API bool built_with_cudnn();
67 extern "C" LIB_API bool built_with_opencv();
68 extern "C" LIB_API void send_json_custom(char const* send_buf, int port, int timeout);
69
70 class Detector {
71 std::shared_ptr<void> detector_gpu_ptr;
72 std::deque<std::vector<bbox_t>> prev_bbox_vec_deque;
73 std::string _cfg_filename, _weight_filename;
74 public:
75 const int cur_gpu_id;
76 float nms = .4;
77 bool wait_stream;
78
79 LIB_API Detector(std::string cfg_filename, std::string weight_filename, int gpu_id = 0);
80 LIB_API ~Detector();
81
82 LIB_API std::vector<bbox_t> detect(std::string image_filename, float thresh = 0.2, bool use_mean = false);
83 LIB_API std::vector<bbox_t> detect(image_t img, float thresh = 0.2, bool use_mean = false);
84 static LIB_API image_t load_image(std::string image_filename);
85 static LIB_API void free_image(image_t m);
86 LIB_API int get_net_width() const;
87 LIB_API int get_net_height() const;
88 LIB_API int get_net_color_depth() const;
89
90 LIB_API std::vector<bbox_t> tracking_id(std::vector<bbox_t> cur_bbox_vec, bool const change_history = true,
91 int const frames_story = 5, int const max_dist = 40);
92
93 LIB_API void *get_cuda_context();
94
95 //LIB_API bool send_json_http(std::vector<bbox_t> cur_bbox_vec, std::vector<std::string> obj_names, int frame_id,
96 // std::string filename = std::string(), int timeout = 400000, int port = 8070);
97
detect_resized(image_t img,int init_w,int init_h,float thresh=0.2,bool use_mean=false)98 std::vector<bbox_t> detect_resized(image_t img, int init_w, int init_h, float thresh = 0.2, bool use_mean = false)
99 {
100 if (img.data == NULL)
101 throw std::runtime_error("Image is empty");
102 auto detection_boxes = detect(img, thresh, use_mean);
103 float wk = (float)init_w / img.w, hk = (float)init_h / img.h;
104 for (auto &i : detection_boxes) i.x *= wk, i.w *= wk, i.y *= hk, i.h *= hk;
105 return detection_boxes;
106 }
107
108 #ifdef OPENCV
detect(cv::Mat mat,float thresh=0.2,bool use_mean=false)109 std::vector<bbox_t> detect(cv::Mat mat, float thresh = 0.2, bool use_mean = false)
110 {
111 if(mat.data == NULL)
112 throw std::runtime_error("Image is empty");
113 auto image_ptr = mat_to_image_resize(mat);
114 return detect_resized(*image_ptr, mat.cols, mat.rows, thresh, use_mean);
115 }
116
mat_to_image_resize(cv::Mat mat) const117 std::shared_ptr<image_t> mat_to_image_resize(cv::Mat mat) const
118 {
119 if (mat.data == NULL) return std::shared_ptr<image_t>(NULL);
120
121 cv::Size network_size = cv::Size(get_net_width(), get_net_height());
122 cv::Mat det_mat;
123 if (mat.size() != network_size)
124 cv::resize(mat, det_mat, network_size);
125 else
126 det_mat = mat; // only reference is copied
127
128 return mat_to_image(det_mat);
129 }
130
mat_to_image(cv::Mat img_src)131 static std::shared_ptr<image_t> mat_to_image(cv::Mat img_src)
132 {
133 cv::Mat img;
134 if (img_src.channels() == 4) cv::cvtColor(img_src, img, cv::COLOR_RGBA2BGR);
135 else if (img_src.channels() == 3) cv::cvtColor(img_src, img, cv::COLOR_RGB2BGR);
136 else if (img_src.channels() == 1) cv::cvtColor(img_src, img, cv::COLOR_GRAY2BGR);
137 else std::cerr << " Warning: img_src.channels() is not 1, 3 or 4. It is = " << img_src.channels() << std::endl;
138 std::shared_ptr<image_t> image_ptr(new image_t, [](image_t *img) { free_image(*img); delete img; });
139 *image_ptr = mat_to_image_custom(img);
140 return image_ptr;
141 }
142
143 private:
144
mat_to_image_custom(cv::Mat mat)145 static image_t mat_to_image_custom(cv::Mat mat)
146 {
147 int w = mat.cols;
148 int h = mat.rows;
149 int c = mat.channels();
150 image_t im = make_image_custom(w, h, c);
151 unsigned char *data = (unsigned char *)mat.data;
152 int step = mat.step;
153 for (int y = 0; y < h; ++y) {
154 for (int k = 0; k < c; ++k) {
155 for (int x = 0; x < w; ++x) {
156 im.data[k*w*h + y*w + x] = data[y*step + x*c + k] / 255.0f;
157 }
158 }
159 }
160 return im;
161 }
162
make_empty_image(int w,int h,int c)163 static image_t make_empty_image(int w, int h, int c)
164 {
165 image_t out;
166 out.data = 0;
167 out.h = h;
168 out.w = w;
169 out.c = c;
170 return out;
171 }
172
make_image_custom(int w,int h,int c)173 static image_t make_image_custom(int w, int h, int c)
174 {
175 image_t out = make_empty_image(w, h, c);
176 out.data = (float *)calloc(h*w*c, sizeof(float));
177 return out;
178 }
179
180 #endif // OPENCV
181
182 public:
183
send_json_http(std::vector<bbox_t> cur_bbox_vec,std::vector<std::string> obj_names,int frame_id,std::string filename=std::string (),int timeout=400000,int port=8070)184 bool send_json_http(std::vector<bbox_t> cur_bbox_vec, std::vector<std::string> obj_names, int frame_id,
185 std::string filename = std::string(), int timeout = 400000, int port = 8070)
186 {
187 std::string send_str;
188
189 char *tmp_buf = (char *)calloc(1024, sizeof(char));
190 if (!filename.empty()) {
191 sprintf(tmp_buf, "{\n \"frame_id\":%d, \n \"filename\":\"%s\", \n \"objects\": [ \n", frame_id, filename.c_str());
192 }
193 else {
194 sprintf(tmp_buf, "{\n \"frame_id\":%d, \n \"objects\": [ \n", frame_id);
195 }
196 send_str = tmp_buf;
197 free(tmp_buf);
198
199 for (auto & i : cur_bbox_vec) {
200 char *buf = (char *)calloc(2048, sizeof(char));
201
202 sprintf(buf, " {\"class_id\":%d, \"name\":\"%s\", \"absolute_coordinates\":{\"center_x\":%d, \"center_y\":%d, \"width\":%d, \"height\":%d}, \"confidence\":%f",
203 i.obj_id, obj_names[i.obj_id].c_str(), i.x, i.y, i.w, i.h, i.prob);
204
205 //sprintf(buf, " {\"class_id\":%d, \"name\":\"%s\", \"relative_coordinates\":{\"center_x\":%f, \"center_y\":%f, \"width\":%f, \"height\":%f}, \"confidence\":%f",
206 // i.obj_id, obj_names[i.obj_id], i.x, i.y, i.w, i.h, i.prob);
207
208 send_str += buf;
209
210 if (!std::isnan(i.z_3d)) {
211 sprintf(buf, "\n , \"coordinates_in_meters\":{\"x_3d\":%.2f, \"y_3d\":%.2f, \"z_3d\":%.2f}",
212 i.x_3d, i.y_3d, i.z_3d);
213 send_str += buf;
214 }
215
216 send_str += "}\n";
217
218 free(buf);
219 }
220
221 //send_str += "\n ] \n}, \n";
222 send_str += "\n ] \n}";
223
224 send_json_custom(send_str.c_str(), port, timeout);
225 return true;
226 }
227 };
228 // --------------------------------------------------------------------------------
229
230
231 #if defined(TRACK_OPTFLOW) && defined(OPENCV) && defined(GPU)
232
233 #include <opencv2/cudaoptflow.hpp>
234 #include <opencv2/cudaimgproc.hpp>
235 #include <opencv2/cudaarithm.hpp>
236 #include <opencv2/core/cuda.hpp>
237
238 class Tracker_optflow {
239 public:
240 const int gpu_count;
241 const int gpu_id;
242 const int flow_error;
243
244
Tracker_optflow(int _gpu_id=0,int win_size=15,int max_level=3,int iterations=8000,int _flow_error=-1)245 Tracker_optflow(int _gpu_id = 0, int win_size = 15, int max_level = 3, int iterations = 8000, int _flow_error = -1) :
246 gpu_count(cv::cuda::getCudaEnabledDeviceCount()), gpu_id(std::min(_gpu_id, gpu_count-1)),
247 flow_error((_flow_error > 0)? _flow_error:(win_size*4))
248 {
249 int const old_gpu_id = cv::cuda::getDevice();
250 cv::cuda::setDevice(gpu_id);
251
252 stream = cv::cuda::Stream();
253
254 sync_PyrLKOpticalFlow_gpu = cv::cuda::SparsePyrLKOpticalFlow::create();
255 sync_PyrLKOpticalFlow_gpu->setWinSize(cv::Size(win_size, win_size)); // 9, 15, 21, 31
256 sync_PyrLKOpticalFlow_gpu->setMaxLevel(max_level); // +- 3 pt
257 sync_PyrLKOpticalFlow_gpu->setNumIters(iterations); // 2000, def: 30
258
259 cv::cuda::setDevice(old_gpu_id);
260 }
261
262 // just to avoid extra allocations
263 cv::cuda::GpuMat src_mat_gpu;
264 cv::cuda::GpuMat dst_mat_gpu, dst_grey_gpu;
265 cv::cuda::GpuMat prev_pts_flow_gpu, cur_pts_flow_gpu;
266 cv::cuda::GpuMat status_gpu, err_gpu;
267
268 cv::cuda::GpuMat src_grey_gpu; // used in both functions
269 cv::Ptr<cv::cuda::SparsePyrLKOpticalFlow> sync_PyrLKOpticalFlow_gpu;
270 cv::cuda::Stream stream;
271
272 std::vector<bbox_t> cur_bbox_vec;
273 std::vector<bool> good_bbox_vec_flags;
274 cv::Mat prev_pts_flow_cpu;
275
update_cur_bbox_vec(std::vector<bbox_t> _cur_bbox_vec)276 void update_cur_bbox_vec(std::vector<bbox_t> _cur_bbox_vec)
277 {
278 cur_bbox_vec = _cur_bbox_vec;
279 good_bbox_vec_flags = std::vector<bool>(cur_bbox_vec.size(), true);
280 cv::Mat prev_pts, cur_pts_flow_cpu;
281
282 for (auto &i : cur_bbox_vec) {
283 float x_center = (i.x + i.w / 2.0F);
284 float y_center = (i.y + i.h / 2.0F);
285 prev_pts.push_back(cv::Point2f(x_center, y_center));
286 }
287
288 if (prev_pts.rows == 0)
289 prev_pts_flow_cpu = cv::Mat();
290 else
291 cv::transpose(prev_pts, prev_pts_flow_cpu);
292
293 if (prev_pts_flow_gpu.cols < prev_pts_flow_cpu.cols) {
294 prev_pts_flow_gpu = cv::cuda::GpuMat(prev_pts_flow_cpu.size(), prev_pts_flow_cpu.type());
295 cur_pts_flow_gpu = cv::cuda::GpuMat(prev_pts_flow_cpu.size(), prev_pts_flow_cpu.type());
296
297 status_gpu = cv::cuda::GpuMat(prev_pts_flow_cpu.size(), CV_8UC1);
298 err_gpu = cv::cuda::GpuMat(prev_pts_flow_cpu.size(), CV_32FC1);
299 }
300
301 prev_pts_flow_gpu.upload(cv::Mat(prev_pts_flow_cpu), stream);
302 }
303
304
update_tracking_flow(cv::Mat src_mat,std::vector<bbox_t> _cur_bbox_vec)305 void update_tracking_flow(cv::Mat src_mat, std::vector<bbox_t> _cur_bbox_vec)
306 {
307 int const old_gpu_id = cv::cuda::getDevice();
308 if (old_gpu_id != gpu_id)
309 cv::cuda::setDevice(gpu_id);
310
311 if (src_mat.channels() == 1 || src_mat.channels() == 3 || src_mat.channels() == 4) {
312 if (src_mat_gpu.cols == 0) {
313 src_mat_gpu = cv::cuda::GpuMat(src_mat.size(), src_mat.type());
314 src_grey_gpu = cv::cuda::GpuMat(src_mat.size(), CV_8UC1);
315 }
316
317 if (src_mat.channels() == 1) {
318 src_mat_gpu.upload(src_mat, stream);
319 src_mat_gpu.copyTo(src_grey_gpu);
320 }
321 else if (src_mat.channels() == 3) {
322 src_mat_gpu.upload(src_mat, stream);
323 cv::cuda::cvtColor(src_mat_gpu, src_grey_gpu, CV_BGR2GRAY, 1, stream);
324 }
325 else if (src_mat.channels() == 4) {
326 src_mat_gpu.upload(src_mat, stream);
327 cv::cuda::cvtColor(src_mat_gpu, src_grey_gpu, CV_BGRA2GRAY, 1, stream);
328 }
329 else {
330 std::cerr << " Warning: src_mat.channels() is not: 1, 3 or 4. It is = " << src_mat.channels() << " \n";
331 return;
332 }
333
334 }
335 update_cur_bbox_vec(_cur_bbox_vec);
336
337 if (old_gpu_id != gpu_id)
338 cv::cuda::setDevice(old_gpu_id);
339 }
340
341
tracking_flow(cv::Mat dst_mat,bool check_error=true)342 std::vector<bbox_t> tracking_flow(cv::Mat dst_mat, bool check_error = true)
343 {
344 if (sync_PyrLKOpticalFlow_gpu.empty()) {
345 std::cout << "sync_PyrLKOpticalFlow_gpu isn't initialized \n";
346 return cur_bbox_vec;
347 }
348
349 int const old_gpu_id = cv::cuda::getDevice();
350 if(old_gpu_id != gpu_id)
351 cv::cuda::setDevice(gpu_id);
352
353 if (dst_mat_gpu.cols == 0) {
354 dst_mat_gpu = cv::cuda::GpuMat(dst_mat.size(), dst_mat.type());
355 dst_grey_gpu = cv::cuda::GpuMat(dst_mat.size(), CV_8UC1);
356 }
357
358 //dst_grey_gpu.upload(dst_mat, stream); // use BGR
359 dst_mat_gpu.upload(dst_mat, stream);
360 cv::cuda::cvtColor(dst_mat_gpu, dst_grey_gpu, CV_BGR2GRAY, 1, stream);
361
362 if (src_grey_gpu.rows != dst_grey_gpu.rows || src_grey_gpu.cols != dst_grey_gpu.cols) {
363 stream.waitForCompletion();
364 src_grey_gpu = dst_grey_gpu.clone();
365 cv::cuda::setDevice(old_gpu_id);
366 return cur_bbox_vec;
367 }
368
369 ////sync_PyrLKOpticalFlow_gpu.sparse(src_grey_gpu, dst_grey_gpu, prev_pts_flow_gpu, cur_pts_flow_gpu, status_gpu, &err_gpu); // OpenCV 2.4.x
370 sync_PyrLKOpticalFlow_gpu->calc(src_grey_gpu, dst_grey_gpu, prev_pts_flow_gpu, cur_pts_flow_gpu, status_gpu, err_gpu, stream); // OpenCV 3.x
371
372 cv::Mat cur_pts_flow_cpu;
373 cur_pts_flow_gpu.download(cur_pts_flow_cpu, stream);
374
375 dst_grey_gpu.copyTo(src_grey_gpu, stream);
376
377 cv::Mat err_cpu, status_cpu;
378 err_gpu.download(err_cpu, stream);
379 status_gpu.download(status_cpu, stream);
380
381 stream.waitForCompletion();
382
383 std::vector<bbox_t> result_bbox_vec;
384
385 if (err_cpu.cols == cur_bbox_vec.size() && status_cpu.cols == cur_bbox_vec.size())
386 {
387 for (size_t i = 0; i < cur_bbox_vec.size(); ++i)
388 {
389 cv::Point2f cur_key_pt = cur_pts_flow_cpu.at<cv::Point2f>(0, i);
390 cv::Point2f prev_key_pt = prev_pts_flow_cpu.at<cv::Point2f>(0, i);
391
392 float moved_x = cur_key_pt.x - prev_key_pt.x;
393 float moved_y = cur_key_pt.y - prev_key_pt.y;
394
395 if (abs(moved_x) < 100 && abs(moved_y) < 100 && good_bbox_vec_flags[i])
396 if (err_cpu.at<float>(0, i) < flow_error && status_cpu.at<unsigned char>(0, i) != 0 &&
397 ((float)cur_bbox_vec[i].x + moved_x) > 0 && ((float)cur_bbox_vec[i].y + moved_y) > 0)
398 {
399 cur_bbox_vec[i].x += moved_x + 0.5;
400 cur_bbox_vec[i].y += moved_y + 0.5;
401 result_bbox_vec.push_back(cur_bbox_vec[i]);
402 }
403 else good_bbox_vec_flags[i] = false;
404 else good_bbox_vec_flags[i] = false;
405
406 //if(!check_error && !good_bbox_vec_flags[i]) result_bbox_vec.push_back(cur_bbox_vec[i]);
407 }
408 }
409
410 cur_pts_flow_gpu.swap(prev_pts_flow_gpu);
411 cur_pts_flow_cpu.copyTo(prev_pts_flow_cpu);
412
413 if (old_gpu_id != gpu_id)
414 cv::cuda::setDevice(old_gpu_id);
415
416 return result_bbox_vec;
417 }
418
419 };
420
421 #elif defined(TRACK_OPTFLOW) && defined(OPENCV)
422
423 //#include <opencv2/optflow.hpp>
424 #include <opencv2/video/tracking.hpp>
425
426 class Tracker_optflow {
427 public:
428 const int flow_error;
429
430
Tracker_optflow(int win_size=15,int max_level=3,int iterations=8000,int _flow_error=-1)431 Tracker_optflow(int win_size = 15, int max_level = 3, int iterations = 8000, int _flow_error = -1) :
432 flow_error((_flow_error > 0)? _flow_error:(win_size*4))
433 {
434 sync_PyrLKOpticalFlow = cv::SparsePyrLKOpticalFlow::create();
435 sync_PyrLKOpticalFlow->setWinSize(cv::Size(win_size, win_size)); // 9, 15, 21, 31
436 sync_PyrLKOpticalFlow->setMaxLevel(max_level); // +- 3 pt
437
438 }
439
440 // just to avoid extra allocations
441 cv::Mat dst_grey;
442 cv::Mat prev_pts_flow, cur_pts_flow;
443 cv::Mat status, err;
444
445 cv::Mat src_grey; // used in both functions
446 cv::Ptr<cv::SparsePyrLKOpticalFlow> sync_PyrLKOpticalFlow;
447
448 std::vector<bbox_t> cur_bbox_vec;
449 std::vector<bool> good_bbox_vec_flags;
450
update_cur_bbox_vec(std::vector<bbox_t> _cur_bbox_vec)451 void update_cur_bbox_vec(std::vector<bbox_t> _cur_bbox_vec)
452 {
453 cur_bbox_vec = _cur_bbox_vec;
454 good_bbox_vec_flags = std::vector<bool>(cur_bbox_vec.size(), true);
455 cv::Mat prev_pts, cur_pts_flow;
456
457 for (auto &i : cur_bbox_vec) {
458 float x_center = (i.x + i.w / 2.0F);
459 float y_center = (i.y + i.h / 2.0F);
460 prev_pts.push_back(cv::Point2f(x_center, y_center));
461 }
462
463 if (prev_pts.rows == 0)
464 prev_pts_flow = cv::Mat();
465 else
466 cv::transpose(prev_pts, prev_pts_flow);
467 }
468
469
update_tracking_flow(cv::Mat new_src_mat,std::vector<bbox_t> _cur_bbox_vec)470 void update_tracking_flow(cv::Mat new_src_mat, std::vector<bbox_t> _cur_bbox_vec)
471 {
472 if (new_src_mat.channels() == 1) {
473 src_grey = new_src_mat.clone();
474 }
475 else if (new_src_mat.channels() == 3) {
476 cv::cvtColor(new_src_mat, src_grey, CV_BGR2GRAY, 1);
477 }
478 else if (new_src_mat.channels() == 4) {
479 cv::cvtColor(new_src_mat, src_grey, CV_BGRA2GRAY, 1);
480 }
481 else {
482 std::cerr << " Warning: new_src_mat.channels() is not: 1, 3 or 4. It is = " << new_src_mat.channels() << " \n";
483 return;
484 }
485 update_cur_bbox_vec(_cur_bbox_vec);
486 }
487
488
tracking_flow(cv::Mat new_dst_mat,bool check_error=true)489 std::vector<bbox_t> tracking_flow(cv::Mat new_dst_mat, bool check_error = true)
490 {
491 if (sync_PyrLKOpticalFlow.empty()) {
492 std::cout << "sync_PyrLKOpticalFlow isn't initialized \n";
493 return cur_bbox_vec;
494 }
495
496 cv::cvtColor(new_dst_mat, dst_grey, CV_BGR2GRAY, 1);
497
498 if (src_grey.rows != dst_grey.rows || src_grey.cols != dst_grey.cols) {
499 src_grey = dst_grey.clone();
500 //std::cerr << " Warning: src_grey.rows != dst_grey.rows || src_grey.cols != dst_grey.cols \n";
501 return cur_bbox_vec;
502 }
503
504 if (prev_pts_flow.cols < 1) {
505 return cur_bbox_vec;
506 }
507
508 ////sync_PyrLKOpticalFlow_gpu.sparse(src_grey_gpu, dst_grey_gpu, prev_pts_flow_gpu, cur_pts_flow_gpu, status_gpu, &err_gpu); // OpenCV 2.4.x
509 sync_PyrLKOpticalFlow->calc(src_grey, dst_grey, prev_pts_flow, cur_pts_flow, status, err); // OpenCV 3.x
510
511 dst_grey.copyTo(src_grey);
512
513 std::vector<bbox_t> result_bbox_vec;
514
515 if (err.rows == cur_bbox_vec.size() && status.rows == cur_bbox_vec.size())
516 {
517 for (size_t i = 0; i < cur_bbox_vec.size(); ++i)
518 {
519 cv::Point2f cur_key_pt = cur_pts_flow.at<cv::Point2f>(0, i);
520 cv::Point2f prev_key_pt = prev_pts_flow.at<cv::Point2f>(0, i);
521
522 float moved_x = cur_key_pt.x - prev_key_pt.x;
523 float moved_y = cur_key_pt.y - prev_key_pt.y;
524
525 if (abs(moved_x) < 100 && abs(moved_y) < 100 && good_bbox_vec_flags[i])
526 if (err.at<float>(0, i) < flow_error && status.at<unsigned char>(0, i) != 0 &&
527 ((float)cur_bbox_vec[i].x + moved_x) > 0 && ((float)cur_bbox_vec[i].y + moved_y) > 0)
528 {
529 cur_bbox_vec[i].x += moved_x + 0.5;
530 cur_bbox_vec[i].y += moved_y + 0.5;
531 result_bbox_vec.push_back(cur_bbox_vec[i]);
532 }
533 else good_bbox_vec_flags[i] = false;
534 else good_bbox_vec_flags[i] = false;
535
536 //if(!check_error && !good_bbox_vec_flags[i]) result_bbox_vec.push_back(cur_bbox_vec[i]);
537 }
538 }
539
540 prev_pts_flow = cur_pts_flow.clone();
541
542 return result_bbox_vec;
543 }
544
545 };
546 #else
547
548 class Tracker_optflow {};
549
550 #endif // defined(TRACK_OPTFLOW) && defined(OPENCV)
551
552
553 #ifdef OPENCV
554
obj_id_to_color(int obj_id)555 static cv::Scalar obj_id_to_color(int obj_id) {
556 int const colors[6][3] = { { 1,0,1 },{ 0,0,1 },{ 0,1,1 },{ 0,1,0 },{ 1,1,0 },{ 1,0,0 } };
557 int const offset = obj_id * 123457 % 6;
558 int const color_scale = 150 + (obj_id * 123457) % 100;
559 cv::Scalar color(colors[offset][0], colors[offset][1], colors[offset][2]);
560 color *= color_scale;
561 return color;
562 }
563
564 class preview_boxes_t {
565 enum { frames_history = 30 }; // how long to keep the history saved
566
567 struct preview_box_track_t {
568 unsigned int track_id, obj_id, last_showed_frames_ago;
569 bool current_detection;
570 bbox_t bbox;
571 cv::Mat mat_obj, mat_resized_obj;
preview_box_track_tpreview_boxes_t::preview_box_track_t572 preview_box_track_t() : track_id(0), obj_id(0), last_showed_frames_ago(frames_history), current_detection(false) {}
573 };
574 std::vector<preview_box_track_t> preview_box_track_id;
575 size_t const preview_box_size, bottom_offset;
576 bool const one_off_detections;
577 public:
preview_boxes_t(size_t _preview_box_size=100,size_t _bottom_offset=100,bool _one_off_detections=false)578 preview_boxes_t(size_t _preview_box_size = 100, size_t _bottom_offset = 100, bool _one_off_detections = false) :
579 preview_box_size(_preview_box_size), bottom_offset(_bottom_offset), one_off_detections(_one_off_detections)
580 {}
581
set(cv::Mat src_mat,std::vector<bbox_t> result_vec)582 void set(cv::Mat src_mat, std::vector<bbox_t> result_vec)
583 {
584 size_t const count_preview_boxes = src_mat.cols / preview_box_size;
585 if (preview_box_track_id.size() != count_preview_boxes) preview_box_track_id.resize(count_preview_boxes);
586
587 // increment frames history
588 for (auto &i : preview_box_track_id)
589 i.last_showed_frames_ago = std::min((unsigned)frames_history, i.last_showed_frames_ago + 1);
590
591 // occupy empty boxes
592 for (auto &k : result_vec) {
593 bool found = false;
594 // find the same (track_id)
595 for (auto &i : preview_box_track_id) {
596 if (i.track_id == k.track_id) {
597 if (!one_off_detections) i.last_showed_frames_ago = 0; // for tracked objects
598 found = true;
599 break;
600 }
601 }
602 if (!found) {
603 // find empty box
604 for (auto &i : preview_box_track_id) {
605 if (i.last_showed_frames_ago == frames_history) {
606 if (!one_off_detections && k.frames_counter == 0) break; // don't show if obj isn't tracked yet
607 i.track_id = k.track_id;
608 i.obj_id = k.obj_id;
609 i.bbox = k;
610 i.last_showed_frames_ago = 0;
611 break;
612 }
613 }
614 }
615 }
616
617 // draw preview box (from old or current frame)
618 for (size_t i = 0; i < preview_box_track_id.size(); ++i)
619 {
620 // get object image
621 cv::Mat dst = preview_box_track_id[i].mat_resized_obj;
622 preview_box_track_id[i].current_detection = false;
623
624 for (auto &k : result_vec) {
625 if (preview_box_track_id[i].track_id == k.track_id) {
626 if (one_off_detections && preview_box_track_id[i].last_showed_frames_ago > 0) {
627 preview_box_track_id[i].last_showed_frames_ago = frames_history; break;
628 }
629 bbox_t b = k;
630 cv::Rect r(b.x, b.y, b.w, b.h);
631 cv::Rect img_rect(cv::Point2i(0, 0), src_mat.size());
632 cv::Rect rect_roi = r & img_rect;
633 if (rect_roi.width > 1 || rect_roi.height > 1) {
634 cv::Mat roi = src_mat(rect_roi);
635 cv::resize(roi, dst, cv::Size(preview_box_size, preview_box_size), cv::INTER_NEAREST);
636 preview_box_track_id[i].mat_obj = roi.clone();
637 preview_box_track_id[i].mat_resized_obj = dst.clone();
638 preview_box_track_id[i].current_detection = true;
639 preview_box_track_id[i].bbox = k;
640 }
641 break;
642 }
643 }
644 }
645 }
646
647
draw(cv::Mat draw_mat,bool show_small_boxes=false)648 void draw(cv::Mat draw_mat, bool show_small_boxes = false)
649 {
650 // draw preview box (from old or current frame)
651 for (size_t i = 0; i < preview_box_track_id.size(); ++i)
652 {
653 auto &prev_box = preview_box_track_id[i];
654
655 // draw object image
656 cv::Mat dst = prev_box.mat_resized_obj;
657 if (prev_box.last_showed_frames_ago < frames_history &&
658 dst.size() == cv::Size(preview_box_size, preview_box_size))
659 {
660 cv::Rect dst_rect_roi(cv::Point2i(i * preview_box_size, draw_mat.rows - bottom_offset), dst.size());
661 cv::Mat dst_roi = draw_mat(dst_rect_roi);
662 dst.copyTo(dst_roi);
663
664 cv::Scalar color = obj_id_to_color(prev_box.obj_id);
665 int thickness = (prev_box.current_detection) ? 5 : 1;
666 cv::rectangle(draw_mat, dst_rect_roi, color, thickness);
667
668 unsigned int const track_id = prev_box.track_id;
669 std::string track_id_str = (track_id > 0) ? std::to_string(track_id) : "";
670 putText(draw_mat, track_id_str, dst_rect_roi.tl() - cv::Point2i(-4, 5), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.9, cv::Scalar(0, 0, 0), 2);
671
672 std::string size_str = std::to_string(prev_box.bbox.w) + "x" + std::to_string(prev_box.bbox.h);
673 putText(draw_mat, size_str, dst_rect_roi.tl() + cv::Point2i(0, 12), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0, 0, 0), 1);
674
675 if (!one_off_detections && prev_box.current_detection) {
676 cv::line(draw_mat, dst_rect_roi.tl() + cv::Point2i(preview_box_size, 0),
677 cv::Point2i(prev_box.bbox.x, prev_box.bbox.y + prev_box.bbox.h),
678 color);
679 }
680
681 if (one_off_detections && show_small_boxes) {
682 cv::Rect src_rect_roi(cv::Point2i(prev_box.bbox.x, prev_box.bbox.y),
683 cv::Size(prev_box.bbox.w, prev_box.bbox.h));
684 unsigned int const color_history = (255 * prev_box.last_showed_frames_ago) / frames_history;
685 color = cv::Scalar(255 - 3 * color_history, 255 - 2 * color_history, 255 - 1 * color_history);
686 if (prev_box.mat_obj.size() == src_rect_roi.size()) {
687 prev_box.mat_obj.copyTo(draw_mat(src_rect_roi));
688 }
689 cv::rectangle(draw_mat, src_rect_roi, color, thickness);
690 putText(draw_mat, track_id_str, src_rect_roi.tl() - cv::Point2i(0, 10), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0, 0, 0), 1);
691 }
692 }
693 }
694 }
695 };
696
697
698 class track_kalman_t
699 {
700 int track_id_counter;
701 std::chrono::steady_clock::time_point global_last_time;
702 float dT;
703
704 public:
705 int max_objects; // max objects for tracking
706 int min_frames; // min frames to consider an object as detected
707 const float max_dist; // max distance (in px) to track with the same ID
708 cv::Size img_size; // max value of x,y,w,h
709
710 struct tst_t {
711 int track_id;
712 int state_id;
713 std::chrono::steady_clock::time_point last_time;
714 int detection_count;
tst_ttrack_kalman_t::tst_t715 tst_t() : track_id(-1), state_id(-1) {}
716 };
717 std::vector<tst_t> track_id_state_id_time;
718 std::vector<bbox_t> result_vec_pred;
719
720 struct one_kalman_t;
721 std::vector<one_kalman_t> kalman_vec;
722
723 struct one_kalman_t
724 {
725 cv::KalmanFilter kf;
726 cv::Mat state;
727 cv::Mat meas;
728 int measSize, stateSize, contrSize;
729
set_delta_timetrack_kalman_t::one_kalman_t730 void set_delta_time(float dT) {
731 kf.transitionMatrix.at<float>(2) = dT;
732 kf.transitionMatrix.at<float>(9) = dT;
733 }
734
settrack_kalman_t::one_kalman_t735 void set(bbox_t box)
736 {
737 initialize_kalman();
738
739 kf.errorCovPre.at<float>(0) = 1; // px
740 kf.errorCovPre.at<float>(7) = 1; // px
741 kf.errorCovPre.at<float>(14) = 1;
742 kf.errorCovPre.at<float>(21) = 1;
743 kf.errorCovPre.at<float>(28) = 1; // px
744 kf.errorCovPre.at<float>(35) = 1; // px
745
746 state.at<float>(0) = box.x;
747 state.at<float>(1) = box.y;
748 state.at<float>(2) = 0;
749 state.at<float>(3) = 0;
750 state.at<float>(4) = box.w;
751 state.at<float>(5) = box.h;
752 // <<<< Initialization
753
754 kf.statePost = state;
755 }
756
757 // Kalman.correct() calculates: statePost = statePre + gain * (z(k)-measurementMatrix*statePre);
758 // corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k))
correcttrack_kalman_t::one_kalman_t759 void correct(bbox_t box) {
760 meas.at<float>(0) = box.x;
761 meas.at<float>(1) = box.y;
762 meas.at<float>(2) = box.w;
763 meas.at<float>(3) = box.h;
764
765 kf.correct(meas);
766
767 bbox_t new_box = predict();
768 if (new_box.w == 0 || new_box.h == 0) {
769 set(box);
770 //std::cerr << " force set(): track_id = " << box.track_id <<
771 // ", x = " << box.x << ", y = " << box.y << ", w = " << box.w << ", h = " << box.h << std::endl;
772 }
773 }
774
775 // Kalman.predict() calculates: statePre = TransitionMatrix * statePost;
776 // predicted state (x'(k)): x(k)=A*x(k-1)+B*u(k)
predicttrack_kalman_t::one_kalman_t777 bbox_t predict() {
778 bbox_t box;
779 state = kf.predict();
780
781 box.x = state.at<float>(0);
782 box.y = state.at<float>(1);
783 box.w = state.at<float>(4);
784 box.h = state.at<float>(5);
785 return box;
786 }
787
initialize_kalmantrack_kalman_t::one_kalman_t788 void initialize_kalman()
789 {
790 kf = cv::KalmanFilter(stateSize, measSize, contrSize, CV_32F);
791
792 // Transition State Matrix A
793 // Note: set dT at each processing step!
794 // [ 1 0 dT 0 0 0 ]
795 // [ 0 1 0 dT 0 0 ]
796 // [ 0 0 1 0 0 0 ]
797 // [ 0 0 0 1 0 0 ]
798 // [ 0 0 0 0 1 0 ]
799 // [ 0 0 0 0 0 1 ]
800 cv::setIdentity(kf.transitionMatrix);
801
802 // Measure Matrix H
803 // [ 1 0 0 0 0 0 ]
804 // [ 0 1 0 0 0 0 ]
805 // [ 0 0 0 0 1 0 ]
806 // [ 0 0 0 0 0 1 ]
807 kf.measurementMatrix = cv::Mat::zeros(measSize, stateSize, CV_32F);
808 kf.measurementMatrix.at<float>(0) = 1.0f;
809 kf.measurementMatrix.at<float>(7) = 1.0f;
810 kf.measurementMatrix.at<float>(16) = 1.0f;
811 kf.measurementMatrix.at<float>(23) = 1.0f;
812
813 // Process Noise Covariance Matrix Q - result smoother with lower values (1e-2)
814 // [ Ex 0 0 0 0 0 ]
815 // [ 0 Ey 0 0 0 0 ]
816 // [ 0 0 Ev_x 0 0 0 ]
817 // [ 0 0 0 Ev_y 0 0 ]
818 // [ 0 0 0 0 Ew 0 ]
819 // [ 0 0 0 0 0 Eh ]
820 //cv::setIdentity(kf.processNoiseCov, cv::Scalar(1e-3));
821 kf.processNoiseCov.at<float>(0) = 1e-2;
822 kf.processNoiseCov.at<float>(7) = 1e-2;
823 kf.processNoiseCov.at<float>(14) = 1e-2;// 5.0f;
824 kf.processNoiseCov.at<float>(21) = 1e-2;// 5.0f;
825 kf.processNoiseCov.at<float>(28) = 5e-3;
826 kf.processNoiseCov.at<float>(35) = 5e-3;
827
828 // Measures Noise Covariance Matrix R - result smoother with higher values (1e-1)
829 cv::setIdentity(kf.measurementNoiseCov, cv::Scalar(1e-1));
830
831 //cv::setIdentity(kf.errorCovPost, cv::Scalar::all(1e-2));
832 // <<<< Kalman Filter
833
834 set_delta_time(0);
835 }
836
837
one_kalman_ttrack_kalman_t::one_kalman_t838 one_kalman_t(int _stateSize = 6, int _measSize = 4, int _contrSize = 0) :
839 kf(_stateSize, _measSize, _contrSize, CV_32F), measSize(_measSize), stateSize(_stateSize), contrSize(_contrSize)
840 {
841 state = cv::Mat(stateSize, 1, CV_32F); // [x,y,v_x,v_y,w,h]
842 meas = cv::Mat(measSize, 1, CV_32F); // [z_x,z_y,z_w,z_h]
843 //cv::Mat procNoise(stateSize, 1, type)
844 // [E_x,E_y,E_v_x,E_v_y,E_w,E_h]
845
846 initialize_kalman();
847 }
848 };
849 // ------------------------------------------
850
851
852
track_kalman_t(int _max_objects=1000,int _min_frames=3,float _max_dist=40,cv::Size _img_size=cv::Size (10000,10000))853 track_kalman_t(int _max_objects = 1000, int _min_frames = 3, float _max_dist = 40, cv::Size _img_size = cv::Size(10000, 10000)) :
854 max_objects(_max_objects), min_frames(_min_frames), max_dist(_max_dist), img_size(_img_size),
855 track_id_counter(0)
856 {
857 kalman_vec.resize(max_objects);
858 track_id_state_id_time.resize(max_objects);
859 result_vec_pred.resize(max_objects);
860 }
861
calc_dt()862 float calc_dt() {
863 dT = std::chrono::duration<double>(std::chrono::steady_clock::now() - global_last_time).count();
864 return dT;
865 }
866
get_distance(float src_x,float src_y,float dst_x,float dst_y)867 static float get_distance(float src_x, float src_y, float dst_x, float dst_y) {
868 return sqrtf((src_x - dst_x)*(src_x - dst_x) + (src_y - dst_y)*(src_y - dst_y));
869 }
870
clear_old_states()871 void clear_old_states() {
872 // clear old bboxes
873 for (size_t state_id = 0; state_id < track_id_state_id_time.size(); ++state_id)
874 {
875 float time_sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - track_id_state_id_time[state_id].last_time).count();
876 float time_wait = 0.5; // 0.5 second
877 if (track_id_state_id_time[state_id].track_id > -1)
878 {
879 if ((result_vec_pred[state_id].x > img_size.width) ||
880 (result_vec_pred[state_id].y > img_size.height))
881 {
882 track_id_state_id_time[state_id].track_id = -1;
883 }
884
885 if (time_sec >= time_wait || track_id_state_id_time[state_id].detection_count < 0) {
886 //std::cerr << " remove track_id = " << track_id_state_id_time[state_id].track_id << ", state_id = " << state_id << std::endl;
887 track_id_state_id_time[state_id].track_id = -1; // remove bbox
888 }
889 }
890 }
891 }
892
get_state_id(bbox_t find_box,std::vector<bool> & busy_vec)893 tst_t get_state_id(bbox_t find_box, std::vector<bool> &busy_vec)
894 {
895 tst_t tst;
896 tst.state_id = -1;
897
898 float min_dist = std::numeric_limits<float>::max();
899
900 for (size_t i = 0; i < max_objects; ++i)
901 {
902 if (track_id_state_id_time[i].track_id > -1 && result_vec_pred[i].obj_id == find_box.obj_id && busy_vec[i] == false)
903 {
904 bbox_t pred_box = result_vec_pred[i];
905
906 float dist = get_distance(pred_box.x, pred_box.y, find_box.x, find_box.y);
907
908 float movement_dist = std::max(max_dist, static_cast<float>(std::max(pred_box.w, pred_box.h)) );
909
910 if ((dist < movement_dist) && (dist < min_dist)) {
911 min_dist = dist;
912 tst.state_id = i;
913 }
914 }
915 }
916
917 if (tst.state_id > -1) {
918 track_id_state_id_time[tst.state_id].last_time = std::chrono::steady_clock::now();
919 track_id_state_id_time[tst.state_id].detection_count = std::max(track_id_state_id_time[tst.state_id].detection_count + 2, 10);
920 tst = track_id_state_id_time[tst.state_id];
921 busy_vec[tst.state_id] = true;
922 }
923 else {
924 //std::cerr << " Didn't find: obj_id = " << find_box.obj_id << ", x = " << find_box.x << ", y = " << find_box.y <<
925 // ", track_id_counter = " << track_id_counter << std::endl;
926 }
927
928 return tst;
929 }
930
new_state_id(std::vector<bool> & busy_vec)931 tst_t new_state_id(std::vector<bool> &busy_vec)
932 {
933 tst_t tst;
934 // find empty cell to add new track_id
935 auto it = std::find_if(track_id_state_id_time.begin(), track_id_state_id_time.end(), [&](tst_t &v) { return v.track_id == -1; });
936 if (it != track_id_state_id_time.end()) {
937 it->state_id = it - track_id_state_id_time.begin();
938 //it->track_id = track_id_counter++;
939 it->track_id = 0;
940 it->last_time = std::chrono::steady_clock::now();
941 it->detection_count = 1;
942 tst = *it;
943 busy_vec[it->state_id] = true;
944 }
945
946 return tst;
947 }
948
find_state_ids(std::vector<bbox_t> result_vec)949 std::vector<tst_t> find_state_ids(std::vector<bbox_t> result_vec)
950 {
951 std::vector<tst_t> tst_vec(result_vec.size());
952
953 std::vector<bool> busy_vec(max_objects, false);
954
955 for (size_t i = 0; i < result_vec.size(); ++i)
956 {
957 tst_t tst = get_state_id(result_vec[i], busy_vec);
958 int state_id = tst.state_id;
959 int track_id = tst.track_id;
960
961 // if new state_id
962 if (state_id < 0) {
963 tst = new_state_id(busy_vec);
964 state_id = tst.state_id;
965 track_id = tst.track_id;
966 if (state_id > -1) {
967 kalman_vec[state_id].set(result_vec[i]);
968 //std::cerr << " post: ";
969 }
970 }
971
972 //std::cerr << " track_id = " << track_id << ", state_id = " << state_id <<
973 // ", x = " << result_vec[i].x << ", det_count = " << tst.detection_count << std::endl;
974
975 if (state_id > -1) {
976 tst_vec[i] = tst;
977 result_vec_pred[state_id] = result_vec[i];
978 result_vec_pred[state_id].track_id = track_id;
979 }
980 }
981
982 return tst_vec;
983 }
984
predict()985 std::vector<bbox_t> predict()
986 {
987 clear_old_states();
988 std::vector<bbox_t> result_vec;
989
990 for (size_t i = 0; i < max_objects; ++i)
991 {
992 tst_t tst = track_id_state_id_time[i];
993 if (tst.track_id > -1) {
994 bbox_t box = kalman_vec[i].predict();
995
996 result_vec_pred[i].x = box.x;
997 result_vec_pred[i].y = box.y;
998 result_vec_pred[i].w = box.w;
999 result_vec_pred[i].h = box.h;
1000
1001 if (tst.detection_count >= min_frames)
1002 {
1003 if (track_id_state_id_time[i].track_id == 0) {
1004 track_id_state_id_time[i].track_id = ++track_id_counter;
1005 result_vec_pred[i].track_id = track_id_counter;
1006 }
1007
1008 result_vec.push_back(result_vec_pred[i]);
1009 }
1010 }
1011 }
1012 //std::cerr << " result_vec.size() = " << result_vec.size() << std::endl;
1013
1014 //global_last_time = std::chrono::steady_clock::now();
1015
1016 return result_vec;
1017 }
1018
1019
correct(std::vector<bbox_t> result_vec)1020 std::vector<bbox_t> correct(std::vector<bbox_t> result_vec)
1021 {
1022 calc_dt();
1023 clear_old_states();
1024
1025 for (size_t i = 0; i < max_objects; ++i)
1026 track_id_state_id_time[i].detection_count--;
1027
1028 std::vector<tst_t> tst_vec = find_state_ids(result_vec);
1029
1030 for (size_t i = 0; i < tst_vec.size(); ++i) {
1031 tst_t tst = tst_vec[i];
1032 int state_id = tst.state_id;
1033 if (state_id > -1)
1034 {
1035 kalman_vec[state_id].set_delta_time(dT);
1036 kalman_vec[state_id].correct(result_vec_pred[state_id]);
1037 }
1038 }
1039
1040 result_vec = predict();
1041
1042 global_last_time = std::chrono::steady_clock::now();
1043
1044 return result_vec;
1045 }
1046
1047 };
1048 // ----------------------------------------------
1049 #endif // OPENCV
1050
1051 #endif // __cplusplus
1052
1053 #endif // YOLO_V2_CLASS_HPP
1054