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
15 #include "net.h"
16
17 #include <math.h>
18 #if defined(USE_NCNN_SIMPLEOCV)
19 #include "simpleocv.h"
20 #else
21 #include <opencv2/core/core.hpp>
22 #include <opencv2/highgui/highgui.hpp>
23 #include <opencv2/imgproc/imgproc.hpp>
24 #endif
25 #include <stdio.h>
26
27 struct Object
28 {
29 cv::Rect_<float> rect;
30 int label;
31 float prob;
32 };
33
intersection_area(const Object & a,const Object & b)34 static inline float intersection_area(const Object& a, const Object& b)
35 {
36 cv::Rect_<float> inter = a.rect & b.rect;
37 return inter.area();
38 }
39
qsort_descent_inplace(std::vector<Object> & objects,int left,int right)40 static void qsort_descent_inplace(std::vector<Object>& objects, int left, int right)
41 {
42 int i = left;
43 int j = right;
44 float p = objects[(left + right) / 2].prob;
45
46 while (i <= j)
47 {
48 while (objects[i].prob > p)
49 i++;
50
51 while (objects[j].prob < p)
52 j--;
53
54 if (i <= j)
55 {
56 // swap
57 std::swap(objects[i], objects[j]);
58
59 i++;
60 j--;
61 }
62 }
63
64 #pragma omp parallel sections
65 {
66 #pragma omp section
67 {
68 if (left < j) qsort_descent_inplace(objects, left, j);
69 }
70 #pragma omp section
71 {
72 if (i < right) qsort_descent_inplace(objects, i, right);
73 }
74 }
75 }
76
qsort_descent_inplace(std::vector<Object> & objects)77 static void qsort_descent_inplace(std::vector<Object>& objects)
78 {
79 if (objects.empty())
80 return;
81
82 qsort_descent_inplace(objects, 0, objects.size() - 1);
83 }
84
nms_sorted_bboxes(const std::vector<Object> & objects,std::vector<int> & picked,float nms_threshold)85 static void nms_sorted_bboxes(const std::vector<Object>& objects, std::vector<int>& picked, float nms_threshold)
86 {
87 picked.clear();
88
89 const int n = objects.size();
90
91 std::vector<float> areas(n);
92 for (int i = 0; i < n; i++)
93 {
94 areas[i] = objects[i].rect.area();
95 }
96
97 for (int i = 0; i < n; i++)
98 {
99 const Object& a = objects[i];
100
101 int keep = 1;
102 for (int j = 0; j < (int)picked.size(); j++)
103 {
104 const Object& b = objects[picked[j]];
105
106 // intersection over union
107 float inter_area = intersection_area(a, b);
108 float union_area = areas[i] + areas[picked[j]] - inter_area;
109 // float IoU = inter_area / union_area
110 if (inter_area / union_area > nms_threshold)
111 keep = 0;
112 }
113
114 if (keep)
115 picked.push_back(i);
116 }
117 }
118
detect_rfcn(const cv::Mat & bgr,std::vector<Object> & objects)119 static int detect_rfcn(const cv::Mat& bgr, std::vector<Object>& objects)
120 {
121 ncnn::Net rfcn;
122
123 rfcn.opt.use_vulkan_compute = true;
124
125 // original pretrained model from https://github.com/YuwenXiong/py-R-FCN
126 // https://github.com/YuwenXiong/py-R-FCN/blob/master/models/pascal_voc/ResNet-50/rfcn_end2end/test_agnostic.prototxt
127 // https://1drv.ms/u/s!AoN7vygOjLIQqUWHpY67oaC7mopf
128 // resnet50_rfcn_final.caffemodel
129 rfcn.load_param("rfcn_end2end.param");
130 rfcn.load_model("rfcn_end2end.bin");
131
132 const int target_size = 224;
133
134 const int max_per_image = 100;
135 const float confidence_thresh = 0.6f; // CONF_THRESH
136
137 const float nms_threshold = 0.3f; // NMS_THRESH
138
139 // scale to target detect size
140 int w = bgr.cols;
141 int h = bgr.rows;
142 float scale = 1.f;
143 if (w < h)
144 {
145 scale = (float)target_size / w;
146 w = target_size;
147 h = h * scale;
148 }
149 else
150 {
151 scale = (float)target_size / h;
152 h = target_size;
153 w = w * scale;
154 }
155
156 ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR, bgr.cols, bgr.rows, w, h);
157
158 const float mean_vals[3] = {102.9801f, 115.9465f, 122.7717f};
159 in.substract_mean_normalize(mean_vals, 0);
160
161 ncnn::Mat im_info(3);
162 im_info[0] = h;
163 im_info[1] = w;
164 im_info[2] = scale;
165
166 // step1, extract feature and all rois
167 ncnn::Extractor ex1 = rfcn.create_extractor();
168
169 ex1.input("data", in);
170 ex1.input("im_info", im_info);
171
172 ncnn::Mat rfcn_cls;
173 ncnn::Mat rfcn_bbox;
174 ncnn::Mat rois; // all rois
175 ex1.extract("rfcn_cls", rfcn_cls);
176 ex1.extract("rfcn_bbox", rfcn_bbox);
177 ex1.extract("rois", rois);
178
179 // step2, extract bbox and score for each roi
180 std::vector<std::vector<Object> > class_candidates;
181 for (int i = 0; i < rois.c; i++)
182 {
183 ncnn::Extractor ex2 = rfcn.create_extractor();
184
185 ncnn::Mat roi = rois.channel(i); // get single roi
186 ex2.input("rfcn_cls", rfcn_cls);
187 ex2.input("rfcn_bbox", rfcn_bbox);
188 ex2.input("rois", roi);
189
190 ncnn::Mat bbox_pred;
191 ncnn::Mat cls_prob;
192 ex2.extract("bbox_pred", bbox_pred);
193 ex2.extract("cls_prob", cls_prob);
194
195 int num_class = cls_prob.w;
196 class_candidates.resize(num_class);
197
198 // find class id with highest score
199 int label = 0;
200 float score = 0.f;
201 for (int i = 0; i < num_class; i++)
202 {
203 float class_score = cls_prob[i];
204 if (class_score > score)
205 {
206 label = i;
207 score = class_score;
208 }
209 }
210
211 // ignore background or low score
212 if (label == 0 || score <= confidence_thresh)
213 continue;
214
215 // fprintf(stderr, "%d = %f\n", label, score);
216
217 // unscale to image size
218 float x1 = roi[0] / scale;
219 float y1 = roi[1] / scale;
220 float x2 = roi[2] / scale;
221 float y2 = roi[3] / scale;
222
223 float pb_w = x2 - x1 + 1;
224 float pb_h = y2 - y1 + 1;
225
226 // apply bbox regression
227 float dx = bbox_pred[4];
228 float dy = bbox_pred[4 + 1];
229 float dw = bbox_pred[4 + 2];
230 float dh = bbox_pred[4 + 3];
231
232 float cx = x1 + pb_w * 0.5f;
233 float cy = y1 + pb_h * 0.5f;
234
235 float obj_cx = cx + pb_w * dx;
236 float obj_cy = cy + pb_h * dy;
237
238 float obj_w = pb_w * exp(dw);
239 float obj_h = pb_h * exp(dh);
240
241 float obj_x1 = obj_cx - obj_w * 0.5f;
242 float obj_y1 = obj_cy - obj_h * 0.5f;
243 float obj_x2 = obj_cx + obj_w * 0.5f;
244 float obj_y2 = obj_cy + obj_h * 0.5f;
245
246 // clip
247 obj_x1 = std::max(std::min(obj_x1, (float)(bgr.cols - 1)), 0.f);
248 obj_y1 = std::max(std::min(obj_y1, (float)(bgr.rows - 1)), 0.f);
249 obj_x2 = std::max(std::min(obj_x2, (float)(bgr.cols - 1)), 0.f);
250 obj_y2 = std::max(std::min(obj_y2, (float)(bgr.rows - 1)), 0.f);
251
252 // append object
253 Object obj;
254 obj.rect = cv::Rect_<float>(obj_x1, obj_y1, obj_x2 - obj_x1 + 1, obj_y2 - obj_y1 + 1);
255 obj.label = label;
256 obj.prob = score;
257
258 class_candidates[label].push_back(obj);
259 }
260
261 // post process
262 objects.clear();
263 for (int i = 0; i < (int)class_candidates.size(); i++)
264 {
265 std::vector<Object>& candidates = class_candidates[i];
266
267 qsort_descent_inplace(candidates);
268
269 std::vector<int> picked;
270 nms_sorted_bboxes(candidates, picked, nms_threshold);
271
272 for (int j = 0; j < (int)picked.size(); j++)
273 {
274 int z = picked[j];
275 objects.push_back(candidates[z]);
276 }
277 }
278
279 qsort_descent_inplace(objects);
280
281 if (max_per_image > 0 && max_per_image < objects.size())
282 {
283 objects.resize(max_per_image);
284 }
285
286 return 0;
287 }
288
draw_objects(const cv::Mat & bgr,const std::vector<Object> & objects)289 static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects)
290 {
291 static const char* class_names[] = {"background",
292 "aeroplane", "bicycle", "bird", "boat",
293 "bottle", "bus", "car", "cat", "chair",
294 "cow", "diningtable", "dog", "horse",
295 "motorbike", "person", "pottedplant",
296 "sheep", "sofa", "train", "tvmonitor"
297 };
298
299 cv::Mat image = bgr.clone();
300
301 for (size_t i = 0; i < objects.size(); i++)
302 {
303 const Object& obj = objects[i];
304
305 fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob,
306 obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
307
308 cv::rectangle(image, obj.rect, cv::Scalar(255, 0, 0));
309
310 char text[256];
311 sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100);
312
313 int baseLine = 0;
314 cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
315
316 int x = obj.rect.x;
317 int y = obj.rect.y - label_size.height - baseLine;
318 if (y < 0)
319 y = 0;
320 if (x + label_size.width > image.cols)
321 x = image.cols - label_size.width;
322
323 cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
324 cv::Scalar(255, 255, 255), -1);
325
326 cv::putText(image, text, cv::Point(x, y + label_size.height),
327 cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
328 }
329
330 cv::imshow("image", image);
331 cv::waitKey(0);
332 }
333
main(int argc,char ** argv)334 int main(int argc, char** argv)
335 {
336 if (argc != 2)
337 {
338 fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
339 return -1;
340 }
341
342 const char* imagepath = argv[1];
343
344 cv::Mat m = cv::imread(imagepath, 1);
345 if (m.empty())
346 {
347 fprintf(stderr, "cv::imread %s failed\n", imagepath);
348 return -1;
349 }
350
351 std::vector<Object> objects;
352 detect_rfcn(m, objects);
353
354 draw_objects(m, objects);
355
356 return 0;
357 }
358