ncnn

Форк
0
/
retinaface.cpp 
436 строк · 13.7 Кб
1
// Tencent is pleased to support the open source community by making ncnn available.
2
//
3
// Copyright (C) 2019 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
    cv::Point2f landmark[5];
31
    float prob;
32
};
33

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

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

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

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

54
        if (i <= j)
55
        {
56
            // swap
57
            std::swap(faceobjects[i], faceobjects[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(faceobjects, left, j);
69
        }
70
        #pragma omp section
71
        {
72
            if (i < right) qsort_descent_inplace(faceobjects, i, right);
73
        }
74
    }
75
}
76

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

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

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

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

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

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

101
        int keep = 1;
102
        for (int j = 0; j < (int)picked.size(); j++)
103
        {
104
            const FaceObject& b = faceobjects[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

119
// copy from src/layer/proposal.cpp
120
static ncnn::Mat generate_anchors(int base_size, const ncnn::Mat& ratios, const ncnn::Mat& scales)
121
{
122
    int num_ratio = ratios.w;
123
    int num_scale = scales.w;
124

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

128
    const float cx = base_size * 0.5f;
129
    const float cy = base_size * 0.5f;
130

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

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

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

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

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

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

154
    return anchors;
155
}
156

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

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

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

169
        const ncnn::Mat score = score_blob.channel(q + num_anchors);
170
        const ncnn::Mat bbox = bbox_blob.channel_range(q * 4, 4);
171
        const ncnn::Mat landmark = landmark_blob.channel_range(q * 10, 10);
172

173
        // shifted anchor
174
        float anchor_y = anchor[1];
175

176
        float anchor_w = anchor[2] - anchor[0];
177
        float anchor_h = anchor[3] - anchor[1];
178

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

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

187
                float prob = score[index];
188

189
                if (prob >= prob_threshold)
190
                {
191
                    // apply center size
192
                    float dx = bbox.channel(0)[index];
193
                    float dy = bbox.channel(1)[index];
194
                    float dw = bbox.channel(2)[index];
195
                    float dh = bbox.channel(3)[index];
196

197
                    float cx = anchor_x + anchor_w * 0.5f;
198
                    float cy = anchor_y + anchor_h * 0.5f;
199

200
                    float pb_cx = cx + anchor_w * dx;
201
                    float pb_cy = cy + anchor_h * dy;
202

203
                    float pb_w = anchor_w * exp(dw);
204
                    float pb_h = anchor_h * exp(dh);
205

206
                    float x0 = pb_cx - pb_w * 0.5f;
207
                    float y0 = pb_cy - pb_h * 0.5f;
208
                    float x1 = pb_cx + pb_w * 0.5f;
209
                    float y1 = pb_cy + pb_h * 0.5f;
210

211
                    FaceObject obj;
212
                    obj.rect.x = x0;
213
                    obj.rect.y = y0;
214
                    obj.rect.width = x1 - x0 + 1;
215
                    obj.rect.height = y1 - y0 + 1;
216
                    obj.landmark[0].x = cx + (anchor_w + 1) * landmark.channel(0)[index];
217
                    obj.landmark[0].y = cy + (anchor_h + 1) * landmark.channel(1)[index];
218
                    obj.landmark[1].x = cx + (anchor_w + 1) * landmark.channel(2)[index];
219
                    obj.landmark[1].y = cy + (anchor_h + 1) * landmark.channel(3)[index];
220
                    obj.landmark[2].x = cx + (anchor_w + 1) * landmark.channel(4)[index];
221
                    obj.landmark[2].y = cy + (anchor_h + 1) * landmark.channel(5)[index];
222
                    obj.landmark[3].x = cx + (anchor_w + 1) * landmark.channel(6)[index];
223
                    obj.landmark[3].y = cy + (anchor_h + 1) * landmark.channel(7)[index];
224
                    obj.landmark[4].x = cx + (anchor_w + 1) * landmark.channel(8)[index];
225
                    obj.landmark[4].y = cy + (anchor_h + 1) * landmark.channel(9)[index];
226
                    obj.prob = prob;
227

228
                    faceobjects.push_back(obj);
229
                }
230

231
                anchor_x += feat_stride;
232
            }
233

234
            anchor_y += feat_stride;
235
        }
236
    }
237
}
238

