yolo_v2_class.hpp 39 KB

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