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.

fasterrcnn.cpp 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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>& 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_fasterrcnn(const cv::Mat& bgr, std::vector<Object>& objects)
  100. {
  101. ncnn::Net fasterrcnn;
  102. fasterrcnn.opt.use_vulkan_compute = true;
  103. // original pretrained model from https://github.com/rbgirshick/py-faster-rcnn
  104. // py-faster-rcnn/models/pascal_voc/ZF/faster_rcnn_alt_opt/faster_rcnn_test.pt
  105. // https://dl.dropboxusercontent.com/s/o6ii098bu51d139/faster_rcnn_models.tgz?dl=0
  106. // ZF_faster_rcnn_final.caffemodel
  107. // the ncnn model https://github.com/nihui/ncnn-assets/tree/master/models
  108. fasterrcnn.load_param("ZF_faster_rcnn_final.param");
  109. fasterrcnn.load_model("ZF_faster_rcnn_final.bin");
  110. // hyper parameters taken from
  111. // py-faster-rcnn/lib/fast_rcnn/config.py
  112. // py-faster-rcnn/lib/fast_rcnn/test.py
  113. const int target_size = 600; // __C.TEST.SCALES
  114. const int max_per_image = 100;
  115. const float confidence_thresh = 0.05f;
  116. const float nms_threshold = 0.3f; // __C.TEST.NMS
  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 = fasterrcnn.create_extractor();
  142. ex1.input("data", in);
  143. ex1.input("im_info", im_info);
  144. ncnn::Mat conv5_relu5; // feature
  145. ncnn::Mat rois; // all rois
  146. ex1.extract("conv5_relu5", conv5_relu5);
  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 = fasterrcnn.create_extractor();
  153. ncnn::Mat roi = rois.channel(i); // get single roi
  154. ex2.input("conv5_relu5", conv5_relu5);
  155. ex2.input("rois", roi);
  156. ncnn::Mat bbox_pred;
  157. ncnn::Mat cls_prob;
  158. ex2.extract("bbox_pred", bbox_pred);
  159. ex2.extract("cls_prob", cls_prob);
  160. int num_class = cls_prob.w;
  161. class_candidates.resize(num_class);
  162. // find class id with highest score
  163. int label = 0;
  164. float score = 0.f;
  165. for (int i = 0; i < num_class; i++)
  166. {
  167. float class_score = cls_prob[i];
  168. if (class_score > score)
  169. {
  170. label = i;
  171. score = class_score;
  172. }
  173. }
  174. // ignore background or low score
  175. if (label == 0 || score <= confidence_thresh)
  176. continue;
  177. // fprintf(stderr, "%d = %f\n", label, score);
  178. // unscale to image size
  179. float x1 = roi[0] / scale;
  180. float y1 = roi[1] / scale;
  181. float x2 = roi[2] / scale;
  182. float y2 = roi[3] / scale;
  183. float pb_w = x2 - x1 + 1;
  184. float pb_h = y2 - y1 + 1;
  185. // apply bbox regression
  186. float dx = bbox_pred[label * 4];
  187. float dy = bbox_pred[label * 4 + 1];
  188. float dw = bbox_pred[label * 4 + 2];
  189. float dh = bbox_pred[label * 4 + 3];
  190. float cx = x1 + pb_w * 0.5f;
  191. float cy = y1 + pb_h * 0.5f;
  192. float obj_cx = cx + pb_w * dx;
  193. float obj_cy = cy + pb_h * dy;
  194. float obj_w = pb_w * exp(dw);
  195. float obj_h = pb_h * exp(dh);
  196. float obj_x1 = obj_cx - obj_w * 0.5f;
  197. float obj_y1 = obj_cy - obj_h * 0.5f;
  198. float obj_x2 = obj_cx + obj_w * 0.5f;
  199. float obj_y2 = obj_cy + obj_h * 0.5f;
  200. // clip
  201. obj_x1 = std::max(std::min(obj_x1, (float)(bgr.cols - 1)), 0.f);
  202. obj_y1 = std::max(std::min(obj_y1, (float)(bgr.rows - 1)), 0.f);
  203. obj_x2 = std::max(std::min(obj_x2, (float)(bgr.cols - 1)), 0.f);
  204. obj_y2 = std::max(std::min(obj_y2, (float)(bgr.rows - 1)), 0.f);
  205. // append object
  206. Object obj;
  207. obj.rect = cv::Rect_<float>(obj_x1, obj_y1, obj_x2 - obj_x1 + 1, obj_y2 - obj_y1 + 1);
  208. obj.label = label;
  209. obj.prob = score;
  210. class_candidates[label].push_back(obj);
  211. }
  212. // post process
  213. objects.clear();
  214. for (int i = 0; i < (int)class_candidates.size(); i++)
  215. {
  216. std::vector<Object>& candidates = class_candidates[i];
  217. qsort_descent_inplace(candidates);
  218. std::vector<int> picked;
  219. nms_sorted_bboxes(candidates, picked, nms_threshold);
  220. for (int j = 0; j < (int)picked.size(); j++)
  221. {
  222. int z = picked[j];
  223. objects.push_back(candidates[z]);
  224. }
  225. }
  226. qsort_descent_inplace(objects);
  227. if (max_per_image > 0 && max_per_image < objects.size())
  228. {
  229. objects.resize(max_per_image);
  230. }
  231. return 0;
  232. }
  233. static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
  234. {
  235. static const char* class_names[] = {"background",
  236. "aeroplane", "bicycle", "bird", "boat",
  237. "bottle", "bus", "car", "cat", "chair",
  238. "cow", "diningtable", "dog", "horse",
  239. "motorbike", "person", "pottedplant",
  240. "sheep", "sofa", "train", "tvmonitor"
  241. };
  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), cv::Size(label_size.width, label_size.height + baseLine)),
  260. cv::Scalar(255, 255, 255), -1);
  261. cv::putText(image, text, cv::Point(x, y + label_size.height),
  262. cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
  263. }
  264. cv::imshow("image", image);
  265. cv::waitKey(0);
  266. }
  267. int main(int argc, char** argv)
  268. {
  269. if (argc != 2)
  270. {
  271. fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
  272. return -1;
  273. }
  274. const char* imagepath = argv[1];
  275. cv::Mat m = cv::imread(imagepath, 1);
  276. if (m.empty())
  277. {
  278. fprintf(stderr, "cv::imread %s failed\n", imagepath);
  279. return -1;
  280. }
  281. std::vector<Object> objects;
  282. detect_fasterrcnn(m, objects);
  283. draw_objects(m, objects);
  284. return 0;
  285. }