main_keypoint.cc 21.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//   Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <glog/logging.h>

Z
zhiboniu 已提交
17 18 19 20
#include <math.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <algorithm>
21
#include <iostream>
Z
zhiboniu 已提交
22
#include <numeric>
23 24 25 26 27 28 29 30 31 32
#include <string>
#include <vector>

#ifdef _WIN32
#include <direct.h>
#include <io.h>
#elif LINUX
#include <stdarg.h>
#endif

Z
zhiboniu 已提交
33
#include <gflags/gflags.h>
34
#include "include/keypoint_detector.h"
Z
zhiboniu 已提交
35
#include "include/object_detector.h"
36 37 38
#include "include/preprocess_op.h"

DEFINE_string(model_dir, "", "Path of object detector inference model");
Z
zhiboniu 已提交
39 40 41
DEFINE_string(model_dir_keypoint,
              "",
              "Path of keypoint detector inference model");
42
DEFINE_string(image_file, "", "Path of input image");
Z
zhiboniu 已提交
43 44 45
DEFINE_string(image_dir,
              "",
              "Dir of input image, `image_file` has a higher priority.");
46 47
DEFINE_int32(batch_size, 1, "batch_size of object detector");
DEFINE_int32(batch_size_keypoint, 8, "batch_size of keypoint detector");
Z
zhiboniu 已提交
48 49 50 51
DEFINE_string(
    video_file,
    "",
    "Path of input video, `video_file` or `camera_id` has a highest priority.");
52
DEFINE_int32(camera_id, -1, "Device id of camera to predict");
Z
zhiboniu 已提交
53 54 55 56 57 58 59 60
DEFINE_bool(
    use_gpu,
    false,
    "Deprecated, please use `--device` to set the device you want to run.");
DEFINE_string(device,
              "CPU",
              "Choose the device you want to run, it can be: CPU/GPU/XPU, "
              "default is CPU.");
61 62 63
DEFINE_double(threshold, 0.5, "Threshold of score.");
DEFINE_double(threshold_keypoint, 0.5, "Threshold of score.");
DEFINE_string(output_dir, "output", "Directory of output visualization files.");
Z
zhiboniu 已提交
64
DEFINE_string(run_mode,
65 66
              "paddle",
              "Mode of running(paddle/trt_fp32/trt_fp16/trt_int8)");
67
DEFINE_int32(gpu_id, 0, "Device id of GPU to execute");
Z
zhiboniu 已提交
68 69 70
DEFINE_bool(run_benchmark,
            false,
            "Whether to predict a image_file repeatedly for benchmark");
71 72 73 74 75
DEFINE_bool(use_mkldnn, false, "Whether use mkldnn with CPU");
DEFINE_int32(cpu_threads, 1, "Num of threads with CPU");
DEFINE_int32(trt_min_shape, 1, "Min shape of TRT DynamicShapeI");
DEFINE_int32(trt_max_shape, 1280, "Max shape of TRT DynamicShapeI");
DEFINE_int32(trt_opt_shape, 640, "Opt shape of TRT DynamicShapeI");
Z
zhiboniu 已提交
76 77 78 79
DEFINE_bool(trt_calib_mode,
            false,
            "If the model is produced by TRT offline quantitative calibration, "
            "trt_calib_mode need to set True");
80 81
DEFINE_bool(use_dark, true, "Whether use dark decode in keypoint postprocess");

