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 13 kB

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