ncnn

Форк
0
/
scrfd.cpp 
436 строк · 12.6 Кб
1
// Tencent is pleased to support the open source community by making ncnn available.
2
//
3
// Copyright (C) 2021 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
#if defined(USE_NCNN_SIMPLEOCV)
18
#include "simpleocv.h"
19
#else
20
#include <opencv2/core/core.hpp>
21
#include <opencv2/highgui/highgui.hpp>
22
#include <opencv2/imgproc/imgproc.hpp>
23
#endif
24
#include <stdio.h>
25
#include <vector>
26

27
struct FaceObject
28
{
29
    cv::Rect_<float> rect;
30
    float prob;
31
};
32

33
static inline float intersection_area(const FaceObject& a, const FaceObject& b)
34
{
35
    cv::Rect_<float> inter = a.rect & b.rect;
36
    return inter.area();
37
}
38

39
static void qsort_descent_inplace(std::vector<FaceObject>& faceobjects, int left, int right)
40
{
41
    int i = left;
42
    int j = right;
43
    float p = faceobjects[(left + right) / 2].prob;
44

45
    while (i <= j)
46
    {
47
        while (faceobjects[i].prob > p)
48
            i++;
49

50
        while (faceobjects[j].prob < p)
51
            j--;
52

53
        if (i <= j)
54
        {
55
            // swap
56
            std::swap(faceobjects[i], faceobjects[j]);
57

58
            i++;
59
            j--;
60
        }
61
    }
62

63
    #pragma omp parallel sections
64
    {
65
        #pragma omp section
66
        {
67
            if (left < j) qsort_descent_inplace(faceobjects, left, j);
68
        }
69
        #pragma omp section
70
        {
71
            if (i < right) qsort_descent_inplace(faceobjects, i, right);
72
        }
73
    }
74
}
75

76
static void qsort_descent_inplace(std::vector<FaceObject>& faceobjects)
77
{
78
    if (faceobjects.empty())
79
        return;
80

81
    qsort_descent_inplace(faceobjects, 0, faceobjects.size() - 1);
82
}
83

84
static void nms_sorted_bboxes(const std::vector<FaceObject>& faceobjects, std::vector<int>& picked, float nms_threshold)
85
{
86
    picked.clear();
87

88
    const int n = faceobjects.size();
89

90
    std::vector<float> areas(n);
91
    for (int i = 0; i < n; i++)
92
    {
93
        areas[i] = faceobjects[i].rect.area();
94
    }
95

96
    for (int i = 0; i < n; i++)
97
    {
98
        const FaceObject& a = faceobjects[i];
99

100
        int keep = 1;
101
        for (int j = 0; j < (int)picked.size(); j++)
102
        {
103
            const FaceObject& b = faceobjects[picked[j]];
104

105
            // intersection over union
106
            float inter_area = intersection_area(a, b);
107
            float union_area = areas[i] + areas[picked[j]] - inter_area;
108
            //             float IoU = inter_area / union_area
109
            if (inter_area / union_area > nms_threshold)
110
                keep = 0;
111
        }
112

113
        if (keep)
114
            picked.push_back(i);
115
    }
116
}
117

118
// insightface/detection/scrfd/mmdet/core/anchor/anchor_generator.py gen_single_level_base_anchors()
119
static ncnn::Mat generate_anchors(int base_size, const ncnn::Mat& ratios, const ncnn::Mat& scales)
120
{
121
    int num_ratio = ratios.w;
122
    int num_scale = scales.w;
123

124
    ncnn::Mat anchors;
125
    anchors.create(4, num_ratio * num_scale);
126

127
    const float cx = 0;
128
    const float cy = 0;
129

130
    for (int i = 0; i < num_ratio; i++)
131
    {
132
        float ar = ratios[i];
133

134
        int r_w = round(base_size / sqrt(ar));
135
        int r_h = round(r_w * ar); //round(base_size * sqrt(ar));
136

137
        for (int j = 0; j < num_scale; j++)
138
        {
139
            float scale = scales[j];
140

141
            float rs_w = r_w * scale;
142
            float rs_h = r_h * scale;
143

144
            float* anchor = anchors.row(i * num_scale + j);
145

146
            anchor[0] = cx - rs_w * 0.5f;
147
            anchor[1] = cy - rs_h * 0.5f;
148
            anchor[2] = cx + rs_w * 0.5f;
149
            anchor[3] = cy + rs_h * 0.5f;
150
        }
151
    }
152

153
    return anchors;
154
}
155

