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.6 kB

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