239
static int detect_retinaface(const cv::Mat& bgr, std::vector<FaceObject>& faceobjects)
240
{
241
    ncnn::Net retinaface;
242

243
    retinaface.opt.use_vulkan_compute = true;
244

245
    // model is converted from
246
    // https://github.com/deepinsight/insightface/tree/master/RetinaFace#retinaface-pretrained-models
247
    // https://github.com/deepinsight/insightface/issues/669
248
    // the ncnn model https://github.com/nihui/ncnn-assets/tree/master/models
249
    //     retinaface.load_param("retinaface-R50.param");
250
    //     retinaface.load_model("retinaface-R50.bin");
251
    if (retinaface.load_param("mnet.25-opt.param"))
252
        exit(-1);
253
    if (retinaface.load_model("mnet.25-opt.bin"))
254
        exit(-1);
255

256
    const float prob_threshold = 0.8f;
257
    const float nms_threshold = 0.4f;
258

259
    int img_w = bgr.cols;
260
    int img_h = bgr.rows;
261

262
    ncnn::Mat in = ncnn::Mat::from_pixels(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, img_w, img_h);
263

264
    ncnn::Extractor ex = retinaface.create_extractor();
265

266
    ex.input("data", in);
267

268
    std::vector<FaceObject> faceproposals;
269

270
    // stride 32
271
    {
272
        ncnn::Mat score_blob, bbox_blob, landmark_blob;
273
        ex.extract("face_rpn_cls_prob_reshape_stride32", score_blob);
274
        ex.extract("face_rpn_bbox_pred_stride32", bbox_blob);
275
        ex.extract("face_rpn_landmark_pred_stride32", landmark_blob);
276

277
        const int base_size = 16;
278
        const int feat_stride = 32;
279
        ncnn::Mat ratios(1);
280
        ratios[0] = 1.f;
281
        ncnn::Mat scales(2);
282
        scales[0] = 32.f;
283
        scales[1] = 16.f;
284
        ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
285

286
        std::vector<FaceObject> faceobjects32;
287
        generate_proposals(anchors, feat_stride, score_blob, bbox_blob, landmark_blob, prob_threshold, faceobjects32);
288

289
        faceproposals.insert(faceproposals.end(), faceobjects32.begin(), faceobjects32.end());
290
    }
291

292
    // stride 16
293
    {
294
        ncnn::Mat score_blob, bbox_blob, landmark_blob;
295
        ex.extract("face_rpn_cls_prob_reshape_stride16", score_blob);
296
        ex.extract("face_rpn_bbox_pred_stride16", bbox_blob);
297
        ex.extract("face_rpn_landmark_pred_stride16", landmark_blob);
298

299
        const int base_size = 16;
300
        const int feat_stride = 16;
301
        ncnn::Mat ratios(1);
302
        ratios[0] = 1.f;
303
        ncnn::Mat scales(2);
304
        scales[0] = 8.f;
305
        scales[1] = 4.f;
306
        ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
307

308
        std::vector<FaceObject> faceobjects16;
309
        generate_proposals(anchors, feat_stride, score_blob, bbox_blob, landmark_blob, prob_threshold, faceobjects16);
310

311
        faceproposals.insert(faceproposals.end(), faceobjects16.begin(), faceobjects16.end());
312
    }
313

314
    // stride 8
315
    {
316
        ncnn::Mat score_blob, bbox_blob, landmark_blob;
317
        ex.extract("face_rpn_cls_prob_reshape_stride8", score_blob);
318
        ex.extract("face_rpn_bbox_pred_stride8", bbox_blob);
319
        ex.extract("face_rpn_landmark_pred_stride8", landmark_blob);
320

321
        const int base_size = 16;
322
        const int feat_stride = 8;
323
        ncnn::Mat ratios(1);
324
        ratios[0] = 1.f;
325
        ncnn::Mat scales(2);
326
        scales[0] = 2.f;
327
        scales[1] = 1.f;
328
        ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
329

330
        std::vector<FaceObject> faceobjects8;
331
        generate_proposals(anchors, feat_stride, score_blob, bbox_blob, landmark_blob, prob_threshold, faceobjects8);
332

333
        faceproposals.insert(faceproposals.end(), faceobjects8.begin(), faceobjects8.end());
334
    }
335

336
    // sort all proposals by score from highest to lowest
337
    qsort_descent_inplace(faceproposals);
338

339
    // apply nms with nms_threshold
340
    std::vector<int> picked;
341
    nms_sorted_bboxes(faceproposals, picked, nms_threshold);
342

343
    int face_count = picked.size();
344

345
    faceobjects.resize(face_count);
346
    for (int i = 0; i < face_count; i++)
347
    {
348
        faceobjects[i] = faceproposals[picked[i]];
349

350
        // clip to image size
351
        float x0 = faceobjects[i].rect.x;
352
        float y0 = faceobjects[i].rect.y;
353
        float x1 = x0 + faceobjects[i].rect.width;
354
        float y1 = y0 + faceobjects[i].rect.height;
355

356
        x0 = std::max(std::min(x0, (float)img_w - 1), 0.f);
357
        y0 = std::max(std::min(y0, (float)img_h - 1), 0.f);
358
        x1 = std::max(std::min(x1, (float)img_w - 1), 0.f);
359
        y1 = std::max(std::min(y1, (float)img_h - 1), 0.f);
360

361
        faceobjects[i].rect.x = x0;
362
        faceobjects[i].rect.y = y0;
363
        faceobjects[i].rect.width = x1 - x0;
364
        faceobjects[i].rect.height = y1 - y0;
365
    }
366

367
    return 0;
368
}
369

370
static void draw_faceobjects(const cv::Mat& bgr, const std::vector<FaceObject>& faceobjects)
371
{
372
    cv::Mat image = bgr.clone();
373

374
    for (size_t i = 0; i < faceobjects.size(); i++)
375
    {
376
        const FaceObject& obj = faceobjects[i];
377

378
        fprintf(stderr, "%.5f at %.2f %.2f %.2f x %.2f\n", obj.prob,
379
                obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
380

381
        cv::rectangle(image, obj.rect, cv::Scalar(0, 255, 0));
382

383
        cv::circle(image, obj.landmark[0], 2, cv::Scalar(0, 255, 255), -1);
384
        cv::circle(image, obj.landmark[1], 2, cv::Scalar(0, 255, 255), -1);
385
        cv::circle(image, obj.landmark[2], 2, cv::Scalar(0, 255, 255), -1);
386
        cv::circle(image, obj.landmark[3], 2, cv::Scalar(0, 255, 255), -1);
387
        cv::circle(image, obj.landmark[4], 2, cv::Scalar(0, 255, 255), -1);
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_retinaface(m, faceobjects);
432

433
    draw_faceobjects(m, faceobjects);
434

435
    return 0;
436
}
437

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

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

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

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