156
static void generate_proposals(const ncnn::Mat& anchors, int feat_stride, const ncnn::Mat& score_blob, const ncnn::Mat& bbox_blob, float prob_threshold, std::vector<FaceObject>& faceobjects)
157
{
158
    int w = score_blob.w;
159
    int h = score_blob.h;
160

161
    // generate face proposal from bbox deltas and shifted anchors
162
    const int num_anchors = anchors.h;
163

164
    for (int q = 0; q < num_anchors; q++)
165
    {
166
        const float* anchor = anchors.row(q);
167

168
        const ncnn::Mat score = score_blob.channel(q);
169
        const ncnn::Mat bbox = bbox_blob.channel_range(q * 4, 4);
170

171
        // shifted anchor
172
        float anchor_y = anchor[1];
173

174
        float anchor_w = anchor[2] - anchor[0];
175
        float anchor_h = anchor[3] - anchor[1];
176

177
        for (int i = 0; i < h; i++)
178
        {
179
            float anchor_x = anchor[0];
180

181
            for (int j = 0; j < w; j++)
182
            {
183
                int index = i * w + j;
184

185
                float prob = score[index];
186

187
                if (prob >= prob_threshold)
188
                {
189
                    // insightface/detection/scrfd/mmdet/models/dense_heads/scrfd_head.py _get_bboxes_single()
190
                    float dx = bbox.channel(0)[index] * feat_stride;
191
                    float dy = bbox.channel(1)[index] * feat_stride;
192
                    float dw = bbox.channel(2)[index] * feat_stride;
193
                    float dh = bbox.channel(3)[index] * feat_stride;
194

195
                    // insightface/detection/scrfd/mmdet/core/bbox/transforms.py distance2bbox()
196
                    float cx = anchor_x + anchor_w * 0.5f;
197
                    float cy = anchor_y + anchor_h * 0.5f;
198

199
                    float x0 = cx - dx;
200
                    float y0 = cy - dy;
201
                    float x1 = cx + dw;
202
                    float y1 = cy + dh;
203

204
                    FaceObject obj;
205
                    obj.rect.x = x0;
206
                    obj.rect.y = y0;
207
                    obj.rect.width = x1 - x0 + 1;
208
                    obj.rect.height = y1 - y0 + 1;
209
                    obj.prob = prob;
210

211
                    faceobjects.push_back(obj);
212
                }
213

214
                anchor_x += feat_stride;
215
            }
216

217
            anchor_y += feat_stride;
218
        }
219
    }
220
}
221

222
static int detect_scrfd(const cv::Mat& bgr, std::vector<FaceObject>& faceobjects)
223
{
224
    ncnn::Net scrfd;
225

226
    scrfd.opt.use_vulkan_compute = true;
227

228
    // model is converted from
229
    // https://github.com/deepinsight/insightface/tree/master/detection/scrfd
230
    // the ncnn model https://github.com/nihui/ncnn-assets/tree/master/models
231
    if (scrfd.load_param("scrfd_500m-opt2.param"))
232
        exit(-1);
233
    if (scrfd.load_model("scrfd_500m-opt2.bin"))
234
        exit(-1);
235

236
    int width = bgr.cols;
237
    int height = bgr.rows;
238

239
    // insightface/detection/scrfd/configs/scrfd/scrfd_500m.py
240
    const int target_size = 640;
241
    const float prob_threshold = 0.3f;
242
    const float nms_threshold = 0.45f;
243

244
    // pad to multiple of 32
245
    int w = width;
246
    int h = height;
247
    float scale = 1.f;
248
    if (w > h)
249
    {
250
        scale = (float)target_size / w;
251
        w = target_size;
252
        h = h * scale;
253
    }
254
    else
255
    {
256
        scale = (float)target_size / h;
257
        h = target_size;
258
        w = w * scale;
259
    }
260

261
    ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, width, height, w, h);
262

263
    // pad to target_size rectangle
264
    int wpad = (w + 31) / 32 * 32 - w;
265
    int hpad = (h + 31) / 32 * 32 - h;
266
    ncnn::Mat in_pad;
267
    ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 0.f);
268

269
    const float mean_vals[3] = {127.5f, 127.5f, 127.5f};
270
    const float norm_vals[3] = {1 / 128.f, 1 / 128.f, 1 / 128.f};
271
    in_pad.substract_mean_normalize(mean_vals, norm_vals);
272

273
    ncnn::Extractor ex = scrfd.create_extractor();
274

275
    ex.input("input.1", in_pad);
276

277
    std::vector<FaceObject> faceproposals;
278

279
    // stride 32
280
    {
281
        ncnn::Mat score_blob, bbox_blob;
282
        ex.extract("412", score_blob);
283
        ex.extract("415", bbox_blob);
284

285
        const int base_size = 16;
286
        const int feat_stride = 8;
287
        ncnn::Mat ratios(1);
288
        ratios[0] = 1.f;
289
        ncnn::Mat scales(2);
290
        scales[0] = 1.f;
291
        scales[1] = 2.f;
292
        ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
293

294
        std::vector<FaceObject> faceobjects32;
295
        generate_proposals(anchors, feat_stride, score_blob, bbox_blob, prob_threshold, faceobjects32);
296

297
        faceproposals.insert(faceproposals.end(), faceobjects32.begin(), faceobjects32.end());
298
    }
299

300
    // stride 16
