| 1 | // Tencent is pleased to support the open source community by making ncnn available. |
| 2 | // |
| 3 | // Copyright (C) 2022 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 "layer.h" |
| 16 | #include "net.h" |
| 17 | |
| 18 | #if defined(USE_NCNN_SIMPLEOCV) |
| 19 | #include "simpleocv.h" |
| 20 | #else |
| 21 | #include <opencv2/core/core.hpp> |
| 22 | #include <opencv2/highgui/highgui.hpp> |
| 23 | #include <opencv2/imgproc/imgproc.hpp> |
| 24 | #endif |
| 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 inline float sigmoid(float x) |
| 125 | { |
| 126 | return static_cast<float>(1.f / (1.f + exp(-x))); |
| 127 | } |
| 128 | |
| 129 | static void generate_proposals(const ncnn::Mat& anchors, int stride, const ncnn::Mat& in_pad, const ncnn::Mat& feat_blob, float prob_threshold, std::vector<Object>& objects) |
| 130 | { |
| 131 | const int num_grid_x = feat_blob.w; |
| 132 | const int num_grid_y = feat_blob.h; |
| 133 | |
| 134 | const int num_anchors = anchors.w / 2; |
| 135 | |
| 136 | const int num_class = 80; |
| 137 | |
| 138 | for (int q = 0; q < num_anchors; q++) |
| 139 | { |
| 140 | const float anchor_w = anchors[q * 2]; |
| 141 | const float anchor_h = anchors[q * 2 + 1]; |
| 142 | |
| 143 | for (int i = 0; i < num_grid_y; i++) |
| 144 | { |
| 145 | for (int j = 0; j < num_grid_x; j++) |
| 146 | { |
| 147 | // find class index with max class score |
| 148 | int class_index = 0; |
| 149 | float class_score = -FLT_MAX; |
| 150 | for (int k = 0; k < num_class; k++) |
| 151 | { |
| 152 | float score = feat_blob.channel(q * 85 + 5 + k).row(i)[j]; |
| 153 | if (score > class_score) |
| 154 | { |
| 155 | class_index = k; |
| 156 | class_score = score; |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | float box_score = feat_blob.channel(q * 85 + 4).row(i)[j]; |
| 161 | |
| 162 | float confidence = sigmoid(box_score) * sigmoid(class_score); |
| 163 | |
| 164 | if (confidence >= prob_threshold) |
| 165 | { |
| 166 | // yolov5/models/yolo.py Detect forward |
| 167 | // y = x[i].sigmoid() |
| 168 | // y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i].to(x[i].device)) * self.stride[i] # xy |
| 169 | // y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh |
| 170 | |
| 171 | float dx = sigmoid(feat_blob.channel(q * 85 + 0).row(i)[j]); |
| 172 | float dy = sigmoid(feat_blob.channel(q * 85 + 1).row(i)[j]); |
| 173 | float dw = sigmoid(feat_blob.channel(q * 85 + 2).row(i)[j]); |
| 174 | float dh = sigmoid(feat_blob.channel(q * 85 + 3).row(i)[j]); |
| 175 | |
| 176 | float pb_cx = (dx * 2.f - 0.5f + j) * stride; |
| 177 | float pb_cy = (dy * 2.f - 0.5f + i) * stride; |
| 178 | |
| 179 | float pb_w = pow(dw * 2.f, 2) * anchor_w; |
| 180 | float pb_h = pow(dh * 2.f, 2) * anchor_h; |
| 181 | |
| 182 | float x0 = pb_cx - pb_w * 0.5f; |
| 183 | float y0 = pb_cy - pb_h * 0.5f; |
| 184 | float x1 = pb_cx + pb_w * 0.5f; |
| 185 | float y1 = pb_cy + pb_h * 0.5f; |
| 186 | |
| 187 | Object obj; |
| 188 | obj.rect.x = x0; |
| 189 | obj.rect.y = y0; |
| 190 | obj.rect.width = x1 - x0; |
| 191 | obj.rect.height = y1 - y0; |
| 192 | obj.label = class_index; |
| 193 | obj.prob = confidence; |
| 194 | |
| 195 | objects.push_back(obj); |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | static int detect_yolov7(const cv::Mat& bgr, std::vector<Object>& objects) |
| 203 | { |
| 204 | ncnn::Net yolov7; |
| 205 | |
| 206 | yolov7.opt.use_vulkan_compute = true; |
| 207 | // yolov7.opt.use_bf16_storage = true; |
| 208 | |
| 209 | // git clone https://github.com/WongKinYiu/yolov7 |
| 210 | // cd yolov7 |
| 211 | // wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7.pt |
| 212 | // python models/export.py --weights yolov7.pt |
| 213 | // pnnx yolov7.torchscript.pt inputshape=[1,3,640,640] inputshape=[1,3,320,320] |
| 214 | yolov7.load_param("yolov7.param"); |
| 215 | yolov7.load_model("yolov7.bin"); |
| 216 | |
| 217 | const int target_size = 640; |
| 218 | const float prob_threshold = 0.25f; |
| 219 | const float nms_threshold = 0.45f; |
| 220 | |
| 221 | int img_w = bgr.cols; |
| 222 | int img_h = bgr.rows; |
| 223 | |
| 224 | // yolov5/models/common.py DetectMultiBackend |
| 225 | const int max_stride = 64; |
| 226 | |
| 227 | // letterbox pad to multiple of max_stride |
| 228 | int w = img_w; |
| 229 | int h = img_h; |
| 230 | float scale = 1.f; |
| 231 | if (w > h) |
| 232 | { |
| 233 | scale = (float)target_size / w; |
| 234 | w = target_size; |
| 235 | h = h * scale; |
| 236 | } |
| 237 | else |
| 238 | { |
| 239 | scale = (float)target_size / h; |
| 240 | h = target_size; |
| 241 | w = w * scale; |
| 242 | } |
| 243 | |
| 244 | ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, img_w, img_h, w, h); |
| 245 | |
| 246 | // pad to target_size rectangle |
| 247 | // yolov5/utils/datasets.py letterbox |
| 248 | int wpad = (w + max_stride - 1) / max_stride * max_stride - w; |
| 249 | int hpad = (h + max_stride - 1) / max_stride * max_stride - h; |
| 250 | ncnn::Mat in_pad; |
| 251 | ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 114.f); |
| 252 | |
| 253 | const float norm_vals[3] = {1 / 255.f, 1 / 255.f, 1 / 255.f}; |
| 254 | in_pad.substract_mean_normalize(0, norm_vals); |
| 255 | |
| 256 | ncnn::Extractor ex = yolov7.create_extractor(); |
| 257 | |
| 258 | ex.input("in0", in_pad); |
| 259 | |
| 260 | std::vector<Object> proposals; |
| 261 | |
| 262 | // anchor setting from yolov5/models/yolov5s.yaml |
| 263 | |
| 264 | // stride 8 |
| 265 | { |
| 266 | ncnn::Mat out; |
| 267 | ex.extract("out0", out); |
| 268 | |
| 269 | ncnn::Mat anchors(6); |
| 270 | anchors[0] = 12.f; |
| 271 | anchors[1] = 16.f; |
| 272 | anchors[2] = 19.f; |
| 273 | anchors[3] = 36.f; |
| 274 | anchors[4] = 40.f; |
| 275 | anchors[5] = 28.f; |
| 276 | |
| 277 | std::vector<Object> objects8; |
| 278 | generate_proposals(anchors, 8, in_pad, out, prob_threshold, objects8); |
| 279 | |
| 280 | proposals.insert(proposals.end(), objects8.begin(), objects8.end()); |
| 281 | } |
| 282 | |
| 283 | // stride 16 |
| 284 | { |
| 285 | ncnn::Mat out; |
| 286 | ex.extract("out1", out); |
| 287 | |
| 288 | ncnn::Mat anchors(6); |
| 289 | anchors[0] = 36.f; |
| 290 | anchors[1] = 75.f; |
| 291 | anchors[2] = 76.f; |
| 292 | anchors[3] = 55.f; |
| 293 | anchors[4] = 72.f; |
| 294 | anchors[5] = 146.f; |
| 295 | |
| 296 | std::vector<Object> objects16; |
| 297 | generate_proposals(anchors, 16, in_pad, out, prob_threshold, objects16); |
| 298 | |
| 299 | proposals.insert(proposals.end(), objects16.begin(), objects16.end()); |
| 300 | } |
| 301 | |
| 302 | // stride 32 |
| 303 | { |
| 304 | ncnn::Mat out; |
| 305 | ex.extract("out2", out); |
| 306 | |
| 307 | ncnn::Mat anchors(6); |
| 308 | anchors[0] = 142.f; |
| 309 | anchors[1] = 110.f; |
| 310 | anchors[2] = 192.f; |
| 311 | anchors[3] = 243.f; |
| 312 | anchors[4] = 459.f; |
| 313 | anchors[5] = 401.f; |
| 314 | |
| 315 | std::vector<Object> objects32; |
| 316 | generate_proposals(anchors, 32, in_pad, out, prob_threshold, objects32); |
| 317 | |
| 318 | proposals.insert(proposals.end(), objects32.begin(), objects32.end()); |
| 319 | } |
| 320 | |
| 321 | // sort all proposals by score from highest to lowest |
| 322 | qsort_descent_inplace(proposals); |
| 323 | |
| 324 | // apply nms with nms_threshold |
| 325 | std::vector<int> picked; |
| 326 | nms_sorted_bboxes(proposals, picked, nms_threshold); |
| 327 | |
| 328 | int count = picked.size(); |
| 329 | |
| 330 | objects.resize(count); |
| 331 | for (int i = 0; i < count; i++) |
| 332 | { |
| 333 | objects[i] = proposals[picked[i]]; |
| 334 | |
| 335 | // adjust offset to original unpadded |
| 336 | float x0 = (objects[i].rect.x - (wpad / 2)) / scale; |
| 337 | float y0 = (objects[i].rect.y - (hpad / 2)) / scale; |
| 338 | float x1 = (objects[i].rect.x + objects[i].rect.width - (wpad / 2)) / scale; |
| 339 | float y1 = (objects[i].rect.y + objects[i].rect.height - (hpad / 2)) / scale; |
| 340 | |
| 341 | // clip |
| 342 | x0 = std::max(std::min(x0, (float)(img_w - 1)), 0.f); |
| 343 | y0 = std::max(std::min(y0, (float)(img_h - 1)), 0.f); |
| 344 | x1 = std::max(std::min(x1, (float)(img_w - 1)), 0.f); |
| 345 | y1 = std::max(std::min(y1, (float)(img_h - 1)), 0.f); |
| 346 | |
| 347 | objects[i].rect.x = x0; |
| 348 | objects[i].rect.y = y0; |
| 349 | objects[i].rect.width = x1 - x0; |
| 350 | objects[i].rect.height = y1 - y0; |
| 351 | } |
| 352 | |
| 353 | return 0; |
| 354 | } |
| 355 | |
| 356 | static void draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects) |
| 357 | { |
| 358 | static const char* class_names[] = { |
| 359 | "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", |
| 360 | "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", |
| 361 | "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", |
| 362 | "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", |
| 363 | "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", |
| 364 | "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", |
| 365 | "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", |
| 366 | "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", |
| 367 | "hair drier", "toothbrush" |
| 368 | }; |
| 369 | |
| 370 | cv::Mat image = bgr.clone(); |
| 371 | |
| 372 | for (size_t i = 0; i < objects.size(); i++) |
| 373 | { |
| 374 | const Object& obj = objects[i]; |
| 375 | |
| 376 | fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob, |
| 377 | obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height); |
| 378 | |
| 379 | cv::rectangle(image, obj.rect, cv::Scalar(255, 0, 0)); |
| 380 | |
| 381 | char text[256]; |
| 382 | sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100); |
| 383 | |
| 384 | int baseLine = 0; |
| 385 | cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine); |
| 386 | |
| 387 | int x = obj.rect.x; |
| 388 | int y = obj.rect.y - label_size.height - baseLine; |
| 389 | if (y < 0) |
| 390 | y = 0; |
| 391 | if (x + label_size.width > image.cols) |
| 392 | x = image.cols - label_size.width; |
| 393 | |
| 394 | cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)), |
| 395 | cv::Scalar(255, 255, 255), -1); |
| 396 | |
| 397 | cv::putText(image, text, cv::Point(x, y + label_size.height), |
| 398 | cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0)); |
| 399 | } |
| 400 | |
| 401 | cv::imshow("image", image); |
| 402 | cv::waitKey(0); |
| 403 | } |
| 404 | |
| 405 | int main(int argc, char** argv) |
| 406 | { |
| 407 | if (argc != 2) |
| 408 | { |
| 409 | fprintf(stderr, "Usage: %s [imagepath]\n", argv[0]); |
| 410 | return -1; |
| 411 | } |
| 412 | |
| 413 | const char* imagepath = argv[1]; |
| 414 | |
| 415 | cv::Mat m = cv::imread(imagepath, 1); |
| 416 | if (m.empty()) |
| 417 | { |
| 418 | fprintf(stderr, "cv::imread %s failed\n", imagepath); |
| 419 | return -1; |
| 420 | } |
| 421 | |
| 422 | std::vector<Object> objects; |
| 423 | detect_yolov7(m, objects); |
| 424 | |
| 425 | draw_objects(m, objects); |
| 426 | |
| 427 | return 0; |
| 428 | } |