| 1 | // Tencent is pleased to support the open source community by making ncnn available. |
| 2 | // |
| 3 | // Copyright (C) 2020 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 <stdlib.h> |
| 25 | #include <float.h> |
| 26 | #include <stdio.h> |
| 27 | #include <vector> |
| 28 | |
| 29 | struct Object |
| 30 | { |
| 31 | cv::Rect_<float> rect; |
| 32 | int label; |
| 33 | float prob; |
| 34 | }; |
| 35 | |
| 36 | static inline float intersection_area(const Object& a, const Object& b) |
| 37 | { |
| 38 | cv::Rect_<float> inter = a.rect & b.rect; |
| 39 | return inter.area(); |
| 40 | } |
| 41 | |
| 42 | static void qsort_descent_inplace(std::vector<Object>& faceobjects, int left, int right) |
| 43 | { |
| 44 | int i = left; |
| 45 | int j = right; |
| 46 | float p = faceobjects[(left + right) / 2].prob; |
| 47 | |
| 48 | while (i <= j) |
| 49 | { |
| 50 | while (faceobjects[i].prob > p) |
| 51 | i++; |
| 52 | |
| 53 | while (faceobjects[j].prob < p) |
| 54 | j--; |
| 55 | |
| 56 | if (i <= j) |
| 57 | { |
| 58 | // swap |
| 59 | std::swap(faceobjects[i], faceobjects[j]); |
| 60 | |
| 61 | i++; |
| 62 | j--; |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | #pragma omp parallel sections |
| 67 | { |
| 68 | #pragma omp section |
| 69 | { |
| 70 | if (left < j) qsort_descent_inplace(faceobjects, left, j); |
| 71 | } |
| 72 | #pragma omp section |
| 73 | { |
| 74 | if (i < right) qsort_descent_inplace(faceobjects, i, right); |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | static void qsort_descent_inplace(std::vector<Object>& faceobjects) |
| 80 | { |
| 81 | if (faceobjects.empty()) |
| 82 | return; |
| 83 | |
| 84 | qsort_descent_inplace(faceobjects, 0, faceobjects.size() - 1); |
| 85 | } |
| 86 | |
| 87 | static void nms_sorted_bboxes(const std::vector<Object>& faceobjects, std::vector<int>& picked, float nms_threshold, bool agnostic = false) |
| 88 | { |
| 89 | picked.clear(); |
| 90 | |
| 91 | const int n = faceobjects.size(); |
| 92 | |
| 93 | std::vector<float> areas(n); |
| 94 | for (int i = 0; i < n; i++) |
| 95 | { |
| 96 | areas[i] = faceobjects[i].rect.area(); |
| 97 | } |
| 98 | |
| 99 | for (int i = 0; i < n; i++) |
| 100 | { |
| 101 | const Object& a = faceobjects[i]; |
| 102 | |
| 103 | int keep = 1; |
| 104 | for (int j = 0; j < (int)picked.size(); j++) |
| 105 | { |
| 106 | const Object& b = faceobjects[picked[j]]; |
| 107 | |
| 108 | if (!agnostic && a.label != b.label) |
| 109 | continue; |
| 110 | |
| 111 | // intersection over union |
| 112 | float inter_area = intersection_area(a, b); |
| 113 | float union_area = areas[i] + areas[picked[j]] - inter_area; |
| 114 | // float IoU = inter_area / union_area |
| 115 | if (inter_area / union_area > nms_threshold) |
| 116 | keep = 0; |
| 117 | } |
| 118 | |
| 119 | if (keep) |
| 120 | picked.push_back(i); |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | static void generate_proposals(const ncnn::Mat& cls_pred, const ncnn::Mat& dis_pred, int stride, const ncnn::Mat& in_pad, float prob_threshold, std::vector<Object>& objects) |
| 125 | { |
| 126 | const int num_grid = cls_pred.h; |
| 127 | |
| 128 | int num_grid_x; |
| 129 | int num_grid_y; |
| 130 | if (in_pad.w > in_pad.h) |
| 131 | { |
| 132 | num_grid_x = in_pad.w / stride; |
| 133 | num_grid_y = num_grid / num_grid_x; |
| 134 | } |
| 135 | else |
| 136 | { |
| 137 | num_grid_y = in_pad.h / stride; |
| 138 | num_grid_x = num_grid / num_grid_y; |
| 139 | } |
| 140 | |
| 141 | const int num_class = cls_pred.w; |
| 142 | const int reg_max_1 = dis_pred.w / 4; |
| 143 | |
| 144 | for (int i = 0; i < num_grid_y; i++) |
| 145 | { |
| 146 | for (int j = 0; j < num_grid_x; j++) |
| 147 | { |
| 148 | const int idx = i * num_grid_x + j; |
| 149 | |
| 150 | const float* scores = cls_pred.row(idx); |
| 151 | |
| 152 | // find label with max score |
| 153 | int label = -1; |
| 154 | float score = -FLT_MAX; |
| 155 | for (int k = 0; k < num_class; k++) |
| 156 | { |
| 157 | if (scores[k] > score) |
| 158 | { |
| 159 | label = k; |
| 160 | score = scores[k]; |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | if (score >= prob_threshold) |
| 165 | { |
| 166 | ncnn::Mat bbox_pred(reg_max_1, 4, (void*)dis_pred.row(idx)); |
| 167 | { |
| 168 | ncnn::Layer* softmax = ncnn::create_layer("Softmax"); |
| 169 | |
| 170 | ncnn::ParamDict pd; |
| 171 | pd.set(0, 1); // axis |
| 172 | pd.set(1, 1); |
| 173 | softmax->load_param(pd); |
| 174 | |
| 175 | ncnn::Option opt; |
| 176 | opt.num_threads = 1; |
| 177 | opt.use_packing_layout = false; |
| 178 | |
| 179 | softmax->create_pipeline(opt); |
| 180 | |
| 181 | softmax->forward_inplace(bbox_pred, opt); |
| 182 | |
| 183 | softmax->destroy_pipeline(opt); |
| 184 | |
| 185 | delete softmax; |
| 186 | } |
| 187 | |
| 188 | float pred_ltrb[4]; |
| 189 | for (int k = 0; k < 4; k++) |
| 190 | { |
| 191 | float dis = 0.f; |
| 192 | const float* dis_after_sm = bbox_pred.row(k); |
| 193 | for (int l = 0; l < reg_max_1; l++) |
| 194 | { |
| 195 | dis += l * dis_after_sm[l]; |
| 196 | } |
| 197 | |
| 198 | pred_ltrb[k] = dis * stride; |
| 199 | } |
| 200 | |
| 201 | float pb_cx = (j + 0.5f) * stride; |
| 202 | float pb_cy = (i + 0.5f) * stride; |
| 203 | |
| 204 | float x0 = pb_cx - pred_ltrb[0]; |
| 205 | float y0 = pb_cy - pred_ltrb[1]; |
| 206 | float x1 = pb_cx + pred_ltrb[2]; |
| 207 | float y1 = pb_cy + pred_ltrb[3]; |
| 208 | |
| 209 | Object obj; |
| 210 | obj.rect.x = x0; |
| 211 | obj.rect.y = y0; |
| 212 | obj.rect.width = x1 - x0; |
| 213 | obj.rect.height = y1 - y0; |
| 214 | obj.label = label; |
| 215 | obj.prob = score; |
| 216 | |
| 217 | objects.push_back(obj); |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | static int detect_nanodet(const cv::Mat& bgr, std::vector<Object>& objects) |
| 224 | { |
| 225 | ncnn::Net nanodet; |
| 226 | |
| 227 | nanodet.opt.use_vulkan_compute = true; |
| 228 | // nanodet.opt.use_bf16_storage = true; |
| 229 | |
| 230 | // original pretrained model from https://github.com/RangiLyu/nanodet |
| 231 | // the ncnn model https://github.com/nihui/ncnn-assets/tree/master/models |
| 232 | if (nanodet.load_param("nanodet_m.param")) |
| 233 | exit(-1); |
| 234 | if (nanodet.load_model("nanodet_m.bin")) |
| 235 | exit(-1); |
| 236 | |
| 237 | int width = bgr.cols; |
| 238 | int height = bgr.rows; |
| 239 | |
| 240 | const int target_size = 320; |
| 241 | const float prob_threshold = 0.4f; |
| 242 | const float nms_threshold = 0.5f; |
| 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_BGR, 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] = {103.53f, 116.28f, 123.675f}; |
| 270 | const float norm_vals[3] = {0.017429f, 0.017507f, 0.017125f}; |
| 271 | in_pad.substract_mean_normalize(mean_vals, norm_vals); |
| 272 | |
| 273 | ncnn::Extractor ex = nanodet.create_extractor(); |
| 274 | |
| 275 | ex.input("input.1", in_pad); |
| 276 | |
| 277 | std::vector<Object> proposals; |
| 278 | |
| 279 | // stride 8 |
| 280 | { |
| 281 | ncnn::Mat cls_pred; |
| 282 | ncnn::Mat dis_pred; |
| 283 | ex.extract("792", cls_pred); |
| 284 | ex.extract("795", dis_pred); |
| 285 | |
| 286 | std::vector<Object> objects8; |
| 287 | generate_proposals(cls_pred, dis_pred, 8, in_pad, prob_threshold, objects8); |
| 288 | |
| 289 | proposals.insert(proposals.end(), objects8.begin(), objects8.end()); |
| 290 | } |
| 291 | |
| 292 | // stride 16 |
| 293 | { |
| 294 | ncnn::Mat cls_pred; |
| 295 | ncnn::Mat dis_pred; |
| 296 | ex.extract("814", cls_pred); |
| 297 | ex.extract("817", dis_pred); |
| 298 | |
| 299 | std::vector<Object> objects16; |
| 300 | generate_proposals(cls_pred, dis_pred, 16, in_pad, prob_threshold, objects16); |
| 301 | |
| 302 | proposals.insert(proposals.end(), objects16.begin(), objects16.end()); |
| 303 | } |
| 304 | |
| 305 | // stride 32 |
| 306 | { |
| 307 | ncnn::Mat cls_pred; |
| 308 | ncnn::Mat dis_pred; |
| 309 | ex.extract("836", cls_pred); |
| 310 | ex.extract("839", dis_pred); |
| 311 | |
| 312 | std::vector<Object> objects32; |
| 313 | generate_proposals(cls_pred, dis_pred, 32, in_pad, prob_threshold, objects32); |
| 314 | |
| 315 | proposals.insert(proposals.end(), objects32.begin(), objects32.end()); |
| 316 | } |
| 317 | |
| 318 | // sort all proposals by score from highest to lowest |
| 319 | qsort_descent_inplace(proposals); |
| 320 | |
| 321 | // apply nms with nms_threshold |
| 322 | std::vector<int> picked; |
| 323 | nms_sorted_bboxes(proposals, picked, nms_threshold); |
| 324 | |
| 325 | int count = picked.size(); |
| 326 | |
| 327 | objects.resize(count); |
| 328 | for (int i = 0; i < count; i++) |
| 329 | { |
| 330 | objects[i] = proposals[picked[i]]; |
| 331 | |
| 332 | // adjust offset to original unpadded |
| 333 | float x0 = (objects[i].rect.x - (wpad / 2)) / scale; |
| 334 | float y0 = (objects[i].rect.y - (hpad / 2)) / scale; |
| 335 | float x1 = (objects[i].rect.x + objects[i].rect.width - (wpad / 2)) / scale; |
| 336 | float y1 = (objects[i].rect.y + objects[i].rect.height - (hpad / 2)) / scale; |
| 337 | |
| 338 | // clip |
| 339 | x0 = std::max(std::min(x0, (float)(width - 1)), 0.f); |
| 340 | y0 = std::max(std::min(y0, (float)(height - 1)), 0.f); |
| 341 | x1 = std::max(std::min(x1, (float)(width - 1)), 0.f); |
| 342 | y1 = std::max(std::min(y1, (float)(height - 1)), 0.f); |
| 343 | |
| 344 | objects[i].rect.x = x0; |
| 345 | objects[i].rect.y = y0; |
| 346 | objects[i].rect.width = x1 - x0; |
| 347 | objects[i].rect.height = y1 - y0; |
| 348 | } |
| 349 | |
| 350 | return 0; |
| 351 | } |
| 352 | |
| 353 | static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects) |
| 354 | { |
| 355 | static const char* class_names[] = { |
| 356 | "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", |
| 357 | "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", |
| 358 | "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", |
| 359 | "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", |
| 360 | "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", |
| 361 | "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", |
| 362 | "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", |
| 363 | "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", |
| 364 | "hair drier", "toothbrush" |
| 365 | }; |
| 366 | |
| 367 | cv::Mat image = bgr.clone(); |
| 368 | |
| 369 | for (size_t i = 0; i < objects.size(); i++) |
| 370 | { |
| 371 | const Object& obj = objects[i]; |
| 372 | |
| 373 | fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob, |
| 374 | obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height); |
| 375 | |
| 376 | cv::rectangle(image, obj.rect, cv::Scalar(255, 0, 0)); |
| 377 | |
| 378 | char text[256]; |
| 379 | sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100); |
| 380 | |
| 381 | int baseLine = 0; |
| 382 | cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine); |
| 383 | |
| 384 | int x = obj.rect.x; |
| 385 | int y = obj.rect.y - label_size.height - baseLine; |
| 386 | if (y < 0) |
| 387 | y = 0; |
| 388 | if (x + label_size.width > image.cols) |
| 389 | x = image.cols - label_size.width; |
| 390 | |
| 391 | cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)), |
| 392 | cv::Scalar(255, 255, 255), -1); |
| 393 | |
| 394 | cv::putText(image, text, cv::Point(x, y + label_size.height), |
| 395 | cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0)); |
| 396 | } |
| 397 | |
| 398 | cv::imshow("image", image); |
| 399 | cv::waitKey(0); |
| 400 | } |
| 401 | |
| 402 | int main(int argc, char** argv) |
| 403 | { |
| 404 | if (argc != 2) |
| 405 | { |
| 406 | fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]); |
| 407 | return -1; |
| 408 | } |
| 409 | |
| 410 | const char* imagepath = argv[1]; |
| 411 | |
| 412 | cv::Mat m = cv::imread(imagepath, 1); |
| 413 | if (m.empty()) |
| 414 | { |
| 415 | fprintf(stderr, "cv::imread %s failed\n", imagepath); |
| 416 | return -1; |
| 417 | } |
| 418 | |
| 419 | std::vector<Object> objects; |
| 420 | detect_nanodet(m, objects); |
| 421 | |
| 422 | draw_objects(m, objects); |
| 423 | |
| 424 | return 0; |
| 425 | } |