301
    {
302
        ncnn::Mat score_blob, bbox_blob;
303
        ex.extract("474", score_blob);
304
        ex.extract("477", bbox_blob);
305

306
        const int base_size = 64;
307
        const int feat_stride = 16;
308
        ncnn::Mat ratios(1);
309
        ratios[0] = 1.f;
310
        ncnn::Mat scales(2);
311
        scales[0] = 1.f;
312
        scales[1] = 2.f;
313
        ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
314

315
        std::vector<FaceObject> faceobjects16;
316
        generate_proposals(anchors, feat_stride, score_blob, bbox_blob, prob_threshold, faceobjects16);
317

318
        faceproposals.insert(faceproposals.end(), faceobjects16.begin(), faceobjects16.end());
319
    }
320

321
    // stride 8
322
    {
323
        ncnn::Mat score_blob, bbox_blob;
324
        ex.extract("536", score_blob);
325
        ex.extract("539", bbox_blob);
326

327
        const int base_size = 256;
328
        const int feat_stride = 32;
329
        ncnn::Mat ratios(1);
330
        ratios[0] = 1.f;
331
        ncnn::Mat scales(2);
332
        scales[0] = 1.f;
333
        scales[1] = 2.f;
334
        ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
335

336
        std::vector<FaceObject> faceobjects8;
337
        generate_proposals(anchors, feat_stride, score_blob, bbox_blob, prob_threshold, faceobjects8);
338

339
        faceproposals.insert(faceproposals.end(), faceobjects8.begin(), faceobjects8.end());
340
    }
341

342
    // sort all proposals by score from highest to lowest
343
    qsort_descent_inplace(faceproposals);
344

345
    // apply nms with nms_threshold
346
    std::vector<int> picked;
347
    nms_sorted_bboxes(faceproposals, picked, nms_threshold);
348

349
    int face_count = picked.size();
350

351
    faceobjects.resize(face_count);
352
    for (int i = 0; i < face_count; i++)
353
    {
354
        faceobjects[i] = faceproposals[picked[i]];
355

356
        // adjust offset to original unpadded
357
        float x0 = (faceobjects[i].rect.x - (wpad / 2)) / scale;
358
        float y0 = (faceobjects[i].rect.y - (hpad / 2)) / scale;
359
        float x1 = (faceobjects[i].rect.x + faceobjects[i].rect.width - (wpad / 2)) / scale;
360
        float y1 = (faceobjects[i].rect.y + faceobjects[i].rect.height - (hpad / 2)) / scale;
361

362
        x0 = std::max(std::min(x0, (float)width - 1), 0.f);
363
        y0 = std::max(std::min(y0, (float)height - 1), 0.f);
364
        x1 = std::max(std::min(x1, (float)width - 1), 0.f);
365
        y1 = std::max(std::min(y1, (float)height - 1), 0.f);
366

367
        faceobjects[i].rect.x = x0;
368
        faceobjects[i].rect.y = y0;
369
        faceobjects[i].rect.width = x1 - x0;
370
        faceobjects[i].rect.height = y1 - y0;
371
    }
372

373
    return 0;
374
}
375

376
static void draw_faceobjects(const cv::Mat& bgr, const std::vector<FaceObject>& faceobjects)
377
{
378
    cv::Mat image = bgr.clone();
379

380
    for (size_t i = 0; i < faceobjects.size(); i++)
381
    {
382
        const FaceObject& obj = faceobjects[i];
383

384
        fprintf(stderr, "%.5f at %.2f %.2f %.2f x %.2f\n", obj.prob,
385
                obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
386

387
        cv::rectangle(image, obj.rect, cv::Scalar(0, 255, 0));
388

389
        char text[256];
390
        sprintf(text, "%.1f%%", obj.prob * 100);
391

392
        int baseLine = 0;
393
        cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
394

395
        int x = obj.rect.x;
396
        int y = obj.rect.y - label_size.height - baseLine;
397
        if (y < 0)
398
            y = 0;
399
        if (x + label_size.width > image.cols)
400
            x = image.cols - label_size.width;
401

402
        cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
403
                      cv::Scalar(255, 255, 255), -1);
404

405
        cv::putText(image, text, cv::Point(x, y + label_size.height),
406
                    cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
407
    }
408

409
    cv::imshow("image", image);
410
    cv::waitKey(0);
411
}
412

413
int main(int argc, char** argv)
414
{
415
    if (argc != 2)
416
    {
417
        fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
418
        return -1;
419
    }
420

421
    const char* imagepath = argv[1];
422

423
    cv::Mat m = cv::imread(imagepath, 1);
424
    if (m.empty())
425
    {
426
        fprintf(stderr, "cv::imread %s failed\n", imagepath);
427
        return -1;
428
    }
429

430
    std::vector<FaceObject> faceobjects;
431
    detect_scrfd(m, faceobjects);
432

433
    draw_faceobjects(m, faceobjects);
434

435
    return 0;
436
}
437

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.