| 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 | #include <opencv2/core/core.hpp> |
| 18 | #include <opencv2/highgui/highgui.hpp> |
| 19 | #include <opencv2/imgproc/imgproc.hpp> |
| 20 | |
| 21 | #if CV_MAJOR_VERSION >= 3 |
| 22 | #include <opencv2/videoio/videoio.hpp> |
| 23 | #endif |
| 24 | |
| 25 | #include <vector> |
| 26 | |
| 27 | #include <stdio.h> |
| 28 | |
| 29 | #define NCNN_PROFILING |
| 30 | #define YOLOV4_TINY //Using yolov4_tiny, if undef, using original yolov4 |
| 31 | |
| 32 | #ifdef NCNN_PROFILING |
| 33 | #include "benchmark.h" |
| 34 | #endif |
| 35 | |
| 36 | struct Object |
| 37 | { |
| 38 | cv::Rect_<float> rect; |
| 39 | int label; |
| 40 | float prob; |
| 41 | }; |
| 42 | |
| 43 | static int init_yolov4(ncnn::Net* yolov4, int* target_size) |
| 44 | { |
| 45 | /* --> Set the params you need for the ncnn inference <-- */ |
| 46 | |
| 47 | yolov4->opt.num_threads = 4; //You need to compile with libgomp for multi thread support |
| 48 | |
| 49 | yolov4->opt.use_vulkan_compute = true; //You need to compile with libvulkan for gpu support |
| 50 | |
| 51 | yolov4->opt.use_winograd_convolution = true; |
| 52 | yolov4->opt.use_sgemm_convolution = true; |
| 53 | yolov4->opt.use_fp16_packed = true; |
| 54 | yolov4->opt.use_fp16_storage = true; |
| 55 | yolov4->opt.use_fp16_arithmetic = true; |
| 56 | yolov4->opt.use_packing_layout = true; |
| 57 | yolov4->opt.use_shader_pack8 = false; |
| 58 | yolov4->opt.use_image_storage = false; |
| 59 | |
| 60 | /* --> End of setting params <-- */ |
| 61 | int ret = 0; |
| 62 | |
| 63 | // original pretrained model from https://github.com/AlexeyAB/darknet |
| 64 | // the ncnn model https://drive.google.com/drive/folders/1YzILvh0SKQPS_lrb33dmGNq7aVTKPWS0?usp=sharing |
| 65 | // the ncnn model https://github.com/nihui/ncnn-assets/tree/master/models |
| 66 | #ifdef YOLOV4_TINY |
| 67 | const char* yolov4_param = "yolov4-tiny-opt.param"; |
| 68 | const char* yolov4_model = "yolov4-tiny-opt.bin"; |
| 69 | *target_size = 416; |
| 70 | #else |
| 71 | const char* yolov4_param = "yolov4-opt.param"; |
| 72 | const char* yolov4_model = "yolov4-opt.bin"; |
| 73 | *target_size = 608; |
| 74 | #endif |
| 75 | |
| 76 | if (yolov4->load_param(yolov4_param)) |
| 77 | exit(-1); |
| 78 | if (yolov4->load_model(yolov4_model)) |
| 79 | exit(-1); |
| 80 | |
| 81 | return 0; |
| 82 | } |
| 83 | |
| 84 | static int detect_yolov4(const cv::Mat& bgr, std::vector<Object>& objects, int target_size, ncnn::Net* yolov4) |
| 85 | { |
| 86 | int img_w = bgr.cols; |
| 87 | int img_h = bgr.rows; |
| 88 | |
| 89 | ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, bgr.cols, bgr.rows, target_size, target_size); |
| 90 | |
| 91 | const float mean_vals[3] = {0, 0, 0}; |
| 92 | const float norm_vals[3] = {1 / 255.f, 1 / 255.f, 1 / 255.f}; |
| 93 | in.substract_mean_normalize(mean_vals, norm_vals); |
| 94 | |
| 95 | ncnn::Extractor ex = yolov4->create_extractor(); |
| 96 | |
| 97 | ex.input("data", in); |
| 98 | |
| 99 | ncnn::Mat out; |
| 100 | ex.extract("output", out); |
| 101 | |
| 102 | objects.clear(); |
| 103 | for (int i = 0; i < out.h; i++) |
| 104 | { |
| 105 | const float* values = out.row(i); |
| 106 | |
| 107 | Object object; |
| 108 | object.label = values[0]; |
| 109 | object.prob = values[1]; |
| 110 | object.rect.x = values[2] * img_w; |
| 111 | object.rect.y = values[3] * img_h; |
| 112 | object.rect.width = values[4] * img_w - object.rect.x; |
| 113 | object.rect.height = values[5] * img_h - object.rect.y; |
| 114 | |
| 115 | objects.push_back(object); |
| 116 | } |
| 117 | |
| 118 | return 0; |
| 119 | } |
| 120 | |
| 121 | static int draw_objects(const cv::Mat& bgr, const std::vector<Object>& objects, int is_streaming) |
| 122 | { |
| 123 | static const char* class_names[] = {"background", "person", "bicycle", |
| 124 | "car", "motorbike", "aeroplane", "bus", "train", "truck", |
| 125 | "boat", "traffic light", "fire hydrant", "stop sign", |
| 126 | "parking meter", "bench", "bird", "cat", "dog", "horse", |
| 127 | "sheep", "cow", "elephant", "bear", "zebra", "giraffe", |
| 128 | "backpack", "umbrella", "handbag", "tie", "suitcase", |
| 129 | "frisbee", "skis", "snowboard", "sports ball", "kite", |
| 130 | "baseball bat", "baseball glove", "skateboard", "surfboard", |
| 131 | "tennis racket", "bottle", "wine glass", "cup", "fork", |
| 132 | "knife", "spoon", "bowl", "banana", "apple", "sandwich", |
| 133 | "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", |
| 134 | "cake", "chair", "sofa", "pottedplant", "bed", "diningtable", |
| 135 | "toilet", "tvmonitor", "laptop", "mouse", "remote", "keyboard", |
| 136 | "cell phone", "microwave", "oven", "toaster", "sink", |
| 137 | "refrigerator", "book", "clock", "vase", "scissors", |
| 138 | "teddy bear", "hair drier", "toothbrush" |
| 139 | }; |
| 140 | |
| 141 | cv::Mat image = bgr.clone(); |
| 142 | |
| 143 | for (size_t i = 0; i < objects.size(); i++) |
| 144 | { |
| 145 | const Object& obj = objects[i]; |
| 146 | |
| 147 | fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob, |
| 148 | obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height); |
| 149 | |
| 150 | cv::rectangle(image, obj.rect, cv::Scalar(255, 0, 0)); |
| 151 | |
| 152 | char text[256]; |
| 153 | sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100); |
| 154 | |
| 155 | int baseLine = 0; |
| 156 | cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine); |
| 157 | |
| 158 | int x = obj.rect.x; |
| 159 | int y = obj.rect.y - label_size.height - baseLine; |
| 160 | if (y < 0) |
| 161 | y = 0; |
| 162 | if (x + label_size.width > image.cols) |
| 163 | x = image.cols - label_size.width; |
| 164 | |
| 165 | cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)), |
| 166 | cv::Scalar(255, 255, 255), -1); |
| 167 | |
| 168 | cv::putText(image, text, cv::Point(x, y + label_size.height), |
| 169 | cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0)); |
| 170 | } |
| 171 | |
| 172 | cv::imshow("image", image); |
| 173 | |
| 174 | if (is_streaming) |
| 175 | { |
| 176 | cv::waitKey(1); |
| 177 | } |
| 178 | else |
| 179 | { |
| 180 | cv::waitKey(0); |
| 181 | } |
| 182 | |
| 183 | return 0; |
| 184 | } |
| 185 | |
| 186 | int main(int argc, char** argv) |
| 187 | { |
| 188 | cv::Mat frame; |
| 189 | std::vector<Object> objects; |
| 190 | |
| 191 | cv::VideoCapture cap; |
| 192 | |
| 193 | ncnn::Net yolov4; |
| 194 | |
| 195 | const char* devicepath; |
| 196 | |
| 197 | int target_size = 0; |
| 198 | int is_streaming = 0; |
| 199 | |
| 200 | if (argc < 2) |
| 201 | { |
| 202 | fprintf(stderr, "Usage: %s [v4l input device or image]\n", argv[0]); |
| 203 | return -1; |
| 204 | } |
| 205 | |
| 206 | devicepath = argv[1]; |
| 207 | |
| 208 | #ifdef NCNN_PROFILING |
| 209 | double t_load_start = ncnn::get_current_time(); |
| 210 | #endif |
| 211 | |
| 212 | int ret = init_yolov4(&yolov4, &target_size); //We load model and param first! |
| 213 | if (ret != 0) |
| 214 | { |
| 215 | fprintf(stderr, "Failed to load model or param, error %d", ret); |
| 216 | return -1; |
| 217 | } |
| 218 | |
| 219 | #ifdef NCNN_PROFILING |
| 220 | double t_load_end = ncnn::get_current_time(); |
| 221 | fprintf(stdout, "NCNN Init time %.02lfms\n", t_load_end - t_load_start); |
| 222 | #endif |
| 223 | |
| 224 | if (strstr(devicepath, "/dev/video") == NULL) |
| 225 | { |
| 226 | frame = cv::imread(argv[1], 1); |
| 227 | if (frame.empty()) |
| 228 | { |
| 229 | fprintf(stderr, "Failed to read image %s.\n", argv[1]); |
| 230 | return -1; |
| 231 | } |
| 232 | } |
| 233 | else |
| 234 | { |
| 235 | cap.open(devicepath); |
| 236 | |
| 237 | if (!cap.isOpened()) |
| 238 | { |
| 239 | fprintf(stderr, "Failed to open %s", devicepath); |
| 240 | return -1; |
| 241 | } |
| 242 | |
| 243 | cap >> frame; |
| 244 | |
| 245 | if (frame.empty()) |
| 246 | { |
| 247 | fprintf(stderr, "Failed to read from device %s.\n", devicepath); |
| 248 | return -1; |
| 249 | } |
| 250 | |
| 251 | is_streaming = 1; |
| 252 | } |
| 253 | |
| 254 | while (1) |
| 255 | { |
| 256 | if (is_streaming) |
| 257 | { |
| 258 | #ifdef NCNN_PROFILING |
| 259 | double t_capture_start = ncnn::get_current_time(); |
| 260 | #endif |
| 261 | |
| 262 | cap >> frame; |
| 263 | |
| 264 | #ifdef NCNN_PROFILING |
| 265 | double t_capture_end = ncnn::get_current_time(); |
| 266 | fprintf(stdout, "NCNN OpenCV capture time %.02lfms\n", t_capture_end - t_capture_start); |
| 267 | #endif |
| 268 | if (frame.empty()) |
| 269 | { |
| 270 | fprintf(stderr, "OpenCV Failed to Capture from device %s\n", devicepath); |
| 271 | return -1; |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | #ifdef NCNN_PROFILING |
| 276 | double t_detect_start = ncnn::get_current_time(); |
| 277 | #endif |
| 278 | |
| 279 | detect_yolov4(frame, objects, target_size, &yolov4); //Create an extractor and run detection |
| 280 | |
| 281 | #ifdef NCNN_PROFILING |
| 282 | double t_detect_end = ncnn::get_current_time(); |
| 283 | fprintf(stdout, "NCNN detection time %.02lfms\n", t_detect_end - t_detect_start); |
| 284 | #endif |
| 285 | |
| 286 | #ifdef NCNN_PROFILING |
| 287 | double t_draw_start = ncnn::get_current_time(); |
| 288 | #endif |
| 289 | |
| 290 | draw_objects(frame, objects, is_streaming); //Draw detection results on opencv image |
| 291 | |
| 292 | #ifdef NCNN_PROFILING |
| 293 | double t_draw_end = ncnn::get_current_time(); |
| 294 | fprintf(stdout, "NCNN OpenCV draw result time %.02lfms\n", t_draw_end - t_draw_start); |
| 295 | #endif |
| 296 | |
| 297 | if (!is_streaming) |
| 298 | { //If it is a still image, exit! |
| 299 | return 0; |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | return 0; |
| 304 | } |