Z
zhiboniu 已提交
82
void PrintBenchmarkLog(std::vector<double> det_time, int img_num) {
83 84
  LOG(INFO) << "----------------------- Config info -----------------------";
  LOG(INFO) << "runtime_device: " << FLAGS_device;
Z
zhiboniu 已提交
85 86 87 88
  LOG(INFO) << "ir_optim: "
            << "True";
  LOG(INFO) << "enable_memory_optim: "
            << "True";
89 90
  int has_trt = FLAGS_run_mode.find("trt");
  if (has_trt >= 0) {
Z
zhiboniu 已提交
91 92
    LOG(INFO) << "enable_tensorrt: "
              << "True";
93 94 95
    std::string precision = FLAGS_run_mode.substr(4, 8);
    LOG(INFO) << "precision: " << precision;
  } else {
Z
zhiboniu 已提交
96 97 98 99
    LOG(INFO) << "enable_tensorrt: "
              << "False";
    LOG(INFO) << "precision: "
              << "fp32";
100 101 102 103 104
  }
  LOG(INFO) << "enable_mkldnn: " << (FLAGS_use_mkldnn ? "True" : "False");
  LOG(INFO) << "cpu_math_library_num_threads: " << FLAGS_cpu_threads;
  LOG(INFO) << "----------------------- Data info -----------------------";
  LOG(INFO) << "batch_size: " << FLAGS_batch_size;
Z
zhiboniu 已提交
105 106
  LOG(INFO) << "input_shape: "
            << "dynamic shape";
107 108
  LOG(INFO) << "----------------------- Model info -----------------------";
  FLAGS_model_dir.erase(FLAGS_model_dir.find_last_not_of("/") + 1);
109 110 111 112 113 114 115 116 117 118 119
  LOG(INFO) << "model_name: " << FLAGS_model_dir;
  LOG(INFO) << "----------------------- Perf info ------------------------";
  LOG(INFO) << "Total number of predicted data: " << img_num
            << " and total time spent(ms): "
            << std::accumulate(det_time.begin(), det_time.end(), 0.);
  img_num = std::max(1, img_num);
  LOG(INFO) << "preproce_time(ms): " << det_time[0] / img_num
            << ", inference_time(ms): " << det_time[1] / img_num
            << ", postprocess_time(ms): " << det_time[2] / img_num;
}

Z
zhiboniu 已提交
120
void PrintKptsBenchmarkLog(std::vector<double> det_time, int img_num) {
121 122 123
  LOG(INFO) << "----------------------- Data info -----------------------";
  LOG(INFO) << "batch_size_keypoint: " << FLAGS_batch_size_keypoint;
  LOG(INFO) << "----------------------- Model info -----------------------";
Z
zhiboniu 已提交
124 125
  FLAGS_model_dir_keypoint.erase(
      FLAGS_model_dir_keypoint.find_last_not_of("/") + 1);
126
  LOG(INFO) << "keypoint_model_name: " << FLAGS_model_dir_keypoint;
127 128 129
  LOG(INFO) << "----------------------- Perf info ------------------------";
  LOG(INFO) << "Total number of predicted data: " << img_num
            << " and total time spent(ms): "
130 131 132
            << std::accumulate(det_time.begin(), det_time.end(), 0.);
  img_num = std::max(1, img_num);
  LOG(INFO) << "Average time cost per person:";
133 134 135 136 137
  LOG(INFO) << "preproce_time(ms): " << det_time[0] / img_num
            << ", inference_time(ms): " << det_time[1] / img_num
            << ", postprocess_time(ms): " << det_time[2] / img_num;
}

Z
zhiboniu 已提交
138
static std::string DirName(const std::string& filepath) {
139 140 141 142 143 144 145
  auto pos = filepath.rfind(OS_PATH_SEP);
  if (pos == std::string::npos) {
    return "";
  }
  return filepath.substr(0, pos);
}

Z
zhiboniu 已提交
146
static bool PathExists(const std::string& path) {
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
#ifdef _WIN32
  struct _stat buffer;
  return (_stat(path.c_str(), &buffer) == 0);
#else
  struct stat buffer;
  return (stat(path.c_str(), &buffer) == 0);
#endif  // !_WIN32
}

static void MkDir(const std::string& path) {
  if (PathExists(path)) return;
  int ret = 0;
#ifdef _WIN32
  ret = _mkdir(path.c_str());
#else
  ret = mkdir(path.c_str(), 0755);
#endif  // !_WIN32
  if (ret != 0) {
    std::string path_error(path);
    path_error += " mkdir failed!";
    throw std::runtime_error(path_error);
  }
}

