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

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