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

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