static void MkDirs(const std::string& path) {
  if (path.empty()) return;
  if (PathExists(path)) return;

  MkDirs(DirName(path));
  MkDir(path);
}

void PredictVideo(const std::string& video_path,
                  PaddleDetection::ObjectDetector* det,
181 182
                  PaddleDetection::KeyPointDetector* keypoint,
                  const std::string& output_dir = "output") {
183 184
  // Open video
  cv::VideoCapture capture;
185
  std::string video_out_name = "output.mp4";
Z
zhiboniu 已提交
186
  if (FLAGS_camera_id != -1) {
187
    capture.open(FLAGS_camera_id);
Z
zhiboniu 已提交
188
  } else {
189
    capture.open(video_path.c_str());
Z
zhiboniu 已提交
190 191
    video_out_name =
        video_path.substr(video_path.find_last_of(OS_PATH_SEP) + 1);
192 193 194 195 196 197
  }
  if (!capture.isOpened()) {
    printf("can not open video : %s\n", video_path.c_str());
    return;
  }

198
  // Get Video info : resolution, fps, frame count
199 200 201
  int video_width = static_cast<int>(capture.get(CV_CAP_PROP_FRAME_WIDTH));
  int video_height = static_cast<int>(capture.get(CV_CAP_PROP_FRAME_HEIGHT));
  int video_fps = static_cast<int>(capture.get(CV_CAP_PROP_FPS));
Z
zhiboniu 已提交
202 203
  int video_frame_count =
      static_cast<int>(capture.get(CV_CAP_PROP_FRAME_COUNT));
204
  printf("fps: %d, frame_count: %d\n", video_fps, video_frame_count);
205 206 207

  // Create VideoWriter for output
  cv::VideoWriter video_out;
208 209 210 211 212
  std::string video_out_path(output_dir);
  if (output_dir.rfind(OS_PATH_SEP) != output_dir.size() - 1) {
    video_out_path += OS_PATH_SEP;
  }
  video_out_path += video_out_name;
213 214 215 216 217 218 219 220 221
  video_out.open(video_out_path.c_str(),
                 0x00000021,
                 video_fps,
                 cv::Size(video_width, video_height),
                 true);
  if (!video_out.isOpened()) {
    printf("create video writer failed!\n");
    return;
  }
Z
zhiboniu 已提交
222 223
  PaddleDetection::PoseSmooth smoother =
      PaddleDetection::PoseSmooth(video_width, video_height);
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238

  std::vector<PaddleDetection::ObjectResult> result;
  std::vector<int> bbox_num;
  std::vector<double> det_times;
  auto labels = det->GetLabelList();
  auto colormap = PaddleDetection::GenerateColorMap(labels.size());

  // Store keypoint results
  std::vector<PaddleDetection::KeyPointResult> result_kpts;
  std::vector<cv::Mat> imgs_kpts;
  std::vector<std::vector<float>> center_bs;
  std::vector<std::vector<float>> scale_bs;
  std::vector<int> colormap_kpts = PaddleDetection::GenerateColorMap(20);
  // Capture all frames and do inference
  cv::Mat frame;
239
  int frame_id = 1;
240 241 242 243 244 245 246
  bool is_rbox = false;
  while (capture.read(frame)) {
    if (frame.empty()) {
      break;
    }
    std::vector<cv::Mat> imgs;
    imgs.push_back(frame);
247 248 249
    printf("detect frame: %d\n", frame_id);
    det->Predict(imgs, FLAGS_threshold, 0, 1, &result, &bbox_num, &det_times);
    std::vector<PaddleDetection::ObjectResult> out_result;
250
    for (const auto& item : result) {
251
      if (item.confidence < FLAGS_threshold || item.class_id == -1) {
Z
zhiboniu 已提交
252
        continue;
253 254
      }
      out_result.push_back(item);
Z
zhiboniu 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268
      if (item.rect.size() > 6) {
        is_rbox = true;
        printf("class=%d confidence=%.4f rect=[%d %d %d %d %d %d %d %d]\n",
               item.class_id,
               item.confidence,
               item.rect[0],
               item.rect[1],
               item.rect[2],
               item.rect[3],
               item.rect[4],
               item.rect[5],
               item.rect[6],
               item.rect[7]);
      } else {
269
        printf("class=%d confidence=%.4f rect=[%d %d %d %d]\n",
Z
zhiboniu 已提交
270 271 272 273 274 275
               item.class_id,
               item.confidence,
               item.rect[0],
               item.rect[1],
               item.rect[2],
               item.rect[3]);
276 277 278
      }
    }

Z
zhiboniu 已提交
279 280
    if (keypoint) {
      result_kpts.clear();
281
      int imsize = out_result.size();
Z
zhiboniu 已提交
282
      for (int i = 0; i < imsize; i++) {
283
        auto item = out_result[i];
284 285
        cv::Mat crop_img;
        std::vector<double> keypoint_times;
Z
zhiboniu 已提交
286 287
        std::vector<int> rect = {
            item.rect[0], item.rect[1], item.rect[2], item.rect[3]};
288 289
        std::vector<float> center;
        std::vector<float> scale;
Z
zhiboniu 已提交
290
        if (item.class_id == 0) {
291 292 293 294 295 296
          PaddleDetection::CropImg(frame, crop_img, rect, center, scale);
          center_bs.emplace_back(center);
          scale_bs.emplace_back(scale);
          imgs_kpts.emplace_back(crop_img);
        }

Z
zhiboniu 已提交
297 298 299 300 301 302 303 304 305 306
        if (imgs_kpts.size() == FLAGS_batch_size_keypoint ||
            ((i == imsize - 1) && !imgs_kpts.empty())) {
          keypoint->Predict(imgs_kpts,
                            center_bs,
                            scale_bs,
                            FLAGS_threshold,
                            0,
                            1,
                            &result_kpts,
                            &keypoint_times);
307 308 309 310 311
          imgs_kpts.clear();
          center_bs.clear();
          scale_bs.clear();
        }
      }
Z
zhiboniu 已提交
312 313 314 315 316 317 318

      if (result_kpts.size() == 1) {
        for (int i = 0; i < result_kpts.size(); i++) {
          result_kpts[i] = smoother.smooth_process(&(result_kpts[i]));
        }
      }

319 320
      cv::Mat out_im = VisualizeKptsResult(frame, result_kpts, colormap_kpts);
      video_out.write(out_im);
Z
zhiboniu 已提交
321
    } else {
322 323
      // Visualization result
      cv::Mat out_im = PaddleDetection::VisualizeResult(
324
          frame, out_result, labels, colormap, is_rbox);
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
      video_out.write(out_im);
    }

    frame_id += 1;
  }
  capture.release();
  video_out.release();
}

