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

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