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.

rfcn.cpp 9.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. // Copyright 2018 Tencent
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. #include "net.h"
  4. #include <math.h>
  5. #if defined(USE_NCNN_SIMPLEOCV)
  6. #include "simpleocv.h"
  7. #else
  8. #include <opencv2/core/core.hpp>
  9. #include <opencv2/highgui/highgui.hpp>
  10. #include <opencv2/imgproc/imgproc.hpp>
  11. #endif
  12. #include <stdio.h>
  13. struct Object
  14. {
  15. cv::Rect_<float> rect;
  16. int label;
  17. float prob;
  18. };
  19. static inline float intersection_area(const Object& a, const Object& b)
  20. {
  21. cv::Rect_<float> inter = a.rect & b.rect;
  22. return inter.area();
  23. }
  24. static void qsort_descent_inplace(std::vector<Object>& objects, int left, int right)
  25. {
  26. int i = left;
  27. int j = right;
  28. float p = objects[(left + right) / 2].prob;
  29. while (i <= j)
  30. {
  31. while (objects[i].prob > p)
  32. i++;
  33. while (objects[j].prob < p)
  34. j--;
  35. if (i <= j)
  36. {
  37. // swap
  38. std::swap(objects[i], objects[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(objects, left, j);
  48. }
  49. #pragma omp section
  50. {
  51. if (i < right) qsort_descent_inplace(objects, i, right);
  52. }
  53. }
  54. }
  55. static void qsort_descent_inplace(std::vector<Object>& objects)
  56. {
  57. if (objects.empty())
  58. return;
  59. qsort_descent_inplace(objects, 0, objects.size() - 1);
  60. }
  61. static void nms_sorted_bboxes(const std::vector<Object>& faceobjects, std::vector<int>& picked, float nms_threshold, bool agnostic = false)
  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 Object& a = faceobjects[i];
  73. int keep = 1;
  74. for (int j = 0; j < (int)picked.size(); j++)
  75. {
  76. const Object& b = faceobjects[picked[j]];
  77. if (!agnostic && a.label != b.label)
  78. continue;
  79. // intersection over union
  80. float inter_area = intersection_area(a, b);
  81. float union_area = areas[i] + areas[picked[j]] - inter_area;
  82. // float IoU = inter_area / union_area
  83. if (inter_area / union_area > nms_threshold)
  84. keep = 0;
  85. }
  86. if (keep)
  87. picked.push_back(i);
  88. }
  89. }
  90. static int detect_rfcn(const cv::Mat& bgr, std::vector<Object>& objects)
  91. {
  92. ncnn::Net rfcn;
  93. rfcn.opt.use_vulkan_compute = true;
  94. // original pretrained model from https://github.com/YuwenXiong/py-R-FCN
  95. // https://github.com/YuwenXiong/py-R-FCN/blob/master/models/pascal_voc/ResNet-50/rfcn_end2end/test_agnostic.prototxt
  96. // https://1drv.ms/u/s!AoN7vygOjLIQqUWHpY67oaC7mopf
  97. // resnet50_rfcn_final.caffemodel
  98. if (rfcn.load_param("rfcn_end2end.param"))
  99. exit(-1);
  100. if (rfcn.load_model("rfcn_end2end.bin"))
  101. exit(-1);
  102. const int target_size = 224;
  103. const int max_per_image = 100;
  104. const float confidence_thresh = 0.6f; // CONF_THRESH
  105. const float nms_threshold = 0.3f; // NMS_THRESH
  106. // scale to target detect size
  107. int w = bgr.cols;
  108. int h = bgr.rows;
  109. float scale = 1.f;
  110. if (w < h)
  111. {
  112. scale = (float)target_size / w;
  113. w = target_size;
  114. h = h * scale;
  115. }
  116. else
  117. {
  118. scale = (float)target_size / h;
  119. h = target_size;
  120. w = w * scale;
  121. }
  122. ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR, bgr.cols, bgr.rows, w, h);
  123. const float mean_vals[3] = {102.9801f, 115.9465f, 122.7717f};
  124. in.substract_mean_normalize(mean_vals, 0);
  125. ncnn::Mat im_info(3);
  126. im_info[0] = h;
  127. im_info[1] = w;
  128. im_info[2] = scale;
  129. // step1, extract feature and all rois
  130. ncnn::Extractor ex1 = rfcn.create_extractor();
  131. ex1.input("data", in);
  132. ex1.input("im_info", im_info);
  133. ncnn::Mat rfcn_cls;
  134. ncnn::Mat rfcn_bbox;
  135. ncnn::Mat rois; // all rois
  136. ex1.extract("rfcn_cls", rfcn_cls);
  137. ex1.extract("rfcn_bbox", rfcn_bbox);
  138. ex1.extract("rois", rois);
  139. // step2, extract bbox and score for each roi
  140. std::vector<std::vector<Object> > class_candidates;
  141. for (int i = 0; i < rois.c; i++)
  142. {
  143. ncnn::Extractor ex2 = rfcn.create_extractor();
  144. ncnn::Mat roi = rois.channel(i); // get single roi
  145. ex2.input("rfcn_cls", rfcn_cls);
  146. ex2.input("rfcn_bbox", rfcn_bbox);
  147. ex2.input("rois", roi);
  148. ncnn::Mat bbox_pred;
  149. ncnn::Mat cls_prob;
  150. ex2.extract("bbox_pred", bbox_pred);
  151. ex2.extract("cls_prob", cls_prob);
  152. int num_class = cls_prob.w;
  153. class_candidates.resize(num_class);
  154. // find class id with highest score
  155. int label = 0;
  156. float score = 0.f;
  157. for (int i = 0; i < num_class; i++)
  158. {
  159. float class_score = cls_prob[i];
  160. if (class_score > score)
  161. {
  162. label = i;
  163. score = class_score;
  164. }
  165. }
  166. // ignore background or low score
  167. if (label == 0 || score <= confidence_thresh)
  168. continue;
  169. // fprintf(stderr, "%d = %f\n", label, score);
  170. // unscale to image size
  171. float x1 = roi[0] / scale;
  172. float y1 = roi[1] / scale;
  173. float x2 = roi[2] / scale;
  174. float y2 = roi[3] / scale;
  175. float pb_w = x2 - x1 + 1;
  176. float pb_h = y2 - y1 + 1;
  177. // apply bbox regression
  178. float dx = bbox_pred[4];
  179. float dy = bbox_pred[4 + 1];
  180. float dw = bbox_pred[4 + 2];
  181. float dh = bbox_pred[4 + 3];
  182. float cx = x1 + pb_w * 0.5f;
  183. float cy = y1 + pb_h * 0.5f;
  184. float obj_cx = cx + pb_w * dx;
  185. float obj_cy = cy + pb_h * dy;
  186. float obj_w = pb_w * exp(dw);
  187. float obj_h = pb_h * exp(dh);
  188. float obj_x1 = obj_cx - obj_w * 0.5f;
  189. float obj_y1 = obj_cy - obj_h * 0.5f;
  190. float obj_x2 = obj_cx + obj_w * 0.5f;
  191. float obj_y2 = obj_cy + obj_h * 0.5f;
  192. // clip
  193. obj_x1 = std::max(std::min(obj_x1, (float)(bgr.cols - 1)), 0.f);
  194. obj_y1 = std::max(std::min(obj_y1, (float)(bgr.rows - 1)), 0.f);
  195. obj_x2 = std::max(std::min(obj_x2, (float)(bgr.cols - 1)), 0.f);
  196. obj_y2 = std::max(std::min(obj_y2, (float)(bgr.rows - 1)), 0.f);
  197. // append object
  198. Object obj;
  199. obj.rect = cv::Rect_<float>(obj_x1, obj_y1, obj_x2 - obj_x1 + 1, obj_y2 - obj_y1 + 1);
  200. obj.label = label;
  201. obj.prob = score;
  202. class_candidates[label].push_back(obj);
  203. }
  204. // post process
  205. objects.clear();
  206. for (int i = 0; i < (int)class_candidates.size(); i++)
  207. {
  208. std::vector<Object>& candidates = class_candidates[i];
  209. qsort_descent_inplace(candidates);
  210. std::vector<int> picked;
  211. nms_sorted_bboxes(candidates, picked, nms_threshold);
  212. for (int j = 0; j < (int)picked.size(); j++)
  213. {
  214. int z = picked[j];
  215. objects.push_back(candidates[z]);
  216. }
  217. }
  218. qsort_descent_inplace(objects);
  219. if (max_per_image > 0 && max_per_image < objects.size())
  220. {
  221. objects.resize(max_per_image);
  222. }
  223. return 0;
  224. }
  225. static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
  226. {
  227. static const char* class_names[] = {"background",
  228. "aeroplane", "bicycle", "bird", "boat",
  229. "bottle", "bus", "car", "cat", "chair",
  230. "cow", "diningtable", "dog", "horse",
  231. "motorbike", "person", "pottedplant",
  232. "sheep", "sofa", "train", "tvmonitor"
  233. };
  234. cv::Mat image = bgr.clone();
  235. for (size_t i = 0; i < objects.size(); i++)
  236. {
  237. const Object& obj = objects[i];
  238. fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob,
  239. obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
  240. cv::rectangle(image, obj.rect, cv::Scalar(255, 0, 0));
  241. char text[256];
  242. sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100);
  243. int baseLine = 0;
  244. cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
  245. int x = obj.rect.x;
  246. int y = obj.rect.y - label_size.height - baseLine;
  247. if (y < 0)
  248. y = 0;
  249. if (x + label_size.width > image.cols)
  250. x = image.cols - label_size.width;
  251. cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
  252. cv::Scalar(255, 255, 255), -1);
  253. cv::putText(image, text, cv::Point(x, y + label_size.height),
  254. cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
  255. }
  256. cv::imshow("image", image);
  257. cv::waitKey(0);
  258. }
  259. int main(int argc, char** argv)
  260. {
  261. if (argc != 2)
  262. {
  263. fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
  264. return -1;
  265. }
  266. const char* imagepath = argv[1];
  267. cv::Mat m = cv::imread(imagepath, 1);
  268. if (m.empty())
  269. {
  270. fprintf(stderr, "cv::imread %s failed\n", imagepath);
  271. return -1;
  272. }
  273. std::vector<Object> objects;
  274. detect_rfcn(m, objects);
  275. draw_objects(m, objects);
  276. return 0;
  277. }