ClipApp.cpp 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. #include "ClipApp.h"
  2. NAMESPACE_MAS_BEGIN
  3. NAMESPACE_CLIP_BEGIN
  4. ClipApp* ClipApp::_instance = nullptr;
  5. tzc::Mutex ClipApp::_mutex;
  6. ClipApp* ClipApp::Instance()
  7. {
  8. if (!_instance)
  9. {
  10. _mutex.Lock();
  11. if (!_instance)
  12. {
  13. _instance = new ClipApp();
  14. TZLogInfo("ClipApp Instance created~~~");
  15. }
  16. _mutex.Unlock();
  17. }
  18. ++(_instance->m_usecnt);
  19. return _instance;
  20. }
  21. void ClipApp::DestroyInstance()
  22. {
  23. tzc::ScopedLock lock(_mutex);
  24. if ((_instance->m_usecnt) < 0)
  25. {
  26. TZLogWarn("ClipApp Instance does not exist!!!");
  27. _instance->m_usecnt = 0;
  28. }
  29. else if ((_instance->m_usecnt) == 0)
  30. {
  31. TZ_delete(_instance);
  32. TZLogInfo("ClipApp Instance destroyed~~~");
  33. }
  34. else
  35. {
  36. TZLogWarn("ClipApp still in use by %d objects!", _instance->m_usecnt);
  37. TZ_delete(_instance);
  38. TZLogInfo("ClipApp Instance destroyed~~~");
  39. }
  40. }
  41. TZ_INT ClipApp::Initialize(const std::string& initParam)
  42. {
  43. if (m_inited)
  44. {
  45. TZLogInfo("ClipApp has been initialized~~~");
  46. return MEC_OK;
  47. }
  48. ClipBuild buildParam;
  49. ClipBuild::fromJson(initParam, buildParam);
  50. // Create ONNX Runtime environment
  51. m_env = new Ort::Env(OrtLoggingLevel::ORT_LOGGING_LEVEL_WARNING, "ClipApp");
  52. // Set session options
  53. m_sessionOptions.SetIntraOpNumThreads(1);
  54. // Configure CUDA execution provider if available
  55. auto providers = Ort::GetAvailableProviders();
  56. auto cudaAvailable = std::find(providers.begin(), providers.end(), "CUDAExecutionProvider");
  57. if (cudaAvailable != providers.end())
  58. {
  59. OrtCUDAProviderOptions cudaOptions;
  60. cudaOptions.device_id = buildParam.gpu_id;
  61. m_sessionOptions.AppendExecutionProvider_CUDA(cudaOptions);
  62. }
  63. // Create ONNX session
  64. m_session = new Ort::Session(*m_env, buildParam.model_path.c_str(), m_sessionOptions);
  65. m_inited = true;
  66. return MEC_OK;
  67. }
  68. TZ_INT ClipApp::Dispose()
  69. {
  70. if (!m_inited)
  71. {
  72. return MEC_NOT_INITED;
  73. }
  74. _mutex.Lock();
  75. --(m_usecnt);
  76. TZLogInfo("ClipApp usecnt -1, now = %d~~~", m_usecnt);
  77. TZ_BOOL empty = (m_usecnt == 0);
  78. _mutex.Unlock();
  79. if (empty)
  80. {
  81. m_inited = FALSE;
  82. TZLogInfo("ClipApp Dispose~~~");
  83. this->DestroyInstance();
  84. }
  85. return MEC_OK;
  86. }
  87. // Preprocess the input image
  88. TZ_INT ClipApp::PreprocessImage(cv::Mat& input, std::vector<TZ_FLOAT>& outputTensor)
  89. {
  90. if (input.empty())
  91. {
  92. TZLogError("Input image is empty!!!");
  93. return MEC_FAILED;
  94. }
  95. // Resize and normalize the image
  96. cv::Mat resized;
  97. cv::resize(input, resized, cv::Size(224, 224));
  98. resized.convertTo(resized, CV_32F, 1.0 / 255);
  99. cv::cvtColor(resized, resized, cv::COLOR_BGR2RGB);
  100. // Convert to CHW format
  101. outputTensor.clear();
  102. for (int c = 0; c < 3; ++c)
  103. {
  104. for (int h = 0; h < resized.rows; ++h)
  105. {
  106. for (int w = 0; w < resized.cols; ++w)
  107. {
  108. outputTensor.push_back(resized.at<cv::Vec3f>(h, w)[c]);
  109. }
  110. }
  111. }
  112. return MEC_OK;
  113. }
  114. TZ_INT ClipApp::DoDetect(cv::Mat& input, ClipDetectResult& detRes)
  115. {
  116. // Preprocess the image
  117. std::vector<TZ_FLOAT> inputTensorValues;
  118. if (PreprocessImage(input, inputTensorValues) != 0)
  119. {
  120. TZLogError("Failed to preprocess input image!!!");
  121. return MEC_FAILED;
  122. }
  123. // Get model input/output information dynamically
  124. auto inputDims = m_session->GetInputTypeInfo(0).GetTensorTypeAndShapeInfo().GetShape();
  125. auto outputDims = m_session->GetOutputTypeInfo(0).GetTensorTypeAndShapeInfo().GetShape();
  126. // Fix dynamic dimensions (-1)
  127. inputDims[0] = 1; // Batch size
  128. outputDims[0] = 1; // Batch size
  129. // Create input tensor
  130. Ort::MemoryInfo memoryInfo = Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault);
  131. Ort::Value inputTensor = Ort::Value::CreateTensor<TZ_FLOAT>(
  132. memoryInfo, inputTensorValues.data(), inputTensorValues.size(),
  133. inputDims.data(), inputDims.size());
  134. // Allocate output tensor
  135. TZ_INT outputTensorSize = 1;
  136. for (auto dim : outputDims)
  137. {
  138. outputTensorSize *= dim;
  139. }
  140. std::vector<TZ_FLOAT> outputTensorValues(outputTensorSize);
  141. Ort::Value outputTensor = Ort::Value::CreateTensor<TZ_FLOAT>(
  142. memoryInfo, outputTensorValues.data(), outputTensorValues.size(),
  143. outputDims.data(), outputDims.size());
  144. // Get input/output names
  145. Ort::AllocatorWithDefaultOptions allocator;
  146. auto inputNamePtr = m_session->GetInputNameAllocated(0, allocator);
  147. auto outputNamePtr = m_session->GetOutputNameAllocated(0, allocator);
  148. const TZ_Int8* inputName = inputNamePtr.get();
  149. const TZ_Int8* outputName = outputNamePtr.get();
  150. // Run inference
  151. m_session->Run(Ort::RunOptions{nullptr}, &inputName, &inputTensor, 1,
  152. &outputName, &outputTensor, 1);
  153. // Convert outputTensorValues (TZ_FLOAT vector) to detRes.output_data (vector<OutputData>)
  154. detRes.output_data.clear(); // Clear any existing data
  155. for (const auto& val : outputTensorValues)
  156. {
  157. OutputData output;
  158. output.val = val; // Populate OutputData with the value
  159. detRes.output_data.push_back(output); // Add to the result vector
  160. }
  161. return MEC_OK;
  162. }
  163. ClipApp::ClipApp()
  164. : m_inited(false),
  165. m_env(nullptr),
  166. m_session(nullptr) {}
  167. ClipApp::~ClipApp()
  168. {
  169. Dispose();
  170. }
  171. NAMESPACE_CLIP_END
  172. NAMESPACE_MAS_END