main.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. // Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // reference from https://github.com/RangiLyu/nanodet
  15. #include <iostream>
  16. #include <opencv2/core/core.hpp>
  17. #include <opencv2/highgui/highgui.hpp>
  18. #include <opencv2/imgproc/imgproc.hpp>
  19. #define image_size 416
  20. #include "keypoint_detector.h"
  21. #include "picodet_openvino.h"
  22. using namespace PaddleDetection;
  23. struct object_rect {
  24. int x;
  25. int y;
  26. int width;
  27. int height;
  28. };
  29. int resize_uniform(cv::Mat& src,
  30. cv::Mat& dst,
  31. cv::Size dst_size,
  32. object_rect& effect_area) {
  33. int w = src.cols;
  34. int h = src.rows;
  35. int dst_w = dst_size.width;
  36. int dst_h = dst_size.height;
  37. dst = cv::Mat(cv::Size(dst_w, dst_h), CV_8UC3, cv::Scalar(0));
  38. float ratio_src = w * 1.0 / h;
  39. float ratio_dst = dst_w * 1.0 / dst_h;
  40. int tmp_w = 0;
  41. int tmp_h = 0;
  42. if (ratio_src > ratio_dst) {
  43. tmp_w = dst_w;
  44. tmp_h = floor((dst_w * 1.0 / w) * h);
  45. } else if (ratio_src < ratio_dst) {
  46. tmp_h = dst_h;
  47. tmp_w = floor((dst_h * 1.0 / h) * w);
  48. } else {
  49. cv::resize(src, dst, dst_size);
  50. effect_area.x = 0;
  51. effect_area.y = 0;
  52. effect_area.width = dst_w;
  53. effect_area.height = dst_h;
  54. return 0;
  55. }
  56. cv::Mat tmp;
  57. cv::resize(src, tmp, cv::Size(tmp_w, tmp_h));
  58. if (tmp_w != dst_w) {
  59. int index_w = floor((dst_w - tmp_w) / 2.0);
  60. for (int i = 0; i < dst_h; i++) {
  61. memcpy(dst.data + i * dst_w * 3 + index_w * 3,
  62. tmp.data + i * tmp_w * 3,
  63. tmp_w * 3);
  64. }
  65. effect_area.x = index_w;
  66. effect_area.y = 0;
  67. effect_area.width = tmp_w;
  68. effect_area.height = tmp_h;
  69. } else if (tmp_h != dst_h) {
  70. int index_h = floor((dst_h - tmp_h) / 2.0);
  71. memcpy(dst.data + index_h * dst_w * 3, tmp.data, tmp_w * tmp_h * 3);
  72. effect_area.x = 0;
  73. effect_area.y = index_h;
  74. effect_area.width = tmp_w;
  75. effect_area.height = tmp_h;
  76. } else {
  77. printf("error\n");
  78. }
  79. return 0;
  80. }
  81. const int color_list[80][3] = {
  82. {216, 82, 24}, {236, 176, 31}, {125, 46, 141}, {118, 171, 47},
  83. {76, 189, 237}, {238, 19, 46}, {76, 76, 76}, {153, 153, 153},
  84. {255, 0, 0}, {255, 127, 0}, {190, 190, 0}, {0, 255, 0},
  85. {0, 0, 255}, {170, 0, 255}, {84, 84, 0}, {84, 170, 0},
  86. {84, 255, 0}, {170, 84, 0}, {170, 170, 0}, {170, 255, 0},
  87. {255, 84, 0}, {255, 170, 0}, {255, 255, 0}, {0, 84, 127},
  88. {0, 170, 127}, {0, 255, 127}, {84, 0, 127}, {84, 84, 127},
  89. {84, 170, 127}, {84, 255, 127}, {170, 0, 127}, {170, 84, 127},
  90. {170, 170, 127}, {170, 255, 127}, {255, 0, 127}, {255, 84, 127},
  91. {255, 170, 127}, {255, 255, 127}, {0, 84, 255}, {0, 170, 255},
  92. {0, 255, 255}, {84, 0, 255}, {84, 84, 255}, {84, 170, 255},
  93. {84, 255, 255}, {170, 0, 255}, {170, 84, 255}, {170, 170, 255},
  94. {170, 255, 255}, {255, 0, 255}, {255, 84, 255}, {255, 170, 255},
  95. {42, 0, 0}, {84, 0, 0}, {127, 0, 0}, {170, 0, 0},
  96. {212, 0, 0}, {255, 0, 0}, {0, 42, 0}, {0, 84, 0},
  97. {0, 127, 0}, {0, 170, 0}, {0, 212, 0}, {0, 255, 0},
  98. {0, 0, 42}, {0, 0, 84}, {0, 0, 127}, {0, 0, 170},
  99. {0, 0, 212}, {0, 0, 255}, {0, 0, 0}, {36, 36, 36},
  100. {72, 72, 72}, {109, 109, 109}, {145, 145, 145}, {182, 182, 182},
  101. {218, 218, 218}, {0, 113, 188}, {80, 182, 188}, {127, 127, 0},
  102. };
  103. void draw_bboxes(const cv::Mat& bgr,
  104. const std::vector<BoxInfo>& bboxes,
  105. object_rect effect_roi) {
  106. static const char* class_names[] = {
  107. "person", "bicycle", "car",
  108. "motorcycle", "airplane", "bus",
  109. "train", "truck", "boat",
  110. "traffic light", "fire hydrant", "stop sign",
  111. "parking meter", "bench", "bird",
  112. "cat", "dog", "horse",
  113. "sheep", "cow", "elephant",
  114. "bear", "zebra", "giraffe",
  115. "backpack", "umbrella", "handbag",
  116. "tie", "suitcase", "frisbee",
  117. "skis", "snowboard", "sports ball",
  118. "kite", "baseball bat", "baseball glove",
  119. "skateboard", "surfboard", "tennis racket",
  120. "bottle", "wine glass", "cup",
  121. "fork", "knife", "spoon",
  122. "bowl", "banana", "apple",
  123. "sandwich", "orange", "broccoli",
  124. "carrot", "hot dog", "pizza",
  125. "donut", "cake", "chair",
  126. "couch", "potted plant", "bed",
  127. "dining table", "toilet", "tv",
  128. "laptop", "mouse", "remote",
  129. "keyboard", "cell phone", "microwave",
  130. "oven", "toaster", "sink",
  131. "refrigerator", "book", "clock",
  132. "vase", "scissors", "teddy bear",
  133. "hair drier", "toothbrush"};
  134. cv::Mat image = bgr.clone();
  135. int src_w = image.cols;
  136. int src_h = image.rows;
  137. int dst_w = effect_roi.width;
  138. int dst_h = effect_roi.height;
  139. float width_ratio = (float)src_w / (float)dst_w;
  140. float height_ratio = (float)src_h / (float)dst_h;
  141. for (size_t i = 0; i < bboxes.size(); i++) {
  142. const BoxInfo& bbox = bboxes[i];
  143. cv::Scalar color = cv::Scalar(color_list[bbox.label][0],
  144. color_list[bbox.label][1],
  145. color_list[bbox.label][2]);
  146. cv::rectangle(image,
  147. cv::Rect(cv::Point((bbox.x1 - effect_roi.x) * width_ratio,
  148. (bbox.y1 - effect_roi.y) * height_ratio),
  149. cv::Point((bbox.x2 - effect_roi.x) * width_ratio,
  150. (bbox.y2 - effect_roi.y) * height_ratio)),
  151. color);
  152. char text[256];
  153. sprintf(text, "%s %.1f%%", class_names[bbox.label], bbox.score * 100);
  154. int baseLine = 0;
  155. cv::Size label_size =
  156. cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.4, 1, &baseLine);
  157. int x = (bbox.x1 - effect_roi.x) * width_ratio;
  158. int y =
  159. (bbox.y1 - effect_roi.y) * height_ratio - label_size.height - baseLine;
  160. if (y < 0) y = 0;
  161. if (x + label_size.width > image.cols) x = image.cols - label_size.width;
  162. cv::rectangle(
  163. image,
  164. cv::Rect(cv::Point(x, y),
  165. cv::Size(label_size.width, label_size.height + baseLine)),
  166. color,
  167. -1);
  168. cv::putText(image,
  169. text,
  170. cv::Point(x, y + label_size.height),
  171. cv::FONT_HERSHEY_SIMPLEX,
  172. 0.4,
  173. cv::Scalar(255, 255, 255));
  174. }
  175. cv::imwrite("../predict.jpg", image);
  176. }
  177. std::vector<BoxInfo> coordsback(const cv::Mat image,
  178. const object_rect effect_roi,
  179. const std::vector<BoxInfo>& bboxes) {
  180. int src_w = image.cols;
  181. int src_h = image.rows;
  182. int dst_w = effect_roi.width;
  183. int dst_h = effect_roi.height;
  184. float width_ratio = (float)src_w / (float)dst_w;
  185. float height_ratio = (float)src_h / (float)dst_h;
  186. std::vector<BoxInfo> bboxes_oimg;
  187. for (int i = 0; i < bboxes.size(); i++) {
  188. auto bbox = bboxes[i];
  189. bbox.x1 = (bbox.x1 - effect_roi.x) * width_ratio;
  190. bbox.y1 = (bbox.y1 - effect_roi.y) * height_ratio;
  191. bbox.x2 = (bbox.x2 - effect_roi.x) * width_ratio;
  192. bbox.y2 = (bbox.y2 - effect_roi.y) * height_ratio;
  193. bboxes_oimg.emplace_back(bbox);
  194. }
  195. return bboxes_oimg;
  196. }
  197. void image_infer_kpts(KeyPointDetector* kpts_detector,
  198. cv::Mat image,
  199. const object_rect effect_roi,
  200. const std::vector<BoxInfo>& results,
  201. std::string img_name = "kpts_vis",
  202. bool save_img = true) {
  203. std::vector<cv::Mat> cropimgs;
  204. std::vector<std::vector<float>> center_bs;
  205. std::vector<std::vector<float>> scale_bs;
  206. std::vector<KeyPointResult> kpts_results;
  207. auto results_oimg = coordsback(image, effect_roi, results);
  208. for (int i = 0; i < results_oimg.size(); i++) {
  209. auto rect = results_oimg[i];
  210. if (rect.label == 0) {
  211. cv::Mat cropimg;
  212. std::vector<float> center, scale;
  213. std::vector<int> area = {static_cast<int>(rect.x1),
  214. static_cast<int>(rect.y1),
  215. static_cast<int>(rect.x2),
  216. static_cast<int>(rect.y2)};
  217. CropImg(image, cropimg, area, center, scale);
  218. cropimgs.emplace_back(cropimg);
  219. center_bs.emplace_back(center);
  220. scale_bs.emplace_back(scale);
  221. }
  222. if (cropimgs.size() == 1 ||
  223. (cropimgs.size() > 0 && i == results_oimg.size() - 1)) {
  224. kpts_detector->Predict(cropimgs, center_bs, scale_bs, &kpts_results);
  225. cropimgs.clear();
  226. center_bs.clear();
  227. scale_bs.clear();
  228. }
  229. }
  230. std::vector<int> compression_params;
  231. compression_params.push_back(cv::IMWRITE_JPEG_QUALITY);
  232. compression_params.push_back(95);
  233. std::string kpts_savepath =
  234. "keypoint_" + img_name.substr(img_name.find_last_of('/') + 1);
  235. cv::Mat kpts_vis_img =
  236. VisualizeKptsResult(image, kpts_results, {0, 255, 0}, 0.1);
  237. if (save_img) {
  238. cv::imwrite(kpts_savepath, kpts_vis_img, compression_params);
  239. printf("Visualized output saved as %s\n", kpts_savepath.c_str());
  240. } else {
  241. cv::imshow("image", kpts_vis_img);
  242. }
  243. }
  244. int image_demo(PicoDet& detector,
  245. KeyPointDetector* kpts_detector,
  246. const char* imagepath) {
  247. std::vector<std::string> filenames;
  248. cv::glob(imagepath, filenames, false);
  249. for (auto img_name : filenames) {
  250. cv::Mat image = cv::imread(img_name);
  251. if (image.empty()) {
  252. return -1;
  253. }
  254. object_rect effect_roi;
  255. cv::Mat resized_img;
  256. resize_uniform(
  257. image, resized_img, cv::Size(image_size, image_size), effect_roi);
  258. auto results = detector.detect(resized_img, 0.4, 0.5);
  259. if (kpts_detector) {
  260. image_infer_kpts(kpts_detector, image, effect_roi, results, img_name);
  261. }
  262. }
  263. return 0;
  264. }
  265. int webcam_demo(PicoDet& detector,
  266. KeyPointDetector* kpts_detector,
  267. int cam_id) {
  268. cv::Mat image;
  269. cv::VideoCapture cap(cam_id);
  270. while (true) {
  271. cap >> image;
  272. object_rect effect_roi;
  273. cv::Mat resized_img;
  274. resize_uniform(
  275. image, resized_img, cv::Size(image_size, image_size), effect_roi);
  276. auto results = detector.detect(resized_img, 0.4, 0.5);
  277. if (kpts_detector) {
  278. image_infer_kpts(kpts_detector, image, effect_roi, results, "", false);
  279. }
  280. }
  281. return 0;
  282. }
  283. int video_demo(PicoDet& detector,
  284. KeyPointDetector* kpts_detector,
  285. const char* path) {
  286. cv::Mat image;
  287. cv::VideoCapture cap(path);
  288. while (true) {
  289. cap >> image;
  290. object_rect effect_roi;
  291. cv::Mat resized_img;
  292. resize_uniform(
  293. image, resized_img, cv::Size(image_size, image_size), effect_roi);
  294. auto results = detector.detect(resized_img, 0.4, 0.5);
  295. if (kpts_detector) {
  296. image_infer_kpts(kpts_detector, image, effect_roi, results, "", false);
  297. }
  298. }
  299. return 0;
  300. }
  301. int benchmark(KeyPointDetector* kpts_detector) {
  302. int loop_num = 100;
  303. int warm_up = 8;
  304. double time_min = DBL_MAX;
  305. double time_max = -DBL_MAX;
  306. double time_avg = 0;
  307. cv::Mat image(256, 192, CV_8UC3, cv::Scalar(1, 1, 1));
  308. std::vector<float> center = {128, 96};
  309. std::vector<float> scale = {256, 192};
  310. std::vector<cv::Mat> cropimgs = {image};
  311. std::vector<std::vector<float>> center_bs = {center};
  312. std::vector<std::vector<float>> scale_bs = {scale};
  313. std::vector<KeyPointResult> kpts_results;
  314. for (int i = 0; i < warm_up + loop_num; i++) {
  315. auto start = std::chrono::steady_clock::now();
  316. std::vector<BoxInfo> results;
  317. kpts_detector->Predict(cropimgs, center_bs, scale_bs, &kpts_results);
  318. auto end = std::chrono::steady_clock::now();
  319. std::chrono::duration<double> elapsed = end - start;
  320. double time = elapsed.count();
  321. if (i >= warm_up) {
  322. time_min = (std::min)(time_min, time);
  323. time_max = (std::max)(time_max, time);
  324. time_avg += time;
  325. }
  326. }
  327. time_avg /= loop_num;
  328. fprintf(stderr,
  329. "%20s min = %7.4f max = %7.4f avg = %7.4f\n",
  330. "tinypose",
  331. time_min,
  332. time_max,
  333. time_avg);
  334. return 0;
  335. }
  336. int main(int argc, char** argv) {
  337. if (argc != 3) {
  338. fprintf(stderr,
  339. "usage: %s [mode] [path]. \n For webcam mode=0, path is cam id; \n "
  340. "For image demo, mode=1, path=xxx/xxx/*.jpg; \n For video, mode=2; "
  341. "\n For benchmark, mode=3 path=0.\n",
  342. argv[0]);
  343. return -1;
  344. }
  345. std::cout << "start init model" << std::endl;
  346. auto detector = PicoDet("./weight/picodet_m_416.xml");
  347. auto kpts_detector =
  348. new KeyPointDetector("./weight/tinypose256_git2-sim.xml", 256, 192);
  349. std::cout << "success" << std::endl;
  350. int mode = atoi(argv[1]);
  351. switch (mode) {
  352. case 0: {
  353. int cam_id = atoi(argv[2]);
  354. webcam_demo(detector, kpts_detector, cam_id);
  355. break;
  356. }
  357. case 1: {
  358. const char* images = argv[2];
  359. image_demo(detector, kpts_detector, images);
  360. break;
  361. }
  362. case 2: {
  363. const char* path = argv[2];
  364. video_demo(detector, kpts_detector, path);
  365. break;
  366. }
  367. case 3: {
  368. benchmark(kpts_detector);
  369. break;
  370. }
  371. default: {
  372. fprintf(stderr,
  373. "usage: %s [mode] [path]. \n For webcam mode=0, path is cam id; "
  374. "\n For image demo, mode=1, path=xxx/xxx/*.jpg; \n For video, "
  375. "mode=2; \n For benchmark, mode=3 path=0.\n",
  376. argv[0]);
  377. break;
  378. }
  379. }
  380. delete kpts_detector;
  381. kpts_detector = nullptr;
  382. }