utils.hpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #ifndef OPENCV_GAPI_PIPELINE_MODELING_TOOL_UTILS_HPP
  2. #define OPENCV_GAPI_PIPELINE_MODELING_TOOL_UTILS_HPP
  3. #include <opencv2/core.hpp>
  4. #if defined(_WIN32)
  5. #include <windows.h>
  6. #endif
  7. // FIXME: It's better to place it somewhere in common.hpp
  8. struct OutputDescr {
  9. std::vector<int> dims;
  10. int precision;
  11. };
  12. namespace utils {
  13. inline void createNDMat(cv::Mat& mat, const std::vector<int>& dims, int depth) {
  14. GAPI_Assert(!dims.empty());
  15. mat.create(dims, depth);
  16. if (dims.size() == 1) {
  17. //FIXME: Well-known 1D mat WA
  18. mat.dims = 1;
  19. }
  20. }
  21. inline void generateRandom(cv::Mat& out) {
  22. switch (out.depth()) {
  23. case CV_8U:
  24. cv::randu(out, 0, 255);
  25. break;
  26. case CV_32F:
  27. cv::randu(out, 0.f, 1.f);
  28. break;
  29. case CV_16F: {
  30. std::vector<int> dims;
  31. for (int i = 0; i < out.size.dims(); ++i) {
  32. dims.push_back(out.size[i]);
  33. }
  34. cv::Mat fp32_mat;
  35. createNDMat(fp32_mat, dims, CV_32F);
  36. cv::randu(fp32_mat, 0.f, 1.f);
  37. fp32_mat.convertTo(out, out.type());
  38. break;
  39. }
  40. default:
  41. throw std::logic_error("Unsupported preprocessing depth");
  42. }
  43. }
  44. inline void sleep(double ms) {
  45. #if defined(_WIN32)
  46. // NB: It takes portions of 100 nanoseconds.
  47. int64_t ns_units = static_cast<int64_t>(ms * 1e4);
  48. // FIXME: Wrap it to RAII and instance only once.
  49. HANDLE timer = CreateWaitableTimer(NULL, true, NULL);
  50. if (!timer) {
  51. throw std::logic_error("Failed to create timer");
  52. }
  53. LARGE_INTEGER li;
  54. li.QuadPart = -ns_units;
  55. if(!SetWaitableTimer(timer, &li, 0, NULL, NULL, false)){
  56. CloseHandle(timer);
  57. throw std::logic_error("Failed to set timer");
  58. }
  59. if (WaitForSingleObject(timer, INFINITE) != WAIT_OBJECT_0) {
  60. CloseHandle(timer);
  61. throw std::logic_error("Failed to wait timer");
  62. }
  63. CloseHandle(timer);
  64. #else
  65. using namespace std::chrono;
  66. std::this_thread::sleep_for(duration<double, std::milli>(ms));
  67. #endif
  68. }
  69. template <typename duration_t>
  70. typename duration_t::rep measure(std::function<void()> f) {
  71. using namespace std::chrono;
  72. auto start = high_resolution_clock::now();
  73. f();
  74. return duration_cast<duration_t>(
  75. high_resolution_clock::now() - start).count();
  76. }
  77. template <typename duration_t>
  78. typename duration_t::rep timestamp() {
  79. using namespace std::chrono;
  80. auto now = high_resolution_clock::now();
  81. return duration_cast<duration_t>(now.time_since_epoch()).count();
  82. }
  83. } // namespace utils
  84. #endif // OPENCV_GAPI_PIPELINE_MODELING_TOOL_UTILS_HPP