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