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

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