void PredictImage(const std::vector<std::string> all_img_paths,
                  const int batch_size,
                  const double threshold,
                  const bool run_benchmark,
                  PaddleDetection::ObjectDetector* det,
                  PaddleDetection::KeyPointDetector* keypoint,
                  const std::string& output_dir = "output") {
  std::vector<double> det_t = {0, 0, 0};
Z
zhiboniu 已提交
342
  int steps = ceil(static_cast<float>(all_img_paths.size()) / batch_size);
343 344 345
  int kpts_imgs = 0;
  std::vector<double> keypoint_t = {0, 0, 0};
  printf("total images = %d, batch_size = %d, total steps = %d\n",
Z
zhiboniu 已提交
346 347 348
         all_img_paths.size(),
         batch_size,
         steps);
349 350 351 352 353 354 355
  for (int idx = 0; idx < steps; idx++) {
    std::vector<cv::Mat> batch_imgs;
    int left_image_cnt = all_img_paths.size() - idx * batch_size;
    if (left_image_cnt > batch_size) {
      left_image_cnt = batch_size;
    }
    for (int bs = 0; bs < left_image_cnt; bs++) {
Z
zhiboniu 已提交
356
      std::string image_file_path = all_img_paths.at(idx * batch_size + bs);
357 358 359
      cv::Mat im = cv::imread(image_file_path, 1);
      batch_imgs.insert(batch_imgs.end(), im);
    }
Z
zhiboniu 已提交
360

361 362 363 364 365 366 367 368 369 370 371 372 373 374
    // Store all detected result
    std::vector<PaddleDetection::ObjectResult> result;
    std::vector<int> bbox_num;
    std::vector<double> det_times;

    // Store keypoint results
    std::vector<PaddleDetection::KeyPointResult> result_kpts;
    std::vector<cv::Mat> imgs_kpts;
    std::vector<std::vector<float>> center_bs;
    std::vector<std::vector<float>> scale_bs;
    std::vector<int> colormap_kpts = PaddleDetection::GenerateColorMap(20);

    bool is_rbox = false;
    if (run_benchmark) {
Z
zhiboniu 已提交
375 376
      det->Predict(
          batch_imgs, threshold, 10, 10, &result, &bbox_num, &det_times);
377
    } else {
378
      det->Predict(batch_imgs, threshold, 0, 1, &result, &bbox_num, &det_times);
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
    }
    // get labels and colormap
    auto labels = det->GetLabelList();
    auto colormap = PaddleDetection::GenerateColorMap(labels.size());
    int item_start_idx = 0;
    for (int i = 0; i < left_image_cnt; i++) {
      cv::Mat im = batch_imgs[i];
      std::vector<PaddleDetection::ObjectResult> im_result;
      int detect_num = 0;
      for (int j = 0; j < bbox_num[i]; j++) {
        PaddleDetection::ObjectResult item = result[item_start_idx + j];
        if (item.confidence < threshold || item.class_id == -1) {
          continue;
        }
        detect_num += 1;
        im_result.push_back(item);
Z
zhiboniu 已提交
395
        if (item.rect.size() > 6) {
396 397
          is_rbox = true;
          printf("class=%d confidence=%.4f rect=[%d %d %d %d %d %d %d %d]\n",
Z
zhiboniu 已提交
398 399 400 401 402 403 404 405 406 407 408
                 item.class_id,
                 item.confidence,
                 item.rect[0],
                 item.rect[1],
                 item.rect[2],
                 item.rect[3],
                 item.rect[4],
                 item.rect[5],
                 item.rect[6],
                 item.rect[7]);
        } else {
409
          printf("class=%d confidence=%.4f rect=[%d %d %d %d]\n",
Z
zhiboniu 已提交
410 411 412 413 414 415
                 item.class_id,
                 item.confidence,
                 item.rect[0],
                 item.rect[1],
                 item.rect[2],
                 item.rect[3]);
416 417
        }
      }
Z
zhiboniu 已提交
418 419 420 421
      std::cout << all_img_paths.at(idx * batch_size + i)
                << " The number of detected box: " << detect_num << std::endl;
      item_start_idx = item_start_idx + bbox_num[i];

422 423 424 425 426 427 428 429
      std::vector<int> compression_params;
      compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
      compression_params.push_back(95);
      std::string output_path(output_dir);
      if (output_dir.rfind(OS_PATH_SEP) != output_dir.size() - 1) {
        output_path += OS_PATH_SEP;
      }
      std::string image_file_path = all_img_paths.at(idx * batch_size + i);
Z
zhiboniu 已提交
430
      if (keypoint) {
431
        int imsize = im_result.size();
Z
zhiboniu 已提交
432
        for (int i = 0; i < imsize; i++) {
433 434 435
          auto item = im_result[i];
          cv::Mat crop_img;
          std::vector<double> keypoint_times;
Z
zhiboniu 已提交
436 437
          std::vector<int> rect = {
              item.rect[0], item.rect[1], item.rect[2], item.rect[3]};
438 439
          std::vector<float> center;
          std::vector<float> scale;
Z
zhiboniu 已提交
440
          if (item.class_id == 0) {
441 442 443 444 445 446 447
            PaddleDetection::CropImg(im, crop_img, rect, center, scale);
            center_bs.emplace_back(center);
            scale_bs.emplace_back(scale);
            imgs_kpts.emplace_back(crop_img);
            kpts_imgs += 1;
          }

Z
zhiboniu 已提交
448 449
          if (imgs_kpts.size() == FLAGS_batch_size_keypoint ||
              ((i == imsize - 1) && !imgs_kpts.empty())) {
450
            if (run_benchmark) {
Z
zhiboniu 已提交
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
              keypoint->Predict(imgs_kpts,
                                center_bs,
                                scale_bs,
                                0.5,
                                10,
                                10,
                                &result_kpts,
                                &keypoint_times);
            } else {
              keypoint->Predict(imgs_kpts,
                                center_bs,
                                scale_bs,
                                0.5,
                                0,
                                1,
                                &result_kpts,
                                &keypoint_times);
468 469 470 471 472 473 474 475 476
            }
            imgs_kpts.clear();
            center_bs.clear();
            scale_bs.clear();
            keypoint_t[0] += keypoint_times[0];
            keypoint_t[1] += keypoint_times[1];
            keypoint_t[2] += keypoint_times[2];
          }
        }
Z
zhiboniu 已提交
477 478 479 480 481
        std::string kpts_savepath =
            output_path + "keypoint_" +
            image_file_path.substr(image_file_path.find_last_of('/') + 1);
        cv::Mat kpts_vis_img =
            VisualizeKptsResult(im, result_kpts, colormap_kpts);
482 483
        cv::imwrite(kpts_savepath, kpts_vis_img, compression_params);
        printf("Visualized output saved as %s\n", kpts_savepath.c_str());
Z
zhiboniu 已提交
484
      } else {
485 486 487
        // Visualization result
        cv::Mat vis_img = PaddleDetection::VisualizeResult(
            im, im_result, labels, colormap, is_rbox);
Z
zhiboniu 已提交
488 489 490
        std::string det_savepath =
            output_path +
            image_file_path.substr(image_file_path.find_last_of('/') + 1);
491
        cv::imwrite(det_savepath, vis_img, compression_params);
Z
zhiboniu 已提交
492
        printf("Visualized output saved as %s\n", det_savepath.c_str());
493 494
      }
    }
Z
zhiboniu 已提交
495

496 497 498 499 500
    det_t[0] += det_times[0];
    det_t[1] += det_times[1];
    det_t[2] += det_times[2];
  }
  PrintBenchmarkLog(det_t, all_img_paths.size());
501 502 503
  if (keypoint) {
    PrintKptsBenchmarkLog(keypoint_t, kpts_imgs);
  }
504 505 506 507 508
}

