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.

retinaface.cpp 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. // Copyright 2019 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. cv::Point2f landmark[5];
  17. float prob;
  18. };
  19. static inline float intersection_area(const FaceObject& a, const FaceObject& b)
  20. {
  21. cv::Rect_<float> inter = a.rect & b.rect;
  22. return inter.area();
  23. }
  24. static void qsort_descent_inplace(std::vector<FaceObject>& faceobjects, int left, int right)
  25. {
  26. int i = left;
  27. int j = right;
  28. float p = faceobjects[(left + right) / 2].prob;
  29. while (i <= j)
  30. {
  31. while (faceobjects[i].prob > p)
  32. i++;
  33. while (faceobjects[j].prob < p)
  34. j--;
  35. if (i <= j)
  36. {
  37. // swap
  38. std::swap(faceobjects[i], faceobjects[j]);
  39. i++;
  40. j--;
  41. }
  42. }
  43. #pragma omp parallel sections
  44. {
  45. #pragma omp section
  46. {
  47. if (left < j) qsort_descent_inplace(faceobjects, left, j);
  48. }
  49. #pragma omp section
  50. {
  51. if (i < right) qsort_descent_inplace(faceobjects, i, right);
  52. }
  53. }
  54. }
  55. static void qsort_descent_inplace(std::vector<FaceObject>& faceobjects)
  56. {
  57. if (faceobjects.empty())
  58. return;
  59. qsort_descent_inplace(faceobjects, 0, faceobjects.size() - 1);
  60. }
  61. static void nms_sorted_bboxes(const std::vector<FaceObject>& faceobjects, std::vector<int>& picked, float nms_threshold)
  62. {
  63. picked.clear();
  64. const int n = faceobjects.size();
  65. std::vector<float> areas(n);
  66. for (int i = 0; i < n; i++)
  67. {
  68. areas[i] = faceobjects[i].rect.area();
  69. }
  70. for (int i = 0; i < n; i++)
  71. {
  72. const FaceObject& a = faceobjects[i];
  73. int keep = 1;
  74. for (int j = 0; j < (int)picked.size(); j++)
  75. {
  76. const FaceObject& b = faceobjects[picked[j]];
  77. // intersection over union
  78. float inter_area = intersection_area(a, b);
  79. float union_area = areas[i] + areas[picked[j]] - inter_area;
  80. // float IoU = inter_area / union_area
  81. if (inter_area / union_area > nms_threshold)
  82. keep = 0;
  83. }
  84. if (keep)
  85. picked.push_back(i);
  86. }
  87. }
  88. // copy from src/layer/proposal.cpp
  89. static ncnn::Mat generate_anchors(int base_size, const ncnn::Mat& ratios, const ncnn::Mat& scales)
  90. {
  91. int num_ratio = ratios.w;
  92. int num_scale = scales.w;
  93. ncnn::Mat anchors;
  94. anchors.create(4, num_ratio * num_scale);
  95. const float cx = base_size * 0.5f;
  96. const float cy = base_size * 0.5f;
  97. for (int i = 0; i < num_ratio; i++)
  98. {
  99. float ar = ratios[i];
  100. int r_w = round(base_size / sqrt(ar));
  101. int r_h = round(r_w * ar); //round(base_size * sqrt(ar));
  102. for (int j = 0; j < num_scale; j++)
  103. {
  104. float scale = scales[j];
  105. float rs_w = r_w * scale;
  106. float rs_h = r_h * scale;
  107. float* anchor = anchors.row(i * num_scale + j);
  108. anchor[0] = cx - rs_w * 0.5f;
  109. anchor[1] = cy - rs_h * 0.5f;
  110. anchor[2] = cx + rs_w * 0.5f;
  111. anchor[3] = cy + rs_h * 0.5f;
  112. }
  113. }
  114. return anchors;
  115. }
  116. static void generate_proposals(const ncnn::Mat& anchors, int feat_stride, const ncnn::Mat& score_blob, const ncnn::Mat& bbox_blob, const ncnn::Mat& landmark_blob, float prob_threshold, std::vector<FaceObject>& faceobjects)
  117. {
  118. int w = score_blob.w;
  119. int h = score_blob.h;
  120. // generate face proposal from bbox deltas and shifted anchors
  121. const int num_anchors = anchors.h;
  122. for (int q = 0; q < num_anchors; q++)
  123. {
  124. const float* anchor = anchors.row(q);
  125. const ncnn::Mat score = score_blob.channel(q + num_anchors);
  126. const ncnn::Mat bbox = bbox_blob.channel_range(q * 4, 4);
  127. const ncnn::Mat landmark = landmark_blob.channel_range(q * 10, 10);
  128. // shifted anchor
  129. float anchor_y = anchor[1];
  130. float anchor_w = anchor[2] - anchor[0];
  131. float anchor_h = anchor[3] - anchor[1];
  132. for (int i = 0; i < h; i++)
  133. {
  134. float anchor_x = anchor[0];
  135. for (int j = 0; j < w; j++)
  136. {
  137. int index = i * w + j;
  138. float prob = score[index];
  139. if (prob >= prob_threshold)
  140. {
  141. // apply center size
  142. float dx = bbox.channel(0)[index];
  143. float dy = bbox.channel(1)[index];
  144. float dw = bbox.channel(2)[index];
  145. float dh = bbox.channel(3)[index];
  146. float cx = anchor_x + anchor_w * 0.5f;
  147. float cy = anchor_y + anchor_h * 0.5f;
  148. float pb_cx = cx + anchor_w * dx;
  149. float pb_cy = cy + anchor_h * dy;
  150. float pb_w = anchor_w * exp(dw);
  151. float pb_h = anchor_h * exp(dh);
  152. float x0 = pb_cx - pb_w * 0.5f;
  153. float y0 = pb_cy - pb_h * 0.5f;
  154. float x1 = pb_cx + pb_w * 0.5f;
  155. float y1 = pb_cy + pb_h * 0.5f;
  156. FaceObject obj;
  157. obj.rect.x = x0;
  158. obj.rect.y = y0;
  159. obj.rect.width = x1 - x0 + 1;
  160. obj.rect.height = y1 - y0 + 1;
  161. obj.landmark[0].x = cx + (anchor_w + 1) * landmark.channel(0)[index];
  162. obj.landmark[0].y = cy + (anchor_h + 1) * landmark.channel(1)[index];
  163. obj.landmark[1].x = cx + (anchor_w + 1) * landmark.channel(2)[index];
  164. obj.landmark[1].y = cy + (anchor_h + 1) * landmark.channel(3)[index];
  165. obj.landmark[2].x = cx + (anchor_w + 1) * landmark.channel(4)[index];
  166. obj.landmark[2].y = cy + (anchor_h + 1) * landmark.channel(5)[index];
  167. obj.landmark[3].x = cx + (anchor_w + 1) * landmark.channel(6)[index];
  168. obj.landmark[3].y = cy + (anchor_h + 1) * landmark.channel(7)[index];
  169. obj.landmark[4].x = cx + (anchor_w + 1) * landmark.channel(8)[index];
  170. obj.landmark[4].y = cy + (anchor_h + 1) * landmark.channel(9)[index];
  171. obj.prob = prob;
  172. faceobjects.push_back(obj);
  173. }
  174. anchor_x += feat_stride;
  175. }
  176. anchor_y += feat_stride;
  177. }
  178. }
  179. }
  180. static int detect_retinaface(const cv::Mat& bgr, std::vector<FaceObject>& faceobjects)
  181. {
  182. ncnn::Net retinaface;
  183. retinaface.opt.use_vulkan_compute = true;
  184. // model is converted from
  185. // https://github.com/deepinsight/insightface/tree/master/RetinaFace#retinaface-pretrained-models
  186. // https://github.com/deepinsight/insightface/issues/669
  187. // the ncnn model https://github.com/nihui/ncnn-assets/tree/master/models
  188. // retinaface.load_param("retinaface-R50.param");
  189. // retinaface.load_model("retinaface-R50.bin");
  190. if (retinaface.load_param("mnet.25-opt.param"))
  191. exit(-1);
  192. if (retinaface.load_model("mnet.25-opt.bin"))
  193. exit(-1);
  194. const float prob_threshold = 0.8f;
  195. const float nms_threshold = 0.4f;
  196. int img_w = bgr.cols;
  197. int img_h = bgr.rows;
  198. ncnn::Mat in = ncnn::Mat::from_pixels(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, img_w, img_h);
  199. ncnn::Extractor ex = retinaface.create_extractor();
  200. ex.input("data", in);
  201. std::vector<FaceObject> faceproposals;
  202. // stride 32
  203. {
  204. ncnn::Mat score_blob, bbox_blob, landmark_blob;
  205. ex.extract("face_rpn_cls_prob_reshape_stride32", score_blob);
  206. ex.extract("face_rpn_bbox_pred_stride32", bbox_blob);
  207. ex.extract("face_rpn_landmark_pred_stride32", landmark_blob);
  208. const int base_size = 16;
  209. const int feat_stride = 32;
  210. ncnn::Mat ratios(1);
  211. ratios[0] = 1.f;
  212. ncnn::Mat scales(2);
  213. scales[0] = 32.f;
  214. scales[1] = 16.f;
  215. ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
  216. std::vector<FaceObject> faceobjects32;
  217. generate_proposals(anchors, feat_stride, score_blob, bbox_blob, landmark_blob, prob_threshold, faceobjects32);
  218. faceproposals.insert(faceproposals.end(), faceobjects32.begin(), faceobjects32.end());
  219. }
  220. // stride 16
  221. {
  222. ncnn::Mat score_blob, bbox_blob, landmark_blob;
  223. ex.extract("face_rpn_cls_prob_reshape_stride16", score_blob);
  224. ex.extract("face_rpn_bbox_pred_stride16", bbox_blob);
  225. ex.extract("face_rpn_landmark_pred_stride16", landmark_blob);
  226. const int base_size = 16;
  227. const int feat_stride = 16;
  228. ncnn::Mat ratios(1);
  229. ratios[0] = 1.f;
  230. ncnn::Mat scales(2);
  231. scales[0] = 8.f;
  232. scales[1] = 4.f;
  233. ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
  234. std::vector<FaceObject> faceobjects16;
  235. generate_proposals(anchors, feat_stride, score_blob, bbox_blob, landmark_blob, prob_threshold, faceobjects16);
  236. faceproposals.insert(faceproposals.end(), faceobjects16.begin(), faceobjects16.end());
  237. }
  238. // stride 8
  239. {
  240. ncnn::Mat score_blob, bbox_blob, landmark_blob;
  241. ex.extract("face_rpn_cls_prob_reshape_stride8", score_blob);
  242. ex.extract("face_rpn_bbox_pred_stride8", bbox_blob);
  243. ex.extract("face_rpn_landmark_pred_stride8", landmark_blob);
  244. const int base_size = 16;
  245. const int feat_stride = 8;
  246. ncnn::Mat ratios(1);
  247. ratios[0] = 1.f;
  248. ncnn::Mat scales(2);
  249. scales[0] = 2.f;
  250. scales[1] = 1.f;
  251. ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
  252. std::vector<FaceObject> faceobjects8;
  253. generate_proposals(anchors, feat_stride, score_blob, bbox_blob, landmark_blob, prob_threshold, faceobjects8);
  254. faceproposals.insert(faceproposals.end(), faceobjects8.begin(), faceobjects8.end());
  255. }
  256. // sort all proposals by score from highest to lowest
  257. qsort_descent_inplace(faceproposals);
  258. // apply nms with nms_threshold
  259. std::vector<int> picked;
  260. nms_sorted_bboxes(faceproposals, picked, nms_threshold);
  261. int face_count = picked.size();
  262. faceobjects.resize(face_count);
  263. for (int i = 0; i < face_count; i++)
  264. {
  265. faceobjects[i] = faceproposals[picked[i]];
  266. // clip to image size
  267. float x0 = faceobjects[i].rect.x;
  268. float y0 = faceobjects[i].rect.y;
  269. float x1 = x0 + faceobjects[i].rect.width;
  270. float y1 = y0 + faceobjects[i].rect.height;
  271. x0 = std::max(std::min(x0, (float)img_w - 1), 0.f);
  272. y0 = std::max(std::min(y0, (float)img_h - 1), 0.f);
  273. x1 = std::max(std::min(x1, (float)img_w - 1), 0.f);
  274. y1 = std::max(std::min(y1, (float)img_h - 1), 0.f);
  275. faceobjects[i].rect.x = x0;
  276. faceobjects[i].rect.y = y0;
  277. faceobjects[i].rect.width = x1 - x0;
  278. faceobjects[i].rect.height = y1 - y0;
  279. }
  280. return 0;
  281. }
  282. static void draw_faceobjects(const cv::Mat& bgr, const std::vector<FaceObject>& faceobjects)
  283. {
  284. cv::Mat image = bgr.clone();
  285. for (size_t i = 0; i < faceobjects.size(); i++)
  286. {
  287. const FaceObject& obj = faceobjects[i];
  288. fprintf(stderr, "%.5f at %.2f %.2f %.2f x %.2f\n", obj.prob,
  289. obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
  290. cv::rectangle(image, obj.rect, cv::Scalar(0, 255, 0));
  291. cv::circle(image, obj.landmark[0], 2, cv::Scalar(0, 255, 255), -1);
  292. cv::circle(image, obj.landmark[1], 2, cv::Scalar(0, 255, 255), -1);
  293. cv::circle(image, obj.landmark[2], 2, cv::Scalar(0, 255, 255), -1);
  294. cv::circle(image, obj.landmark[3], 2, cv::Scalar(0, 255, 255), -1);
  295. cv::circle(image, obj.landmark[4], 2, cv::Scalar(0, 255, 255), -1);
  296. char text[256];
  297. sprintf(text, "%.1f%%", 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<FaceObject> faceobjects;
  329. detect_retinaface(m, faceobjects);
  330. draw_faceobjects(m, faceobjects);
  331. return 0;
  332. }