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.

scrfd_crowdhuman.cpp 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. // Copyright 2021 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 <stdio.h>
  12. #include <vector>
  13. struct FaceObject
  14. {
  15. cv::Rect_<float> rect;
  16. float prob;
  17. };
  18. static inline float intersection_area(const FaceObject& a, const FaceObject& b)
  19. {
  20. cv::Rect_<float> inter = a.rect & b.rect;
  21. return inter.area();
  22. }
  23. static void qsort_descent_inplace(std::vector<FaceObject>& faceobjects, int left, int right)
  24. {
  25. int i = left;
  26. int j = right;
  27. float p = faceobjects[(left + right) / 2].prob;
  28. while (i <= j)
  29. {
  30. while (faceobjects[i].prob > p)
  31. i++;
  32. while (faceobjects[j].prob < p)
  33. j--;
  34. if (i <= j)
  35. {
  36. // swap
  37. std::swap(faceobjects[i], faceobjects[j]);
  38. i++;
  39. j--;
  40. }
  41. }
  42. #pragma omp parallel sections
  43. {
  44. #pragma omp section
  45. {
  46. if (left < j) qsort_descent_inplace(faceobjects, left, j);
  47. }
  48. #pragma omp section
  49. {
  50. if (i < right) qsort_descent_inplace(faceobjects, i, right);
  51. }
  52. }
  53. }
  54. static void qsort_descent_inplace(std::vector<FaceObject>& faceobjects)
  55. {
  56. if (faceobjects.empty())
  57. return;
  58. qsort_descent_inplace(faceobjects, 0, faceobjects.size() - 1);
  59. }
  60. static void nms_sorted_bboxes(const std::vector<FaceObject>& faceobjects, std::vector<int>& picked, float nms_threshold)
  61. {
  62. picked.clear();
  63. const int n = faceobjects.size();
  64. std::vector<float> areas(n);
  65. for (int i = 0; i < n; i++)
  66. {
  67. areas[i] = faceobjects[i].rect.area();
  68. }
  69. for (int i = 0; i < n; i++)
  70. {
  71. const FaceObject& a = faceobjects[i];
  72. int keep = 1;
  73. for (int j = 0; j < (int)picked.size(); j++)
  74. {
  75. const FaceObject& b = faceobjects[picked[j]];
  76. // intersection over union
  77. float inter_area = intersection_area(a, b);
  78. float union_area = areas[i] + areas[picked[j]] - inter_area;
  79. // float IoU = inter_area / union_area
  80. if (inter_area / union_area > nms_threshold)
  81. keep = 0;
  82. }
  83. if (keep)
  84. picked.push_back(i);
  85. }
  86. }
  87. // insightface/detection/scrfd/mmdet/core/anchor/anchor_generator.py gen_single_level_base_anchors()
  88. static ncnn::Mat generate_anchors(int base_size, const ncnn::Mat& ratios, const ncnn::Mat& scales)
  89. {
  90. int num_ratio = ratios.w;
  91. int num_scale = scales.w;
  92. ncnn::Mat anchors;
  93. anchors.create(4, num_ratio * num_scale);
  94. const float cx = 0;
  95. const float cy = 0;
  96. for (int i = 0; i < num_ratio; i++)
  97. {
  98. float ar = ratios[i];
  99. int r_w = round(base_size / sqrt(ar));
  100. int r_h = round(r_w * ar); //round(base_size * sqrt(ar));
  101. for (int j = 0; j < num_scale; j++)
  102. {
  103. float scale = scales[j];
  104. float rs_w = r_w * scale;
  105. float rs_h = r_h * scale;
  106. float* anchor = anchors.row(i * num_scale + j);
  107. anchor[0] = cx - rs_w * 0.5f;
  108. anchor[1] = cy - rs_h * 0.5f;
  109. anchor[2] = cx + rs_w * 0.5f;
  110. anchor[3] = cy + rs_h * 0.5f;
  111. }
  112. }
  113. return anchors;
  114. }
  115. static void generate_proposals(const ncnn::Mat& anchors, int feat_stride, const ncnn::Mat& score_blob, const ncnn::Mat& bbox_blob, float prob_threshold, std::vector<FaceObject>& faceobjects)
  116. {
  117. int w = score_blob.w;
  118. int h = score_blob.h;
  119. // generate face proposal from bbox deltas and shifted anchors
  120. const int num_anchors = anchors.h;
  121. for (int q = 0; q < num_anchors; q++)
  122. {
  123. const float* anchor = anchors.row(q);
  124. const ncnn::Mat score = score_blob.channel(q);
  125. const ncnn::Mat bbox = bbox_blob.channel_range(q * 4, 4);
  126. // shifted anchor
  127. float anchor_y = anchor[1];
  128. float anchor_w = anchor[2] - anchor[0];
  129. float anchor_h = anchor[3] - anchor[1];
  130. for (int i = 0; i < h; i++)
  131. {
  132. float anchor_x = anchor[0];
  133. for (int j = 0; j < w; j++)
  134. {
  135. int index = i * w + j;
  136. float prob = score[index];
  137. if (prob >= prob_threshold)
  138. {
  139. // insightface/detection/scrfd/mmdet/models/dense_heads/scrfd_head.py _get_bboxes_single()
  140. float dx = bbox.channel(0)[index] * feat_stride;
  141. float dy = bbox.channel(1)[index] * feat_stride;
  142. float dw = bbox.channel(2)[index] * feat_stride;
  143. float dh = bbox.channel(3)[index] * feat_stride;
  144. // insightface/detection/scrfd/mmdet/core/bbox/transforms.py distance2bbox()
  145. float cx = anchor_x + anchor_w * 0.5f;
  146. float cy = anchor_y + anchor_h * 0.5f;
  147. float x0 = cx - dx;
  148. float y0 = cy - dy;
  149. float x1 = cx + dw;
  150. float y1 = cy + dh;
  151. FaceObject obj;
  152. obj.rect.x = x0;
  153. obj.rect.y = y0;
  154. obj.rect.width = x1 - x0 + 1;
  155. obj.rect.height = y1 - y0 + 1;
  156. obj.prob = prob;
  157. faceobjects.push_back(obj);
  158. }
  159. anchor_x += feat_stride;
  160. }
  161. anchor_y += feat_stride;
  162. }
  163. }
  164. }
  165. static int detect_scrfd(const cv::Mat& bgr, std::vector<FaceObject>& faceobjects)
  166. {
  167. ncnn::Net scrfd;
  168. scrfd.opt.use_vulkan_compute = true;
  169. // Insight face does not provided a trained scrfd_crowdhuman model
  170. // but I have one for detecing cat face, you can have a try here:
  171. // https://drive.google.com/file/d/1JogkKa0f_09HkENbCnXy9hRYxm35wKTn
  172. if (scrfd.load_param("scrfd_crowdhuman.param"))
  173. exit(-1);
  174. if (scrfd.load_model("scrfd_crowdhuman.bin"))
  175. exit(-1);
  176. int width = bgr.cols;
  177. int height = bgr.rows;
  178. const int target_size = 640;
  179. const float prob_threshold = 0.3f;
  180. const float nms_threshold = 0.45f;
  181. // pad to multiple of 32
  182. int w = width;
  183. int h = height;
  184. float scale = 1.f;
  185. if (w > h)
  186. {
  187. scale = (float)target_size / w;
  188. w = target_size;
  189. h = h * scale;
  190. }
  191. else
  192. {
  193. scale = (float)target_size / h;
  194. h = target_size;
  195. w = w * scale;
  196. }
  197. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, width, height, w, h);
  198. // pad to target_size rectangle
  199. int wpad = (w + 31) / 32 * 32 - w;
  200. int hpad = (h + 31) / 32 * 32 - h;
  201. ncnn::Mat in_pad;
  202. ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 0.f);
  203. const float mean_vals[3] = {127.5f, 127.5f, 127.5f};
  204. const float norm_vals[3] = {1 / 128.f, 1 / 128.f, 1 / 128.f};
  205. in_pad.substract_mean_normalize(mean_vals, norm_vals);
  206. ncnn::Extractor ex = scrfd.create_extractor();
  207. ex.input("input.1", in_pad);
  208. std::vector<FaceObject> faceproposals;
  209. // stride 8
  210. {
  211. ncnn::Mat score_blob, bbox_blob;
  212. ex.extract("490", score_blob);
  213. ex.extract("493", bbox_blob);
  214. const int base_size = 8;
  215. const int feat_stride = 8;
  216. ncnn::Mat ratios(1);
  217. ratios[0] = 2.f;
  218. ncnn::Mat scales(1);
  219. scales[0] = 3.f;
  220. ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
  221. std::vector<FaceObject> faceobjects32;
  222. generate_proposals(anchors, feat_stride, score_blob, bbox_blob, prob_threshold, faceobjects32);
  223. faceproposals.insert(faceproposals.end(), faceobjects32.begin(), faceobjects32.end());
  224. }
  225. // stride 16
  226. {
  227. ncnn::Mat score_blob, bbox_blob;
  228. ex.extract("510", score_blob);
  229. ex.extract("513", bbox_blob);
  230. const int base_size = 16;
  231. const int feat_stride = 16;
  232. ncnn::Mat ratios(1);
  233. ratios[0] = 2.f;
  234. ncnn::Mat scales(1);
  235. scales[0] = 3.f;
  236. ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
  237. std::vector<FaceObject> faceobjects16;
  238. generate_proposals(anchors, feat_stride, score_blob, bbox_blob, prob_threshold, faceobjects16);
  239. faceproposals.insert(faceproposals.end(), faceobjects16.begin(), faceobjects16.end());
  240. }
  241. // stride 32
  242. {
  243. ncnn::Mat score_blob, bbox_blob;
  244. ex.extract("530", score_blob);
  245. ex.extract("533", bbox_blob);
  246. const int base_size = 32;
  247. const int feat_stride = 32;
  248. ncnn::Mat ratios(1);
  249. ratios[0] = 2.f;
  250. ncnn::Mat scales(1);
  251. scales[0] = 3.f;
  252. ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
  253. std::vector<FaceObject> faceobjects8;
  254. generate_proposals(anchors, feat_stride, score_blob, bbox_blob, prob_threshold, faceobjects8);
  255. faceproposals.insert(faceproposals.end(), faceobjects8.begin(), faceobjects8.end());
  256. }
  257. // stride 64
  258. {
  259. ncnn::Mat score_blob, bbox_blob, kps_blob;
  260. ex.extract("550", score_blob);
  261. ex.extract("553", bbox_blob);
  262. const int base_size = 64;
  263. const int feat_stride = 64;
  264. ncnn::Mat ratios(1);
  265. ratios[0] = 2.f;
  266. ncnn::Mat scales(1);
  267. scales[0] = 3.f;
  268. ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
  269. std::vector<FaceObject> faceobjects8;
  270. generate_proposals(anchors, feat_stride, score_blob, bbox_blob, prob_threshold, faceobjects8);
  271. faceproposals.insert(faceproposals.end(), faceobjects8.begin(), faceobjects8.end());
  272. }
  273. // stride 128
  274. {
  275. ncnn::Mat score_blob, bbox_blob, kps_blob;
  276. ex.extract("570", score_blob);
  277. ex.extract("573", bbox_blob);
  278. const int base_size = 128;
  279. const int feat_stride = 128;
  280. ncnn::Mat ratios(1);
  281. ratios[0] = 2.f;
  282. ncnn::Mat scales(1);
  283. scales[0] = 3.f;
  284. ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
  285. std::vector<FaceObject> faceobjects8;
  286. generate_proposals(anchors, feat_stride, score_blob, bbox_blob, prob_threshold, faceobjects8);
  287. faceproposals.insert(faceproposals.end(), faceobjects8.begin(), faceobjects8.end());
  288. }
  289. // sort all proposals by score from highest to lowest
  290. qsort_descent_inplace(faceproposals);
  291. // apply nms with nms_threshold
  292. std::vector<int> picked;
  293. nms_sorted_bboxes(faceproposals, picked, nms_threshold);
  294. int face_count = picked.size();
  295. faceobjects.resize(face_count);
  296. for (int i = 0; i < face_count; i++)
  297. {
  298. faceobjects[i] = faceproposals[picked[i]];
  299. // adjust offset to original unpadded
  300. float x0 = (faceobjects[i].rect.x - (wpad / 2)) / scale;
  301. float y0 = (faceobjects[i].rect.y - (hpad / 2)) / scale;
  302. float x1 = (faceobjects[i].rect.x + faceobjects[i].rect.width - (wpad / 2)) / scale;
  303. float y1 = (faceobjects[i].rect.y + faceobjects[i].rect.height - (hpad / 2)) / scale;
  304. x0 = std::max(std::min(x0, (float)width - 1), 0.f);
  305. y0 = std::max(std::min(y0, (float)height - 1), 0.f);
  306. x1 = std::max(std::min(x1, (float)width - 1), 0.f);
  307. y1 = std::max(std::min(y1, (float)height - 1), 0.f);
  308. faceobjects[i].rect.x = x0;
  309. faceobjects[i].rect.y = y0;
  310. faceobjects[i].rect.width = x1 - x0;
  311. faceobjects[i].rect.height = y1 - y0;
  312. }
  313. return 0;
  314. }
  315. static void draw_faceobjects(const cv::Mat& bgr, const std::vector<FaceObject>& faceobjects)
  316. {
  317. cv::Mat image = bgr.clone();
  318. for (size_t i = 0; i < faceobjects.size(); i++)
  319. {
  320. const FaceObject& obj = faceobjects[i];
  321. fprintf(stderr, "%.5f at %.2f %.2f %.2f x %.2f\n", obj.prob,
  322. obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
  323. cv::rectangle(image, obj.rect, cv::Scalar(0, 255, 0));
  324. char text[256];
  325. sprintf(text, "%.1f%%", obj.prob * 100);
  326. int baseLine = 0;
  327. cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
  328. int x = obj.rect.x;
  329. int y = obj.rect.y - label_size.height - baseLine;
  330. if (y < 0)
  331. y = 0;
  332. if (x + label_size.width > image.cols)
  333. x = image.cols - label_size.width;
  334. cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
  335. cv::Scalar(255, 255, 255), -1);
  336. cv::putText(image, text, cv::Point(x, y + label_size.height),
  337. cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
  338. }
  339. cv::imshow("image", image);
  340. cv::waitKey(0);
  341. }
  342. int main(int argc, char** argv)
  343. {
  344. if (argc != 2)
  345. {
  346. fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
  347. return -1;
  348. }
  349. const char* imagepath = argv[1];
  350. cv::Mat m = cv::imread(imagepath, 1);
  351. if (m.empty())
  352. {
  353. fprintf(stderr, "cv::imread %s failed\n", imagepath);
  354. return -1;
  355. }
  356. std::vector<FaceObject> faceobjects;
  357. detect_scrfd(m, faceobjects);
  358. draw_faceobjects(m, faceobjects);
  359. return 0;
  360. }