You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

nanodet.cpp 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. // Copyright 2020 Tencent
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. #include "net.h"
  4. #if defined(USE_NCNN_SIMPLEOCV)
  5. #include "simpleocv.h"
  6. #else
  7. #include <opencv2/core/core.hpp>
  8. #include <opencv2/highgui/highgui.hpp>
  9. #include <opencv2/imgproc/imgproc.hpp>
  10. #endif
  11. #include <stdlib.h>
  12. #include <float.h>
  13. #include <stdio.h>
  14. #include <vector>
  15. struct Object
  16. {
  17. cv::Rect_<float> rect;
  18. int label;
  19. float prob;
  20. };
  21. static inline float intersection_area(const Object& a, const Object& b)
  22. {
  23. cv::Rect_<float> inter = a.rect & b.rect;
  24. return inter.area();
  25. }
  26. static void qsort_descent_inplace(std::vector<Object>& faceobjects, int left, int right)
  27. {
  28. int i = left;
  29. int j = right;
  30. float p = faceobjects[(left + right) / 2].prob;
  31. while (i <= j)
  32. {
  33. while (faceobjects[i].prob > p)
  34. i++;
  35. while (faceobjects[j].prob < p)
  36. j--;
  37. if (i <= j)
  38. {
  39. // swap
  40. std::swap(faceobjects[i], faceobjects[j]);
  41. i++;
  42. j--;
  43. }
  44. }
  45. #pragma omp parallel sections
  46. {
  47. #pragma omp section
  48. {
  49. if (left < j) qsort_descent_inplace(faceobjects, left, j);
  50. }
  51. #pragma omp section
  52. {
  53. if (i < right) qsort_descent_inplace(faceobjects, i, right);
  54. }
  55. }
  56. }
  57. static void qsort_descent_inplace(std::vector<Object>& faceobjects)
  58. {
  59. if (faceobjects.empty())
  60. return;
  61. qsort_descent_inplace(faceobjects, 0, faceobjects.size() - 1);
  62. }
  63. static void nms_sorted_bboxes(const std::vector<Object>& faceobjects, std::vector<int>& picked, float nms_threshold, bool agnostic = false)
  64. {
  65. picked.clear();
  66. const int n = faceobjects.size();
  67. std::vector<float> areas(n);
  68. for (int i = 0; i < n; i++)
  69. {
  70. areas[i] = faceobjects[i].rect.area();
  71. }
  72. for (int i = 0; i < n; i++)
  73. {
  74. const Object& a = faceobjects[i];
  75. int keep = 1;
  76. for (int j = 0; j < (int)picked.size(); j++)
  77. {
  78. const Object& b = faceobjects[picked[j]];
  79. if (!agnostic && a.label != b.label)
  80. continue;
  81. // intersection over union
  82. float inter_area = intersection_area(a, b);
  83. float union_area = areas[i] + areas[picked[j]] - inter_area;
  84. // float IoU = inter_area / union_area
  85. if (inter_area / union_area > nms_threshold)
  86. keep = 0;
  87. }
  88. if (keep)
  89. picked.push_back(i);
  90. }
  91. }
  92. static void generate_proposals(const ncnn::Mat& cls_pred, const ncnn::Mat& dis_pred, int stride, const ncnn::Mat& in_pad, float prob_threshold, std::vector<Object>& objects)
  93. {
  94. const int num_grid = cls_pred.h;
  95. int num_grid_x;
  96. int num_grid_y;
  97. if (in_pad.w > in_pad.h)
  98. {
  99. num_grid_x = in_pad.w / stride;
  100. num_grid_y = num_grid / num_grid_x;
  101. }
  102. else
  103. {
  104. num_grid_y = in_pad.h / stride;
  105. num_grid_x = num_grid / num_grid_y;
  106. }
  107. const int num_class = cls_pred.w;
  108. const int reg_max_1 = dis_pred.w / 4;
  109. for (int i = 0; i < num_grid_y; i++)
  110. {
  111. for (int j = 0; j < num_grid_x; j++)
  112. {
  113. const int idx = i * num_grid_x + j;
  114. const float* scores = cls_pred.row(idx);
  115. // find label with max score
  116. int label = -1;
  117. float score = -FLT_MAX;
  118. for (int k = 0; k < num_class; k++)
  119. {
  120. if (scores[k] > score)
  121. {
  122. label = k;
  123. score = scores[k];
  124. }
  125. }
  126. if (score >= prob_threshold)
  127. {
  128. ncnn::Mat bbox_pred(reg_max_1, 4, (void*)dis_pred.row(idx));
  129. {
  130. ncnn::Layer* softmax = ncnn::create_layer("Softmax");
  131. ncnn::ParamDict pd;
  132. pd.set(0, 1); // axis
  133. pd.set(1, 1);
  134. softmax->load_param(pd);
  135. ncnn::Option opt;
  136. opt.num_threads = 1;
  137. opt.use_packing_layout = false;
  138. softmax->create_pipeline(opt);
  139. softmax->forward_inplace(bbox_pred, opt);
  140. softmax->destroy_pipeline(opt);
  141. delete softmax;
  142. }
  143. float pred_ltrb[4];
  144. for (int k = 0; k < 4; k++)
  145. {
  146. float dis = 0.f;
  147. const float* dis_after_sm = bbox_pred.row(k);
  148. for (int l = 0; l < reg_max_1; l++)
  149. {
  150. dis += l * dis_after_sm[l];
  151. }
  152. pred_ltrb[k] = dis * stride;
  153. }
  154. float pb_cx = (j + 0.5f) * stride;
  155. float pb_cy = (i + 0.5f) * stride;
  156. float x0 = pb_cx - pred_ltrb[0];
  157. float y0 = pb_cy - pred_ltrb[1];
  158. float x1 = pb_cx + pred_ltrb[2];
  159. float y1 = pb_cy + pred_ltrb[3];
  160. Object obj;
  161. obj.rect.x = x0;
  162. obj.rect.y = y0;
  163. obj.rect.width = x1 - x0;
  164. obj.rect.height = y1 - y0;
  165. obj.label = label;
  166. obj.prob = score;
  167. objects.push_back(obj);
  168. }
  169. }
  170. }
  171. }
  172. static int detect_nanodet(const cv::Mat& bgr, std::vector<Object>& objects)
  173. {
  174. ncnn::Net nanodet;
  175. nanodet.opt.use_vulkan_compute = true;
  176. // nanodet.opt.use_bf16_storage = true;
  177. // original pretrained model from https://github.com/RangiLyu/nanodet
  178. // the ncnn model https://github.com/nihui/ncnn-assets/tree/master/models
  179. if (nanodet.load_param("nanodet_m.param"))
  180. exit(-1);
  181. if (nanodet.load_model("nanodet_m.bin"))
  182. exit(-1);
  183. int width = bgr.cols;
  184. int height = bgr.rows;
  185. const int target_size = 320;
  186. const float prob_threshold = 0.4f;
  187. const float nms_threshold = 0.5f;
  188. // pad to multiple of 32
  189. int w = width;
  190. int h = height;
  191. float scale = 1.f;
  192. if (w > h)
  193. {
  194. scale = (float)target_size / w;
  195. w = target_size;
  196. h = h * scale;
  197. }
  198. else
  199. {
  200. scale = (float)target_size / h;
  201. h = target_size;
  202. w = w * scale;
  203. }
  204. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR, width, height, w, h);
  205. // pad to target_size rectangle
  206. int wpad = (w + 31) / 32 * 32 - w;
  207. int hpad = (h + 31) / 32 * 32 - h;
  208. ncnn::Mat in_pad;
  209. ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 0.f);
  210. const float mean_vals[3] = {103.53f, 116.28f, 123.675f};
  211. const float norm_vals[3] = {0.017429f, 0.017507f, 0.017125f};
  212. in_pad.substract_mean_normalize(mean_vals, norm_vals);
  213. ncnn::Extractor ex = nanodet.create_extractor();
  214. ex.input("input.1", in_pad);
  215. std::vector<Object> proposals;
  216. // stride 8
  217. {
  218. ncnn::Mat cls_pred;
  219. ncnn::Mat dis_pred;
  220. ex.extract("792", cls_pred);
  221. ex.extract("795", dis_pred);
  222. std::vector<Object> objects8;
  223. generate_proposals(cls_pred, dis_pred, 8, in_pad, prob_threshold, objects8);
  224. proposals.insert(proposals.end(), objects8.begin(), objects8.end());
  225. }
  226. // stride 16
  227. {
  228. ncnn::Mat cls_pred;
  229. ncnn::Mat dis_pred;
  230. ex.extract("814", cls_pred);
  231. ex.extract("817", dis_pred);
  232. std::vector<Object> objects16;
  233. generate_proposals(cls_pred, dis_pred, 16, in_pad, prob_threshold, objects16);
  234. proposals.insert(proposals.end(), objects16.begin(), objects16.end());
  235. }
  236. // stride 32
  237. {
  238. ncnn::Mat cls_pred;
  239. ncnn::Mat dis_pred;
  240. ex.extract("836", cls_pred);
  241. ex.extract("839", dis_pred);
  242. std::vector<Object> objects32;
  243. generate_proposals(cls_pred, dis_pred, 32, in_pad, prob_threshold, objects32);
  244. proposals.insert(proposals.end(), objects32.begin(), objects32.end());
  245. }
  246. // sort all proposals by score from highest to lowest
  247. qsort_descent_inplace(proposals);
  248. // apply nms with nms_threshold
  249. std::vector<int> picked;
  250. nms_sorted_bboxes(proposals, picked, nms_threshold);
  251. int count = picked.size();
  252. objects.resize(count);
  253. for (int i = 0; i < count; i++)
  254. {
  255. objects[i] = proposals[picked[i]];
  256. // adjust offset to original unpadded
  257. float x0 = (objects[i].rect.x - (wpad / 2)) / scale;
  258. float y0 = (objects[i].rect.y - (hpad / 2)) / scale;
  259. float x1 = (objects[i].rect.x + objects[i].rect.width - (wpad / 2)) / scale;
  260. float y1 = (objects[i].rect.y + objects[i].rect.height - (hpad / 2)) / scale;
  261. // clip
  262. x0 = std::max(std::min(x0, (float)(width - 1)), 0.f);
  263. y0 = std::max(std::min(y0, (float)(height - 1)), 0.f);
  264. x1 = std::max(std::min(x1, (float)(width - 1)), 0.f);
  265. y1 = std::max(std::min(y1, (float)(height - 1)), 0.f);
  266. objects[i].rect.x = x0;
  267. objects[i].rect.y = y0;
  268. objects[i].rect.width = x1 - x0;
  269. objects[i].rect.height = y1 - y0;
  270. }
  271. return 0;
  272. }
  273. static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
  274. {
  275. static const char* class_names[] = {
  276. "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light",
  277. "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow",
  278. "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
  279. "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard",
  280. "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
  281. "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch",
  282. "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone",
  283. "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear",
  284. "hair drier", "toothbrush"
  285. };
  286. cv::Mat image = bgr.clone();
  287. for (size_t i = 0; i < objects.size(); i++)
  288. {
  289. const Object& obj = objects[i];
  290. fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob,
  291. obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
  292. cv::rectangle(image, obj.rect, cv::Scalar(255, 0, 0));
  293. char text[256];
  294. sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100);
  295. int baseLine = 0;
  296. cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
  297. int x = obj.rect.x;
  298. int y = obj.rect.y - label_size.height - baseLine;
  299. if (y < 0)
  300. y = 0;
  301. if (x + label_size.width > image.cols)
  302. x = image.cols - label_size.width;
  303. cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
  304. cv::Scalar(255, 255, 255), -1);
  305. cv::putText(image, text, cv::Point(x, y + label_size.height),
  306. cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
  307. }
  308. cv::imshow("image", image);
  309. cv::waitKey(0);
  310. }
  311. int main(int argc, char** argv)
  312. {
  313. if (argc != 2)
  314. {
  315. fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
  316. return -1;
  317. }
  318. const char* imagepath = argv[1];
  319. cv::Mat m = cv::imread(imagepath, 1);
  320. if (m.empty())
  321. {
  322. fprintf(stderr, "cv::imread %s failed\n", imagepath);
  323. return -1;
  324. }
  325. std::vector<Object> objects;
  326. detect_nanodet(m, objects);
  327. draw_objects(m, objects);
  328. return 0;
  329. }