You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

yolov4.cpp 9.4 kB

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