int main(int argc, char** argv) {
  // Parsing command-line
  google::ParseCommandLineFlags(&argc, &argv, true);
Z
zhiboniu 已提交
509 510 511 512 513 514
  if (FLAGS_model_dir.empty() ||
      (FLAGS_image_file.empty() && FLAGS_image_dir.empty() &&
       FLAGS_video_file.empty())) {
    std::cout << "Usage: ./main --model_dir=/PATH/TO/INFERENCE_MODEL/ "
                 "(--model_dir_keypoint=/PATH/TO/INFERENCE_MODEL/)"
              << "--image_file=/PATH/TO/INPUT/IMAGE/" << std::endl;
515 516
    return -1;
  }
517
  if (!(FLAGS_run_mode == "paddle" || FLAGS_run_mode == "trt_fp32" ||
Z
zhiboniu 已提交
518 519
        FLAGS_run_mode == "trt_fp16" || FLAGS_run_mode == "trt_int8")) {
    std::cout
520
        << "run_mode should be 'paddle', 'trt_fp32', 'trt_fp16' or 'trt_int8'.";
521 522
    return -1;
  }
Z
zhiboniu 已提交
523 524 525 526 527 528
  transform(FLAGS_device.begin(),
            FLAGS_device.end(),
            FLAGS_device.begin(),
            ::toupper);
  if (!(FLAGS_device == "CPU" || FLAGS_device == "GPU" ||
        FLAGS_device == "XPU")) {
529 530 531 532
    std::cout << "device should be 'CPU', 'GPU' or 'XPU'.";
    return -1;
  }
  if (FLAGS_use_gpu) {
Z
zhiboniu 已提交
533 534
    std::cout << "Deprecated, please use `--device` to set the device you want "
                 "to run.";
535 536 537
    return -1;
  }
  // Load model and create a object detector
Z
zhiboniu 已提交
538 539 540 541 542 543 544 545 546 547 548
  PaddleDetection::ObjectDetector det(FLAGS_model_dir,
                                      FLAGS_device,
                                      FLAGS_use_mkldnn,
                                      FLAGS_cpu_threads,
                                      FLAGS_run_mode,
                                      FLAGS_batch_size,
                                      FLAGS_gpu_id,
                                      FLAGS_trt_min_shape,
                                      FLAGS_trt_max_shape,
                                      FLAGS_trt_opt_shape,
                                      FLAGS_trt_calib_mode);
549 550

  PaddleDetection::KeyPointDetector* keypoint = nullptr;
Z
zhiboniu 已提交
551 552 553 554 555 556 557 558 559 560 561 562 563
  if (!FLAGS_model_dir_keypoint.empty()) {
    keypoint = new PaddleDetection::KeyPointDetector(FLAGS_model_dir_keypoint,
                                                     FLAGS_device,
                                                     FLAGS_use_mkldnn,
                                                     FLAGS_cpu_threads,
                                                     FLAGS_run_mode,
                                                     FLAGS_batch_size_keypoint,
                                                     FLAGS_gpu_id,
                                                     FLAGS_trt_min_shape,
                                                     FLAGS_trt_max_shape,
                                                     FLAGS_trt_opt_shape,
                                                     FLAGS_trt_calib_mode,
                                                     FLAGS_use_dark);
564 565
  }
  // Do inference on input video or image
566
  if (!PathExists(FLAGS_output_dir)) {
Z
zhiboniu 已提交
567
    MkDirs(FLAGS_output_dir);
568
  }
569
  if (!FLAGS_video_file.empty() || FLAGS_camera_id != -1) {
570
    PredictVideo(FLAGS_video_file, &det, keypoint, FLAGS_output_dir);
571 572 573 574 575 576
  } else if (!FLAGS_image_file.empty() || !FLAGS_image_dir.empty()) {
    std::vector<std::string> all_img_paths;
    std::vector<cv::String> cv_all_img_paths;
    if (!FLAGS_image_file.empty()) {
      all_img_paths.push_back(FLAGS_image_file);
      if (FLAGS_batch_size > 1) {
Z
zhiboniu 已提交
577 578 579
        std::cout << "batch_size should be 1, when set `image_file`."
                  << std::endl;
        return -1;
580 581
      }
    } else {
Z
zhiboniu 已提交
582 583 584 585
      cv::glob(FLAGS_image_dir, cv_all_img_paths);
      for (const auto& img_path : cv_all_img_paths) {
        all_img_paths.push_back(img_path);
      }
586
    }
Z
zhiboniu 已提交
587 588 589 590 591 592 593
    PredictImage(all_img_paths,
                 FLAGS_batch_size,
                 FLAGS_threshold,
                 FLAGS_run_benchmark,
                 &det,
                 keypoint,
                 FLAGS_output_dir);
594 595 596 597 598
  }
  delete keypoint;
  keypoint = nullptr;
  return 0;
}