Meta Byte Track
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.

bytetrack.cpp 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. #include "layer.h"
  2. #include "net.h"
  3. #if defined(USE_NCNN_SIMPLEOCV)
  4. #include "simpleocv.h"
  5. #include <opencv2/opencv.hpp>
  6. #else
  7. #include <opencv2/core/core.hpp>
  8. #include <opencv2/highgui/highgui.hpp>
  9. #include <opencv2/imgproc/imgproc.hpp>
  10. #include <opencv2/opencv.hpp>
  11. #endif
  12. #include <float.h>
  13. #include <stdio.h>
  14. #include <vector>
  15. #include <chrono>
  16. #include "BYTETracker.h"
  17. #define YOLOX_NMS_THRESH 0.7 // nms threshold
  18. #define YOLOX_CONF_THRESH 0.1 // threshold of bounding box prob
  19. #define INPUT_W 1088 // target image size w after resize
  20. #define INPUT_H 608 // target image size h after resize
  21. Mat static_resize(Mat& img) {
  22. float r = min(INPUT_W / (img.cols*1.0), INPUT_H / (img.rows*1.0));
  23. // r = std::min(r, 1.0f);
  24. int unpad_w = r * img.cols;
  25. int unpad_h = r * img.rows;
  26. Mat re(unpad_h, unpad_w, CV_8UC3);
  27. resize(img, re, re.size());
  28. Mat out(INPUT_H, INPUT_W, CV_8UC3, Scalar(114, 114, 114));
  29. re.copyTo(out(Rect(0, 0, re.cols, re.rows)));
  30. return out;
  31. }
  32. // YOLOX use the same focus in yolov5
  33. class YoloV5Focus : public ncnn::Layer
  34. {
  35. public:
  36. YoloV5Focus()
  37. {
  38. one_blob_only = true;
  39. }
  40. virtual int forward(const ncnn::Mat& bottom_blob, ncnn::Mat& top_blob, const ncnn::Option& opt) const
  41. {
  42. int w = bottom_blob.w;
  43. int h = bottom_blob.h;
  44. int channels = bottom_blob.c;
  45. int outw = w / 2;
  46. int outh = h / 2;
  47. int outc = channels * 4;
  48. top_blob.create(outw, outh, outc, 4u, 1, opt.blob_allocator);
  49. if (top_blob.empty())
  50. return -100;
  51. #pragma omp parallel for num_threads(opt.num_threads)
  52. for (int p = 0; p < outc; p++)
  53. {
  54. const float* ptr = bottom_blob.channel(p % channels).row((p / channels) % 2) + ((p / channels) / 2);
  55. float* outptr = top_blob.channel(p);
  56. for (int i = 0; i < outh; i++)
  57. {
  58. for (int j = 0; j < outw; j++)
  59. {
  60. *outptr = *ptr;
  61. outptr += 1;
  62. ptr += 2;
  63. }
  64. ptr += w;
  65. }
  66. }
  67. return 0;
  68. }
  69. };
  70. DEFINE_LAYER_CREATOR(YoloV5Focus)
  71. struct GridAndStride
  72. {
  73. int grid0;
  74. int grid1;
  75. int stride;
  76. };
  77. static inline float intersection_area(const Object& a, const Object& b)
  78. {
  79. cv::Rect_<float> inter = a.rect & b.rect;
  80. return inter.area();
  81. }
  82. static void qsort_descent_inplace(std::vector<Object>& faceobjects, int left, int right)
  83. {
  84. int i = left;
  85. int j = right;
  86. float p = faceobjects[(left + right) / 2].prob;
  87. while (i <= j)
  88. {
  89. while (faceobjects[i].prob > p)
  90. i++;
  91. while (faceobjects[j].prob < p)
  92. j--;
  93. if (i <= j)
  94. {
  95. // swap
  96. std::swap(faceobjects[i], faceobjects[j]);
  97. i++;
  98. j--;
  99. }
  100. }
  101. #pragma omp parallel sections
  102. {
  103. #pragma omp section
  104. {
  105. if (left < j) qsort_descent_inplace(faceobjects, left, j);
  106. }
  107. #pragma omp section
  108. {
  109. if (i < right) qsort_descent_inplace(faceobjects, i, right);
  110. }
  111. }
  112. }
  113. static void qsort_descent_inplace(std::vector<Object>& objects)
  114. {
  115. if (objects.empty())
  116. return;
  117. qsort_descent_inplace(objects, 0, objects.size() - 1);
  118. }
  119. static void nms_sorted_bboxes(const std::vector<Object>& faceobjects, std::vector<int>& picked, float nms_threshold)
  120. {
  121. picked.clear();
  122. const int n = faceobjects.size();
  123. std::vector<float> areas(n);
  124. for (int i = 0; i < n; i++)
  125. {
  126. areas[i] = faceobjects[i].rect.area();
  127. }
  128. for (int i = 0; i < n; i++)
  129. {
  130. const Object& a = faceobjects[i];
  131. int keep = 1;
  132. for (int j = 0; j < (int)picked.size(); j++)
  133. {
  134. const Object& b = faceobjects[picked[j]];
  135. // intersection over union
  136. float inter_area = intersection_area(a, b);
  137. float union_area = areas[i] + areas[picked[j]] - inter_area;
  138. // float IoU = inter_area / union_area
  139. if (inter_area / union_area > nms_threshold)
  140. keep = 0;
  141. }
  142. if (keep)
  143. picked.push_back(i);
  144. }
  145. }
  146. static void generate_grids_and_stride(const int target_w, const int target_h, std::vector<int>& strides, std::vector<GridAndStride>& grid_strides)
  147. {
  148. for (int i = 0; i < (int)strides.size(); i++)
  149. {
  150. int stride = strides[i];
  151. int num_grid_w = target_w / stride;
  152. int num_grid_h = target_h / stride;
  153. for (int g1 = 0; g1 < num_grid_h; g1++)
  154. {
  155. for (int g0 = 0; g0 < num_grid_w; g0++)
  156. {
  157. GridAndStride gs;
  158. gs.grid0 = g0;
  159. gs.grid1 = g1;
  160. gs.stride = stride;
  161. grid_strides.push_back(gs);
  162. }
  163. }
  164. }
  165. }
  166. static void generate_yolox_proposals(std::vector<GridAndStride> grid_strides, const ncnn::Mat& feat_blob, float prob_threshold, std::vector<Object>& objects)
  167. {
  168. const int num_grid = feat_blob.h;
  169. const int num_class = feat_blob.w - 5;
  170. const int num_anchors = grid_strides.size();
  171. const float* feat_ptr = feat_blob.channel(0);
  172. for (int anchor_idx = 0; anchor_idx < num_anchors; anchor_idx++)
  173. {
  174. const int grid0 = grid_strides[anchor_idx].grid0;
  175. const int grid1 = grid_strides[anchor_idx].grid1;
  176. const int stride = grid_strides[anchor_idx].stride;
  177. // yolox/models/yolo_head.py decode logic
  178. // outputs[..., :2] = (outputs[..., :2] + grids) * strides
  179. // outputs[..., 2:4] = torch.exp(outputs[..., 2:4]) * strides
  180. float x_center = (feat_ptr[0] + grid0) * stride;
  181. float y_center = (feat_ptr[1] + grid1) * stride;
  182. float w = exp(feat_ptr[2]) * stride;
  183. float h = exp(feat_ptr[3]) * stride;
  184. float x0 = x_center - w * 0.5f;
  185. float y0 = y_center - h * 0.5f;
  186. float box_objectness = feat_ptr[4];
  187. for (int class_idx = 0; class_idx < num_class; class_idx++)
  188. {
  189. float box_cls_score = feat_ptr[5 + class_idx];
  190. float box_prob = box_objectness * box_cls_score;
  191. if (box_prob > prob_threshold)
  192. {
  193. Object obj;
  194. obj.rect.x = x0;
  195. obj.rect.y = y0;
  196. obj.rect.width = w;
  197. obj.rect.height = h;
  198. obj.label = class_idx;
  199. obj.prob = box_prob;
  200. objects.push_back(obj);
  201. }
  202. } // class loop
  203. feat_ptr += feat_blob.w;
  204. } // point anchor loop
  205. }
  206. static int detect_yolox(ncnn::Mat& in_pad, std::vector<Object>& objects, ncnn::Extractor ex, float scale)
  207. {
  208. ex.input("images", in_pad);
  209. std::vector<Object> proposals;
  210. {
  211. ncnn::Mat out;
  212. ex.extract("output", out);
  213. static const int stride_arr[] = {8, 16, 32}; // might have stride=64 in YOLOX
  214. std::vector<int> strides(stride_arr, stride_arr + sizeof(stride_arr) / sizeof(stride_arr[0]));
  215. std::vector<GridAndStride> grid_strides;
  216. generate_grids_and_stride(INPUT_W, INPUT_H, strides, grid_strides);
  217. generate_yolox_proposals(grid_strides, out, YOLOX_CONF_THRESH, proposals);
  218. }
  219. // sort all proposals by score from highest to lowest
  220. qsort_descent_inplace(proposals);
  221. // apply nms with nms_threshold
  222. std::vector<int> picked;
  223. nms_sorted_bboxes(proposals, picked, YOLOX_NMS_THRESH);
  224. int count = picked.size();
  225. objects.resize(count);
  226. for (int i = 0; i < count; i++)
  227. {
  228. objects[i] = proposals[picked[i]];
  229. // adjust offset to original unpadded
  230. float x0 = (objects[i].rect.x) / scale;
  231. float y0 = (objects[i].rect.y) / scale;
  232. float x1 = (objects[i].rect.x + objects[i].rect.width) / scale;
  233. float y1 = (objects[i].rect.y + objects[i].rect.height) / scale;
  234. // clip
  235. // x0 = std::max(std::min(x0, (float)(img_w - 1)), 0.f);
  236. // y0 = std::max(std::min(y0, (float)(img_h - 1)), 0.f);
  237. // x1 = std::max(std::min(x1, (float)(img_w - 1)), 0.f);
  238. // y1 = std::max(std::min(y1, (float)(img_h - 1)), 0.f);
  239. objects[i].rect.x = x0;
  240. objects[i].rect.y = y0;
  241. objects[i].rect.width = x1 - x0;
  242. objects[i].rect.height = y1 - y0;
  243. }
  244. return 0;
  245. }
  246. int main(int argc, char** argv)
  247. {
  248. if (argc != 2)
  249. {
  250. fprintf(stderr, "Usage: %s [videopath]\n", argv[0]);
  251. return -1;
  252. }
  253. ncnn::Net yolox;
  254. //yolox.opt.use_vulkan_compute = true;
  255. //yolox.opt.use_bf16_storage = true;
  256. yolox.opt.num_threads = 20;
  257. //ncnn::set_cpu_powersave(0);
  258. //ncnn::set_omp_dynamic(0);
  259. //ncnn::set_omp_num_threads(20);
  260. // Focus in yolov5
  261. yolox.register_custom_layer("YoloV5Focus", YoloV5Focus_layer_creator);
  262. yolox.load_param("bytetrack_s_op.param");
  263. yolox.load_model("bytetrack_s_op.bin");
  264. ncnn::Extractor ex = yolox.create_extractor();
  265. const char* videopath = argv[1];
  266. VideoCapture cap(videopath);
  267. if (!cap.isOpened())
  268. return 0;
  269. int img_w = cap.get(CV_CAP_PROP_FRAME_WIDTH);
  270. int img_h = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
  271. int fps = cap.get(CV_CAP_PROP_FPS);
  272. long nFrame = static_cast<long>(cap.get(CV_CAP_PROP_FRAME_COUNT));
  273. cout << "Total frames: " << nFrame << endl;
  274. VideoWriter writer("demo.mp4", CV_FOURCC('m', 'p', '4', 'v'), fps, Size(img_w, img_h));
  275. Mat img;
  276. BYTETracker tracker(fps, 30);
  277. int num_frames = 0;
  278. int total_ms = 1;
  279. for (;;)
  280. {
  281. if(!cap.read(img))
  282. break;
  283. num_frames ++;
  284. if (num_frames % 20 == 0)
  285. {
  286. cout << "Processing frame " << num_frames << " (" << num_frames * 1000000 / total_ms << " fps)" << endl;
  287. }
  288. if (img.empty())
  289. break;
  290. float scale = min(INPUT_W / (img.cols*1.0), INPUT_H / (img.rows*1.0));
  291. Mat pr_img = static_resize(img);
  292. ncnn::Mat in_pad = ncnn::Mat::from_pixels_resize(pr_img.data, ncnn::Mat::PIXEL_BGR2RGB, INPUT_W, INPUT_H, INPUT_W, INPUT_H);
  293. // python 0-1 input tensor with rgb_means = (0.485, 0.456, 0.406), std = (0.229, 0.224, 0.225)
  294. // so for 0-255 input image, rgb_mean should multiply 255 and norm should div by std.
  295. const float mean_vals[3] = {255.f * 0.485f, 255.f * 0.456, 255.f * 0.406f};
  296. const float norm_vals[3] = {1 / (255.f * 0.229f), 1 / (255.f * 0.224f), 1 / (255.f * 0.225f)};
  297. in_pad.substract_mean_normalize(mean_vals, norm_vals);
  298. std::vector<Object> objects;
  299. auto start = chrono::system_clock::now();
  300. //detect_yolox(img, objects);
  301. detect_yolox(in_pad, objects, ex, scale);
  302. vector<STrack> output_stracks = tracker.update(objects);
  303. auto end = chrono::system_clock::now();
  304. total_ms = total_ms + chrono::duration_cast<chrono::microseconds>(end - start).count();
  305. for (int i = 0; i < output_stracks.size(); i++)
  306. {
  307. vector<float> tlwh = output_stracks[i].tlwh;
  308. bool vertical = tlwh[2] / tlwh[3] > 1.6;
  309. if (tlwh[2] * tlwh[3] > 20 && !vertical)
  310. {
  311. Scalar s = tracker.get_color(output_stracks[i].track_id);
  312. putText(img, format("%d", output_stracks[i].track_id), Point(tlwh[0], tlwh[1] - 5),
  313. 0, 0.6, Scalar(0, 0, 255), 2, LINE_AA);
  314. rectangle(img, Rect(tlwh[0], tlwh[1], tlwh[2], tlwh[3]), s, 2);
  315. }
  316. }
  317. putText(img, format("frame: %d fps: %d num: %d", num_frames, num_frames * 1000000 / total_ms, output_stracks.size()),
  318. Point(0, 30), 0, 0.6, Scalar(0, 0, 255), 2, LINE_AA);
  319. writer.write(img);
  320. char c = waitKey(1);
  321. if (c > 0)
  322. {
  323. break;
  324. }
  325. }
  326. cap.release();
  327. cout << "FPS: " << num_frames * 1000000 / total_ms << endl;
  328. return 0;
  329. }