1
// Tencent is pleased to support the open source community by making ncnn available.
3
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
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
8
// https://opensource.org/licenses/BSD-3-Clause
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.
17
#if defined(USE_NCNN_SIMPLEOCV)
20
#include <opencv2/core/core.hpp>
21
#include <opencv2/highgui/highgui.hpp>
22
#include <opencv2/imgproc/imgproc.hpp>
29
cv::Rect_<float> rect;
30
cv::Point2f landmark[5];
34
static inline float intersection_area(const FaceObject& a, const FaceObject& b)
36
cv::Rect_<float> inter = a.rect & b.rect;
40
static void qsort_descent_inplace(std::vector<FaceObject>& faceobjects, int left, int right)
44
float p = faceobjects[(left + right) / 2].prob;
48
while (faceobjects[i].prob > p)
51
while (faceobjects[j].prob < p)
57
std::swap(faceobjects[i], faceobjects[j]);
64
#pragma omp parallel sections
68
if (left < j) qsort_descent_inplace(faceobjects, left, j);
72
if (i < right) qsort_descent_inplace(faceobjects, i, right);
77
static void qsort_descent_inplace(std::vector<FaceObject>& faceobjects)
79
if (faceobjects.empty())
82
qsort_descent_inplace(faceobjects, 0, faceobjects.size() - 1);
85
static void nms_sorted_bboxes(const std::vector<FaceObject>& faceobjects, std::vector<int>& picked, float nms_threshold)
89
const int n = faceobjects.size();
91
std::vector<float> areas(n);
92
for (int i = 0; i < n; i++)
94
areas[i] = faceobjects[i].rect.area();
97
for (int i = 0; i < n; i++)
99
const FaceObject& a = faceobjects[i];
102
for (int j = 0; j < (int)picked.size(); j++)
104
const FaceObject& b = faceobjects[picked[j]];
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)
119
// copy from src/layer/proposal.cpp
120
static ncnn::Mat generate_anchors(int base_size, const ncnn::Mat& ratios, const ncnn::Mat& scales)
122
int num_ratio = ratios.w;
123
int num_scale = scales.w;
126
anchors.create(4, num_ratio * num_scale);
128
const float cx = base_size * 0.5f;
129
const float cy = base_size * 0.5f;
131
for (int i = 0; i < num_ratio; i++)
133
float ar = ratios[i];
135
int r_w = round(base_size / sqrt(ar));
136
int r_h = round(r_w * ar); //round(base_size * sqrt(ar));
138
for (int j = 0; j < num_scale; j++)
140
float scale = scales[j];
142
float rs_w = r_w * scale;
143
float rs_h = r_h * scale;
145
float* anchor = anchors.row(i * num_scale + j);
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;
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)
159
int w = score_blob.w;
160
int h = score_blob.h;
162
// generate face proposal from bbox deltas and shifted anchors
163
const int num_anchors = anchors.h;
165
for (int q = 0; q < num_anchors; q++)
167
const float* anchor = anchors.row(q);
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);
174
float anchor_y = anchor[1];
176
float anchor_w = anchor[2] - anchor[0];
177
float anchor_h = anchor[3] - anchor[1];
179
for (int i = 0; i < h; i++)
181
float anchor_x = anchor[0];
183
for (int j = 0; j < w; j++)
185
int index = i * w + j;
187
float prob = score[index];
189
if (prob >= prob_threshold)
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];
197
float cx = anchor_x + anchor_w * 0.5f;
198
float cy = anchor_y + anchor_h * 0.5f;
200
float pb_cx = cx + anchor_w * dx;
201
float pb_cy = cy + anchor_h * dy;
203
float pb_w = anchor_w * exp(dw);
204
float pb_h = anchor_h * exp(dh);
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;
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];
228
faceobjects.push_back(obj);
231
anchor_x += feat_stride;
234
anchor_y += feat_stride;
239
static int detect_retinaface(const cv::Mat& bgr, std::vector<FaceObject>& faceobjects)
241
ncnn::Net retinaface;
243
retinaface.opt.use_vulkan_compute = true;
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"))
253
if (retinaface.load_model("mnet.25-opt.bin"))
256
const float prob_threshold = 0.8f;
257
const float nms_threshold = 0.4f;
259
int img_w = bgr.cols;
260
int img_h = bgr.rows;
262
ncnn::Mat in = ncnn::Mat::from_pixels(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, img_w, img_h);
264
ncnn::Extractor ex = retinaface.create_extractor();
266
ex.input("data", in);
268
std::vector<FaceObject> faceproposals;
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);
277
const int base_size = 16;
278
const int feat_stride = 32;
284
ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
286
std::vector<FaceObject> faceobjects32;
287
generate_proposals(anchors, feat_stride, score_blob, bbox_blob, landmark_blob, prob_threshold, faceobjects32);
289
faceproposals.insert(faceproposals.end(), faceobjects32.begin(), faceobjects32.end());
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);
299
const int base_size = 16;
300
const int feat_stride = 16;
306
ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
308
std::vector<FaceObject> faceobjects16;
309
generate_proposals(anchors, feat_stride, score_blob, bbox_blob, landmark_blob, prob_threshold, faceobjects16);
311
faceproposals.insert(faceproposals.end(), faceobjects16.begin(), faceobjects16.end());
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);
321
const int base_size = 16;
322
const int feat_stride = 8;
328
ncnn::Mat anchors = generate_anchors(base_size, ratios, scales);
330
std::vector<FaceObject> faceobjects8;
331
generate_proposals(anchors, feat_stride, score_blob, bbox_blob, landmark_blob, prob_threshold, faceobjects8);
333
faceproposals.insert(faceproposals.end(), faceobjects8.begin(), faceobjects8.end());
336
// sort all proposals by score from highest to lowest
337
qsort_descent_inplace(faceproposals);
339
// apply nms with nms_threshold
340
std::vector<int> picked;
341
nms_sorted_bboxes(faceproposals, picked, nms_threshold);
343
int face_count = picked.size();
345
faceobjects.resize(face_count);
346
for (int i = 0; i < face_count; i++)
348
faceobjects[i] = faceproposals[picked[i]];
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;
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);
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;
370
static void draw_faceobjects(const cv::Mat& bgr, const std::vector<FaceObject>& faceobjects)
372
cv::Mat image = bgr.clone();
374
for (size_t i = 0; i < faceobjects.size(); i++)
376
const FaceObject& obj = faceobjects[i];
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);
381
cv::rectangle(image, obj.rect, cv::Scalar(0, 255, 0));
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);
390
sprintf(text, "%.1f%%", obj.prob * 100);
393
cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
396
int y = obj.rect.y - label_size.height - baseLine;
399
if (x + label_size.width > image.cols)
400
x = image.cols - label_size.width;
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);
405
cv::putText(image, text, cv::Point(x, y + label_size.height),
406
cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
409
cv::imshow("image", image);
413
int main(int argc, char** argv)
417
fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]);
421
const char* imagepath = argv[1];
423
cv::Mat m = cv::imread(imagepath, 1);
426
fprintf(stderr, "cv::imread %s failed\n", imagepath);
430
std::vector<FaceObject> faceobjects;
431
detect_retinaface(m, faceobjects);
433
draw_faceobjects(m, faceobjects);