Elffuss BraidHub

kikocis/ncnn public

master · 9.3 KiBRawPermalink
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 "yolodetectionoutput.h"
16
17#include "layer_type.h"
18
19namespace ncnn {
20
21YoloDetectionOutput::YoloDetectionOutput()
22{
23 one_blob_only = false;
24 support_inplace = true;
25}
26
27int YoloDetectionOutput::load_param(const ParamDict& pd)
28{
29 num_class = pd.get(0, 20);
30 num_box = pd.get(1, 5);
31 confidence_threshold = pd.get(2, 0.01f);
32 nms_threshold = pd.get(3, 0.45f);
33 biases = pd.get(4, Mat());
34
35 return 0;
36}
37
38int YoloDetectionOutput::create_pipeline(const Option& opt)
39{
40 {
41 softmax = ncnn::create_layer_cpu(ncnn::LayerType::Softmax);
42
43 ncnn::ParamDict pd;
44 pd.set(0, 0); // axis
45
46 softmax->load_param(pd);
47
48 softmax->create_pipeline(opt);
49 }
50
51 return 0;
52}
53
54int YoloDetectionOutput::destroy_pipeline(const Option& opt)
55{
56 if (softmax)
57 {
58 softmax->destroy_pipeline(opt);
59 delete softmax;
60 softmax = 0;
61 }
62
63 return 0;
64}
65
66struct BBoxRect
67{
68 float xmin;
69 float ymin;
70 float xmax;
71 float ymax;
72 int label;
73};
74
75static inline float intersection_area(const BBoxRect& a, const BBoxRect& b)
76{
77 if (a.xmin > b.xmax || a.xmax < b.xmin || a.ymin > b.ymax || a.ymax < b.ymin)
78 {
79 // no intersection
80 return 0.f;
81 }
82
83 float inter_width = std::min(a.xmax, b.xmax) - std::max(a.xmin, b.xmin);
84 float inter_height = std::min(a.ymax, b.ymax) - std::max(a.ymin, b.ymin);
85
86 return inter_width * inter_height;
87}
88
89template<typename T>
90static void qsort_descent_inplace(std::vector<T>& datas, std::vector<float>& scores, int left, int right)
91{
92 int i = left;
93 int j = right;
94 float p = scores[(left + right) / 2];
95
96 while (i <= j)
97 {
98 while (scores[i] > p)
99 i++;
100
101 while (scores[j] < p)
102 j--;
103
104 if (i <= j)
105 {
106 // swap
107 std::swap(datas[i], datas[j]);
108 std::swap(scores[i], scores[j]);
109
110 i++;
111 j--;
112 }
113 }
114
115 if (left < j)
116 qsort_descent_inplace(datas, scores, left, j);
117
118 if (i < right)
119 qsort_descent_inplace(datas, scores, i, right);
120}
121
122template<typename T>
123static void qsort_descent_inplace(std::vector<T>& datas, std::vector<float>& scores)
124{
125 if (datas.empty() || scores.empty())
126 return;
127
128 qsort_descent_inplace(datas, scores, 0, static_cast<int>(scores.size() - 1));
129}
130
131static void nms_sorted_bboxes(const std::vector<BBoxRect>& bboxes, std::vector<size_t>& picked, float nms_threshold)
132{
133 picked.clear();
134
135 const size_t n = bboxes.size();
136
137 std::vector<float> areas(n);
138 for (size_t i = 0; i < n; i++)
139 {
140 const BBoxRect& r = bboxes[i];
141
142 float width = r.xmax - r.xmin;
143 float height = r.ymax - r.ymin;
144
145 areas[i] = width * height;
146 }
147
148 for (size_t i = 0; i < n; i++)
149 {
150 const BBoxRect& a = bboxes[i];
151
152 int keep = 1;
153 for (int j = 0; j < (int)picked.size(); j++)
154 {
155 const BBoxRect& b = bboxes[picked[j]];
156
157 // intersection over union
158 float inter_area = intersection_area(a, b);
159 float union_area = areas[i] + areas[picked[j]] - inter_area;
160 // float IoU = inter_area / union_area
161 if (inter_area / union_area > nms_threshold)
162 keep = 0;
163 }
164
165 if (keep)
166 picked.push_back(i);
167 }
168}
169
170static inline float sigmoid(float x)
171{
172 return 1.f / (1.f + expf(-x));
173}
174
175int YoloDetectionOutput::forward_inplace(std::vector<Mat>& bottom_top_blobs, const Option& opt) const
176{
177 // gather all box
178 std::vector<BBoxRect> all_bbox_rects;
179 std::vector<float> all_bbox_scores;
180
181 for (size_t b = 0; b < bottom_top_blobs.size(); b++)
182 {
183 Mat& bottom_top_blob = bottom_top_blobs[b];
184
185 int w = bottom_top_blob.w;
186 int h = bottom_top_blob.h;
187 int channels = bottom_top_blob.c;
188
189 const int channels_per_box = channels / num_box;
190
191 // anchor coord + box score + num_class
192 if (channels_per_box != 4 + 1 + num_class)
193 return -1;
194
195 std::vector<std::vector<BBoxRect> > all_box_bbox_rects;
196 std::vector<std::vector<float> > all_box_bbox_scores;
197 all_box_bbox_rects.resize(num_box);
198 all_box_bbox_scores.resize(num_box);
199
200 std::vector<int> softmax_rets;
201 softmax_rets.resize(num_box);
202
203 #pragma omp parallel for num_threads(opt.num_threads)
204 for (int pp = 0; pp < num_box; pp++)
205 {
206 int p = pp * channels_per_box;
207
208 const float bias_w = biases[pp * 2];
209 const float bias_h = biases[pp * 2 + 1];
210
211 const float* xptr = bottom_top_blob.channel(p);
212 const float* yptr = bottom_top_blob.channel(p + 1);
213 const float* wptr = bottom_top_blob.channel(p + 2);
214 const float* hptr = bottom_top_blob.channel(p + 3);
215
216 const float* box_score_ptr = bottom_top_blob.channel(p + 4);
217
218 // softmax class scores
219 Mat scores = bottom_top_blob.channel_range(p + 5, num_class);
220 softmax_rets[pp] = softmax->forward_inplace(scores, opt);
221
222 for (int i = 0; i < h; i++)
223 {
224 for (int j = 0; j < w; j++)
225 {
226 // region box
227 float bbox_cx = (j + sigmoid(xptr[0])) / w;
228 float bbox_cy = (i + sigmoid(yptr[0])) / h;
229 float bbox_w = expf(wptr[0]) * bias_w / w;
230 float bbox_h = expf(hptr[0]) * bias_h / h;
231
232 float bbox_xmin = bbox_cx - bbox_w * 0.5f;
233 float bbox_ymin = bbox_cy - bbox_h * 0.5f;
234 float bbox_xmax = bbox_cx + bbox_w * 0.5f;
235 float bbox_ymax = bbox_cy + bbox_h * 0.5f;
236
237 // box score
238 float box_score = sigmoid(box_score_ptr[0]);
239
240 // find class index with max class score
241 int class_index = 0;
242 float class_score = 0.f;
243 for (int q = 0; q < num_class; q++)
244 {
245 float score = scores.channel(q).row(i)[j];
246 if (score > class_score)
247 {
248 class_index = q;
249 class_score = score;
250 }
251 }
252
253 // NCNN_LOGE("%d %f %f", class_index, box_score, class_score);
254
255 float confidence = box_score * class_score;
256 if (confidence >= confidence_threshold)
257 {
258 BBoxRect c = {bbox_xmin, bbox_ymin, bbox_xmax, bbox_ymax, class_index};
259 all_box_bbox_rects[pp].push_back(c);
260 all_box_bbox_scores[pp].push_back(confidence);
261 }
262
263 xptr++;
264 yptr++;
265 wptr++;
266 hptr++;
267
268 box_score_ptr++;
269 }
270 }
271 }
272
273 for (int i = 0; i < num_box; i++)
274 {
275 if (softmax_rets[i] != 0)
276 return softmax_rets[i];
277
278 const std::vector<BBoxRect>& box_bbox_rects = all_box_bbox_rects[i];
279 const std::vector<float>& box_bbox_scores = all_box_bbox_scores[i];
280
281 all_bbox_rects.insert(all_bbox_rects.end(), box_bbox_rects.begin(), box_bbox_rects.end());
282 all_bbox_scores.insert(all_bbox_scores.end(), box_bbox_scores.begin(), box_bbox_scores.end());
283 }
284 }
285
286 // global sort inplace
287 qsort_descent_inplace(all_bbox_rects, all_bbox_scores);
288
289 // apply nms
290 std::vector<size_t> picked;
291 nms_sorted_bboxes(all_bbox_rects, picked, nms_threshold);
292
293 // select
294 std::vector<BBoxRect> bbox_rects;
295 std::vector<float> bbox_scores;
296
297 for (size_t i = 0; i < picked.size(); i++)
298 {
299 size_t z = picked[i];
300 bbox_rects.push_back(all_bbox_rects[z]);
301 bbox_scores.push_back(all_bbox_scores[z]);
302 }
303
304 // fill result
305 int num_detected = static_cast<int>(bbox_rects.size());
306 if (num_detected == 0)
307 return 0;
308
309 Mat& top_blob = bottom_top_blobs[0];
310 top_blob.create(6, num_detected, 4u, opt.blob_allocator);
311 if (top_blob.empty())
312 return -100;
313
314 for (int i = 0; i < num_detected; i++)
315 {
316 const BBoxRect& r = bbox_rects[i];
317 float score = bbox_scores[i];
318 float* outptr = top_blob.row(i);
319
320 outptr[0] = r.label + 1.0f; // +1 for prepend background class
321 outptr[1] = score;
322 outptr[2] = r.xmin;
323 outptr[3] = r.ymin;
324 outptr[4] = r.xmax;
325 outptr[5] = r.ymax;
326 }
327
328 return 0;
329}
330
331} // namespace ncnn