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

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