ravijoshi53

asynchronous.cpp

Feb 2nd, 2019
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 10.05 KB | None | 0 0
  1. // -------------------------
  2. // OpenPose C++ API Tutorial - Example 6 - Custom Input
  3. // -------------------------
  4. // Asynchronous mode:
  5. // ideal for fast prototyping when performance
  6. // is not an issue. In this function, the user
  7. // can implement its own way to create frames (e.g.,
  8. // reading his own folder of images) and
  9. // emplaces/pushes the frames to OpenPose.
  10.  
  11. // Command-line user intraface
  12. #define OPENPOSE_FLAGS_DISABLE_PRODUCER
  13.  
  14. // OpenPose headers
  15. #include <openpose/flags.hpp>
  16. #include <openpose/headers.hpp>
  17.  
  18. // The W-classes can be implemented either as
  19. // a template or as simple classes given that
  20. // the user usually knows which kind of data
  21. // he will move between the queues, in this
  22. // case we assume a std::shared_ptr of a
  23. // std::vector of op::Datum
  24.  
  25. // OpenPose image_dir
  26. DEFINE_string(image_dir, "/home/ravi/tools/openpose/examples/media/", "");
  27. // OpenPose model_folder
  28. DEFINE_string(model_folder, "/home/ravi/tools/openpose/models/", "");
  29.  
  30. class UserInputClass
  31. {
  32. public:
  33.   UserInputClass(const std::string& directoryPath)
  34.     : mImageFiles{ op::getFilesOnDirectory(directoryPath,
  35.                                            op::Extensions::Images) }
  36.     ,  // For all basic image formats
  37.     // If we want only e.g., "jpg" + "png" images
  38.     // mImageFiles{op::getFilesOnDirectory(directoryPath,
  39.     // std::vector<std::string>{"jpg", "png"})},
  40.     mCounter{ 0 }
  41.     , mClosed{ false }
  42.   {
  43.     if (mImageFiles.empty())
  44.       op::error("No images found on: " + directoryPath, __LINE__, __FUNCTION__,
  45.                 __FILE__);
  46.   }
  47.  
  48.   std::shared_ptr<std::vector<std::shared_ptr<op::Datum>>> createDatum()
  49.   {
  50.     // Close program when empty frame
  51.     if (mClosed || mImageFiles.size() <= mCounter)
  52.     {
  53.       op::log("Last frame read and added to queue. Closing program after it is "
  54.               "processed.",
  55.               op::Priority::High);
  56.       // This funtion stops this worker, which will eventually stop the whole
  57.       // thread system once all the frames
  58.       // have been processed
  59.       mClosed = true;
  60.       return nullptr;
  61.     }
  62.     else  // if (!mClosed)
  63.     {
  64.       // Create new datum
  65.       auto datumsPtr =
  66.           std::make_shared<std::vector<std::shared_ptr<op::Datum>>>();
  67.       datumsPtr->emplace_back();
  68.       auto& datumPtr = datumsPtr->at(0);
  69.       datumPtr = std::make_shared<op::Datum>();
  70.  
  71.       // Fill datum
  72.       datumPtr->cvInputData = cv::imread(mImageFiles.at(mCounter++));
  73.  
  74.       // If empty frame -> return nullptr
  75.       if (datumPtr->cvInputData.empty())
  76.       {
  77.         op::log("Empty frame detected on path: " +
  78.                     mImageFiles.at(mCounter - 1) + ". Closing program.",
  79.                 op::Priority::High);
  80.         mClosed = true;
  81.         datumsPtr = nullptr;
  82.       }
  83.  
  84.       return datumsPtr;
  85.     }
  86.   }
  87.  
  88.   bool isFinished() const
  89.   {
  90.     return mClosed;
  91.   }
  92.  
  93. private:
  94.   const std::vector<std::string> mImageFiles;
  95.   unsigned long long mCounter;
  96.   bool mClosed;
  97. };
  98.  
  99. void configureWrapper(op::Wrapper& opWrapper)
  100. {
  101.   try
  102.   {
  103.     // Configuring OpenPose
  104.  
  105.     // logging_level
  106.     op::check(0 <= FLAGS_logging_level && FLAGS_logging_level <= 255,
  107.               "Wrong logging_level value.", __LINE__, __FUNCTION__, __FILE__);
  108.     op::ConfigureLog::setPriorityThreshold((op::Priority)FLAGS_logging_level);
  109.     op::Profiler::setDefaultX(FLAGS_profile_speed);
  110.  
  111.     // Applying user defined configuration - GFlags to program variables
  112.     // outputSize
  113.     const auto outputSize = op::flagsToPoint(FLAGS_output_resolution, "-1x-1");
  114.     // netInputSize
  115.     const auto netInputSize = op::flagsToPoint(FLAGS_net_resolution, "-1x368");
  116.     // faceNetInputSize
  117.     const auto faceNetInputSize = op::flagsToPoint(FLAGS_face_net_resolution,
  118.                                                    "368x368 (multiples of 16)");
  119.     // handNetInputSize
  120.     const auto handNetInputSize = op::flagsToPoint(FLAGS_hand_net_resolution,
  121.                                                    "368x368 (multiples of 16)");
  122.     // poseModel
  123.     const auto poseModel = op::flagsToPoseModel(FLAGS_model_pose);
  124.     // JSON saving
  125.     if (!FLAGS_write_keypoint.empty())
  126.       op::log(
  127.           "Flag `write_keypoint` is deprecated and will eventually be removed."
  128.           " Please, use `write_json` instead.",
  129.           op::Priority::Max);
  130.     // keypointScaleMode
  131.     const auto keypointScaleMode = op::flagsToScaleMode(FLAGS_keypoint_scale);
  132.     // heatmaps to add
  133.     const auto heatMapTypes =
  134.         op::flagsToHeatMaps(FLAGS_heatmaps_add_parts, FLAGS_heatmaps_add_bkg,
  135.                             FLAGS_heatmaps_add_PAFs);
  136.     const auto heatMapScaleMode =
  137.         op::flagsToHeatMapScaleMode(FLAGS_heatmaps_scale);
  138.     // >1 camera view?
  139.     const auto multipleView = (FLAGS_3d || FLAGS_3d_views > 1);
  140.     // Face and hand detectors
  141.     const auto faceDetector = op::flagsToDetector(FLAGS_face_detector);
  142.     const auto handDetector = op::flagsToDetector(FLAGS_hand_detector);
  143.     // Enabling Google Logging
  144.     const bool enableGoogleLogging = true;
  145.  
  146.     // Pose configuration (use WrapperStructPose{} for default and recommended
  147.     // configuration)
  148.     const op::WrapperStructPose wrapperStructPose{
  149.       !FLAGS_body_disable,
  150.       netInputSize,
  151.       outputSize,
  152.       keypointScaleMode,
  153.       FLAGS_num_gpu,
  154.       FLAGS_num_gpu_start,
  155.       FLAGS_scale_number,
  156.       (float)FLAGS_scale_gap,
  157.       op::flagsToRenderMode(FLAGS_render_pose, multipleView),
  158.       poseModel,
  159.       !FLAGS_disable_blending,
  160.       (float)FLAGS_alpha_pose,
  161.       (float)FLAGS_alpha_heatmap,
  162.       FLAGS_part_to_show,
  163.       FLAGS_model_folder,
  164.       heatMapTypes,
  165.       heatMapScaleMode,
  166.       FLAGS_part_candidates,
  167.       (float)FLAGS_render_threshold,
  168.       FLAGS_number_people_max,
  169.       FLAGS_maximize_positives,
  170.       FLAGS_fps_max,
  171.       FLAGS_prototxt_path,
  172.       FLAGS_caffemodel_path,
  173.       enableGoogleLogging
  174.     };
  175.     opWrapper.configure(wrapperStructPose);
  176.     // Face configuration (use op::WrapperStructFace{} to disable it)
  177.     const op::WrapperStructFace wrapperStructFace{
  178.       FLAGS_face,
  179.       faceDetector,
  180.       faceNetInputSize,
  181.       op::flagsToRenderMode(FLAGS_face_render, multipleView, FLAGS_render_pose),
  182.       (float)FLAGS_face_alpha_pose,
  183.       (float)FLAGS_face_alpha_heatmap,
  184.       (float)FLAGS_face_render_threshold
  185.     };
  186.     opWrapper.configure(wrapperStructFace);
  187.     // Hand configuration (use op::WrapperStructHand{} to disable it)
  188.     const op::WrapperStructHand wrapperStructHand{
  189.       FLAGS_hand,
  190.       handDetector,
  191.       handNetInputSize,
  192.       FLAGS_hand_scale_number,
  193.       (float)FLAGS_hand_scale_range,
  194.       op::flagsToRenderMode(FLAGS_hand_render, multipleView, FLAGS_render_pose),
  195.       (float)FLAGS_hand_alpha_pose,
  196.       (float)FLAGS_hand_alpha_heatmap,
  197.       (float)FLAGS_hand_render_threshold
  198.     };
  199.     opWrapper.configure(wrapperStructHand);
  200.     // Extra functionality configuration (use op::WrapperStructExtra{} to
  201.     // disable it)
  202.     const op::WrapperStructExtra wrapperStructExtra{
  203.       FLAGS_3d, FLAGS_3d_min_views, FLAGS_identification, FLAGS_tracking,
  204.       FLAGS_ik_threads
  205.     };
  206.     opWrapper.configure(wrapperStructExtra);
  207.     // Output (comment or use default argument to disable any output)
  208.     const op::WrapperStructOutput wrapperStructOutput{
  209.       FLAGS_cli_verbose,
  210.       FLAGS_write_keypoint,
  211.       op::stringToDataFormat(FLAGS_write_keypoint_format),
  212.       FLAGS_write_json,
  213.       FLAGS_write_coco_json,
  214.       FLAGS_write_coco_foot_json,
  215.       FLAGS_write_coco_json_variant,
  216.       FLAGS_write_images,
  217.       FLAGS_write_images_format,
  218.       FLAGS_write_video,
  219.       FLAGS_write_video_fps,
  220.       FLAGS_write_video_with_audio,
  221.       FLAGS_write_heatmaps,
  222.       FLAGS_write_heatmaps_format,
  223.       FLAGS_write_video_3d,
  224.       FLAGS_write_video_adam,
  225.       FLAGS_write_bvh,
  226.       FLAGS_udp_host,
  227.       FLAGS_udp_port
  228.     };
  229.     opWrapper.configure(wrapperStructOutput);
  230.     // GUI (comment or use default argument to disable any visual output)
  231.     const op::WrapperStructGui wrapperStructGui{
  232.       op::flagsToDisplayMode(FLAGS_display, FLAGS_3d), !FLAGS_no_gui_verbose,
  233.       FLAGS_fullscreen
  234.     };
  235.     opWrapper.configure(wrapperStructGui);
  236.     // Set to single-thread (for sequential processing and/or debugging and/or
  237.     // reducing latency)
  238.     if (FLAGS_disable_multi_thread)
  239.       opWrapper.disableMultiThreading();
  240.   }
  241.   catch (const std::exception& e)
  242.   {
  243.     op::error(e.what(), __LINE__, __FUNCTION__, __FILE__);
  244.   }
  245. }
  246.  
  247. int tutorialApiCpp()
  248. {
  249.   try
  250.   {
  251.     op::log("Starting OpenPose demo...", op::Priority::High);
  252.     const auto opTimer = op::getTimerInit();
  253.  
  254.     // Configuring OpenPose
  255.     op::log("Configuring OpenPose...", op::Priority::High);
  256.     op::Wrapper opWrapper{ op::ThreadManagerMode::AsynchronousIn };
  257.     configureWrapper(opWrapper);
  258.  
  259.     // Start, run, and stop processing - exec() blocks this thread until
  260.     // OpenPose wrapper has finished
  261.     op::log("Starting thread(s)...", op::Priority::High);
  262.     opWrapper.start();
  263.  
  264.     // User processing
  265.     UserInputClass userInputClass(FLAGS_image_dir);
  266.     bool userWantsToExit = false;
  267.     while (!userWantsToExit && !userInputClass.isFinished())
  268.     {
  269.       // Push frame
  270.       auto datumToProcess = userInputClass.createDatum();
  271.       if (datumToProcess != nullptr)
  272.       {
  273.         auto successfullyEmplaced = opWrapper.waitAndEmplace(datumToProcess);
  274.         if (!successfullyEmplaced)
  275.           op::log("Processed datum could not be emplaced.", op::Priority::High);
  276.       }
  277.     }
  278.  
  279.     op::log("Stopping thread(s)", op::Priority::High);
  280.     opWrapper.stop();
  281.  
  282.     // Measuring total time
  283.     op::printTime(opTimer, "OpenPose demo successfully finished. Total time: ",
  284.                   " seconds.", op::Priority::High);
  285.  
  286.     // Return
  287.     return 0;
  288.   }
  289.   catch (const std::exception& e)
  290.   {
  291.     return -1;
  292.   }
  293. }
  294.  
  295. int main(int argc, char* argv[])
  296. {
  297.   // Parsing command line flags
  298.   gflags::ParseCommandLineFlags(&argc, &argv, true);
  299.  
  300.   // Running tutorialApiCpp
  301.   return tutorialApiCpp();
  302. }
Advertisement
Add Comment
Please, Sign In to add comment