meter.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. // Copyright (c) 2020 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. #include <glog/logging.h>
  15. #include <omp.h>
  16. #include <algorithm>
  17. #include <chrono> // NOLINT
  18. #include <iostream>
  19. #include <vector>
  20. #include <utility>
  21. #include <limits>
  22. #include <opencv2/opencv.hpp>
  23. #include <opencv2/highgui.hpp>
  24. #include <opencv2/core/core.hpp>
  25. #include "meter/global.h"
  26. #include "meter/readvalue.h"
  27. #include "include/paddlex/paddlex.h"
  28. #include "include/paddlex/visualize.h"
  29. using namespace std::chrono; // NOLINT
  30. DEFINE_string(det_model_dir, "", "Path of detection inference model");
  31. DEFINE_string(seg_model_dir, "", "Path of segmentation inference model");
  32. DEFINE_bool(use_gpu, false, "Infering with GPU or CPU");
  33. DEFINE_bool(use_trt, false, "Infering with TensorRT");
  34. DEFINE_bool(use_camera, false, "Infering with Camera");
  35. DEFINE_bool(use_erode, true, "Eroding predicted label map");
  36. DEFINE_int32(gpu_id, 0, "GPU card id");
  37. DEFINE_int32(camera_id, 0, "Camera id");
  38. DEFINE_int32(thread_num,
  39. omp_get_num_procs(),
  40. "Number of preprocessing threads");
  41. DEFINE_int32(erode_kernel, true, "Eroding kernel size");
  42. DEFINE_int32(seg_batch_size, 2, "Batch size of segmentation infering");
  43. DEFINE_string(det_key, "", "Detector key of encryption");
  44. DEFINE_string(seg_key, "", "Segmenter model key of encryption");
  45. DEFINE_string(image, "", "Path of test image file");
  46. DEFINE_string(image_list, "", "Path of test image list file");
  47. DEFINE_string(save_dir, "output", "Path to save visualized image");
  48. void predict(const cv::Mat &input_image, PaddleX::Model *det_model,
  49. PaddleX::Model *seg_model, const std::string save_dir,
  50. const std::string image_path, const bool use_erode,
  51. const int erode_kernel, const int thread_num,
  52. const int seg_batch_size) {
  53. PaddleX::DetResult det_result;
  54. det_model->predict(input_image, &det_result);
  55. int meter_num = det_result.boxes.size();
  56. if (!meter_num) {
  57. std::cout << "Don't find any meter." << std::endl;
  58. return;
  59. }
  60. std::vector<std::vector<int64_t>> seg_result(meter_num);
  61. for (int i = 0; i < meter_num; i += seg_batch_size) {
  62. int im_vec_size =
  63. std::min(static_cast<int>(meter_num), i + seg_batch_size);
  64. std::vector<cv::Mat> meters_image(im_vec_size - i);
  65. int batch_thread_num = std::min(thread_num, im_vec_size - i);
  66. #pragma omp parallel for num_threads(batch_thread_num)
  67. for (int j = i; j < im_vec_size; ++j) {
  68. int left = static_cast<int>(det_result.boxes[j].coordinate[0]);
  69. int top = static_cast<int>(det_result.boxes[j].coordinate[1]);
  70. int width = static_cast<int>(det_result.boxes[j].coordinate[2]);
  71. int height = static_cast<int>(det_result.boxes[j].coordinate[3]);
  72. int right = left + width - 1;
  73. int bottom = top + height - 1;
  74. cv::Mat sub_image = input_image(
  75. cv::Range(top, bottom + 1), cv::Range(left, right + 1));
  76. float scale_x =
  77. static_cast<float>(METER_SHAPE[0]) / static_cast<float>(sub_image.cols);
  78. float scale_y =
  79. static_cast<float>(METER_SHAPE[1]) / static_cast<float>(sub_image.rows);
  80. cv::resize(sub_image,
  81. sub_image,
  82. cv::Size(),
  83. scale_x,
  84. scale_y,
  85. cv::INTER_LINEAR);
  86. meters_image[j - i] = std::move(sub_image);
  87. }
  88. std::vector<PaddleX::SegResult> batch_result(im_vec_size - i);
  89. seg_model->predict(meters_image, &batch_result, batch_thread_num);
  90. #pragma omp parallel for num_threads(batch_thread_num)
  91. for (int j = i; j < im_vec_size; ++j) {
  92. if (use_erode) {
  93. cv::Mat kernel(4, 4, CV_8U, cv::Scalar(1));
  94. std::vector<uint8_t> label_map(
  95. batch_result[j - i].label_map.data.begin(),
  96. batch_result[j - i].label_map.data.end());
  97. cv::Mat mask(batch_result[j - i].label_map.shape[0],
  98. batch_result[j - i].label_map.shape[1],
  99. CV_8UC1,
  100. label_map.data());
  101. cv::erode(mask, mask, kernel);
  102. std::vector<int64_t> map;
  103. if (mask.isContinuous()) {
  104. map.assign(mask.data, mask.data + mask.total() * mask.channels());
  105. } else {
  106. for (int r = 0; r < mask.rows; r++) {
  107. map.insert(map.end(),
  108. mask.ptr<int64_t>(r),
  109. mask.ptr<int64_t>(r) + mask.cols * mask.channels());
  110. }
  111. }
  112. seg_result[j] = std::move(map);
  113. } else {
  114. seg_result[j] = std::move(batch_result[j - i].label_map.data);
  115. }
  116. }
  117. }
  118. std::vector<READ_RESULT> read_results(meter_num);
  119. int all_thread_num = std::min(thread_num, meter_num);
  120. read_process(seg_result, &read_results, all_thread_num);
  121. cv::Mat output_image = input_image.clone();
  122. for (int i = 0; i < meter_num; i++) {
  123. float result = 0;;
  124. if (read_results[i].scale_num > TYPE_THRESHOLD) {
  125. result = read_results[i].scales * meter_config[0].scale_value;
  126. } else {
  127. result = read_results[i].scales * meter_config[1].scale_value;
  128. }
  129. std::cout << "-- Meter " << i
  130. << " -- result: " << result
  131. << " --" << std::endl;
  132. int lx = static_cast<int>(det_result.boxes[i].coordinate[0]);
  133. int ly = static_cast<int>(det_result.boxes[i].coordinate[1]);
  134. int w = static_cast<int>(det_result.boxes[i].coordinate[2]);
  135. int h = static_cast<int>(det_result.boxes[i].coordinate[3]);
  136. cv::Rect bounding_box = cv::Rect(lx, ly, w, h) &
  137. cv::Rect(0, 0, output_image.cols, output_image.rows);
  138. if (w > 0 && h > 0) {
  139. cv::Scalar color = cv::Scalar(237, 189, 101);
  140. cv::rectangle(output_image, bounding_box, color);
  141. cv::rectangle(output_image,
  142. cv::Point2d(lx, ly),
  143. cv::Point2d(lx + w, ly - 30),
  144. color, -1);
  145. std::string class_name = "Meter";
  146. cv::putText(output_image,
  147. class_name + " " + std::to_string(result),
  148. cv::Point2d(lx, ly-5),
  149. cv::FONT_HERSHEY_SIMPLEX,
  150. 1, cv::Scalar(255, 255, 255), 2);
  151. }
  152. }
  153. cv::Mat result_image;
  154. cv::Size resize_size(RESULT_SHAPE[0], RESULT_SHAPE[1]);
  155. cv::resize(output_image, result_image, resize_size, 0, 0, cv::INTER_LINEAR);
  156. std::string save_path = PaddleX::generate_save_path(save_dir, image_path);
  157. cv::imwrite(save_path, result_image);
  158. return;
  159. }
  160. int main(int argc, char **argv) {
  161. google::ParseCommandLineFlags(&argc, &argv, true);
  162. if (FLAGS_det_model_dir == "") {
  163. std::cerr << "--det_model_dir need to be defined" << std::endl;
  164. return -1;
  165. }
  166. if (FLAGS_seg_model_dir == "") {
  167. std::cerr << "--seg_model_dir need to be defined" << std::endl;
  168. return -1;
  169. }
  170. if (FLAGS_image == "" & FLAGS_image_list == "" & FLAGS_use_camera == false) {
  171. std::cerr << "--image or --image_list need to be defined "
  172. << "when the camera is not been used" << std::endl;
  173. return -1;
  174. }
  175. // 加载模型
  176. PaddleX::Model det_model;
  177. det_model.Init(FLAGS_det_model_dir, FLAGS_use_gpu, FLAGS_use_trt,
  178. FLAGS_gpu_id, FLAGS_det_key);
  179. PaddleX::Model seg_model;
  180. seg_model.Init(FLAGS_seg_model_dir, FLAGS_use_gpu, FLAGS_use_trt,
  181. FLAGS_gpu_id, FLAGS_seg_key);
  182. double total_running_time_s = 0.0;
  183. double total_imread_time_s = 0.0;
  184. int imgs = 1;
  185. if (FLAGS_use_camera) {
  186. cv::VideoCapture cap(FLAGS_camera_id);
  187. cap.set(CV_CAP_PROP_FRAME_WIDTH, IMAGE_SHAPE[0]);
  188. cap.set(CV_CAP_PROP_FRAME_HEIGHT, IMAGE_SHAPE[1]);
  189. if (!cap.isOpened()) {
  190. std::cout << "Open the camera unsuccessfully." << std::endl;
  191. return -1;
  192. }
  193. std::cout << "Open the camera successfully." << std::endl;
  194. while (1) {
  195. auto start = system_clock::now();
  196. cv::Mat im;
  197. cap >> im;
  198. auto imread_end = system_clock::now();
  199. std::cout << "-------------------------" << std::endl;
  200. std::cout << "Got a camera image." << std::endl;
  201. std::string ext_name = ".jpg";
  202. predict(im, &det_model, &seg_model, FLAGS_save_dir,
  203. std::to_string(imgs) + ext_name, FLAGS_use_erode,
  204. FLAGS_erode_kernel, FLAGS_thread_num, FLAGS_seg_batch_size);
  205. imgs++;
  206. auto imread_duration = duration_cast<microseconds>(imread_end - start);
  207. total_imread_time_s += static_cast<double>(imread_duration.count()) *
  208. microseconds::period::num /
  209. microseconds::period::den;
  210. auto end = system_clock::now();
  211. auto duration = duration_cast<microseconds>(end - start);
  212. total_running_time_s += static_cast<double>(duration.count()) *
  213. microseconds::period::num /
  214. microseconds::period::den;
  215. }
  216. cap.release();
  217. cv::destroyAllWindows();
  218. } else {
  219. if (FLAGS_image_list != "") {
  220. std::ifstream inf(FLAGS_image_list);
  221. if (!inf) {
  222. std::cerr << "Fail to open file " << FLAGS_image_list << std::endl;
  223. return -1;
  224. }
  225. std::string image_path;
  226. while (getline(inf, image_path)) {
  227. auto start = system_clock::now();
  228. cv::Mat im = cv::imread(image_path, 1);
  229. imgs++;
  230. auto imread_end = system_clock::now();
  231. predict(im, &det_model, &seg_model, FLAGS_save_dir,
  232. image_path, FLAGS_use_erode, FLAGS_erode_kernel,
  233. FLAGS_thread_num, FLAGS_seg_batch_size);
  234. auto imread_duration = duration_cast<microseconds>(imread_end - start);
  235. total_imread_time_s += static_cast<double>(imread_duration.count()) *
  236. microseconds::period::num /
  237. microseconds::period::den;
  238. auto end = system_clock::now();
  239. auto duration = duration_cast<microseconds>(end - start);
  240. total_running_time_s += static_cast<double>(duration.count()) *
  241. microseconds::period::num /
  242. microseconds::period::den;
  243. }
  244. } else {
  245. auto start = system_clock::now();
  246. cv::Mat im = cv::imread(FLAGS_image, 1);
  247. auto imread_end = system_clock::now();
  248. predict(im, &det_model, &seg_model, FLAGS_save_dir,
  249. FLAGS_image, FLAGS_use_erode, FLAGS_erode_kernel,
  250. FLAGS_thread_num, FLAGS_seg_batch_size);
  251. auto imread_duration = duration_cast<microseconds>(imread_end - start);
  252. total_imread_time_s += static_cast<double>(imread_duration.count()) *
  253. microseconds::period::num /
  254. microseconds::period::den;
  255. auto end = system_clock::now();
  256. auto duration = duration_cast<microseconds>(end - start);
  257. total_running_time_s += static_cast<double>(duration.count()) *
  258. microseconds::period::num /
  259. microseconds::period::den;
  260. }
  261. }
  262. std::cout << "Total running time: " << total_running_time_s
  263. << " s, average running time: " << total_running_time_s / imgs
  264. << " s/img, total read img time: " << total_imread_time_s
  265. << " s, average read time: " << total_imread_time_s / imgs
  266. << " s/img" << std::endl;
  267. return 0;
  268. }