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

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