ImageDemo.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. #include <fstream>
  2. #include <opencv2/opencv.hpp>
  3. // libcommon
  4. #include "Logger.h"
  5. #include "OSTime.h"
  6. #include "SysUtils.h"
  7. // libmascommon
  8. #include "MemPool.h"
  9. // deps
  10. #include "DetUtils.h"
  11. #include "ilogger.hpp"
  12. #include "trt_infer.hpp"
  13. // libyolocrowddetector
  14. #include "DetectorAPI.h"
  15. #include "YoloCrowdDetector.h"
  16. // libheadcountstrategy
  17. #include "StrategyAPI.h"
  18. #include "HeadCountStrategy.h"
  19. #define RUN_TEXT_DRAWING 0
  20. struct CallbackContext
  21. {
  22. masd::Strategy* strategy;
  23. cv::Mat* img;
  24. };
  25. void SaveDetectorInfo(const char* info)
  26. {
  27. std::ofstream outFile("detector_info.json", std::ios::out | std::ios::app);
  28. if (outFile.is_open())
  29. {
  30. outFile << "{\n\t\"Detector Information\": \"" << info << "\"\n}" << std::endl;
  31. outFile.close();
  32. TZLogInfo("Detector information saved to detector_info.json~~~");
  33. }
  34. else
  35. {
  36. TZLogError("Failed to open file for writing!!!");
  37. }
  38. }
  39. TZ_INT DetectionCallback(SPtr<masd::StreamInfo>& media, void* ctx)
  40. {
  41. TZLogInfo("Detection callback triggered!~~~");
  42. // Retrieve the context
  43. CallbackContext* callbackContext = reinterpret_cast<CallbackContext*>(ctx);
  44. if (!callbackContext || !callbackContext->img || callbackContext->strategy == nullptr)
  45. {
  46. TZLogError("Error: Invalid context or image pointer!!!");
  47. return -1;
  48. }
  49. cv::Mat* img = callbackContext->img;
  50. masd::Strategy* strategy = callbackContext->strategy;
  51. if (img->empty())
  52. {
  53. TZLogError("Error: Invalid image pointer!!!");
  54. return -1;
  55. }
  56. auto allDetRst = media->GetAllDetRst();
  57. int imgWidth = img->cols, imgHeight = img->rows;
  58. for (auto it = allDetRst.begin(); it != allDetRst.end(); ++it)
  59. {
  60. const std::string& detKey = it->first;
  61. const SPtr<masd::DetProducing>& detProducing = it->second;
  62. TZLogInfo("Detection Key: %s~~~", detKey.c_str());
  63. std::cout << "Detection Result: " << detProducing->Result << std::endl;
  64. if (!detProducing->Draw.Rects.empty())
  65. {
  66. TZLogInfo("Processing Draw Info...~~~");
  67. for (const auto& rect : detProducing->Draw.Rects)
  68. {
  69. TZLogInfo("Rect: LTX: %.2f, LTY: %.2f, "
  70. "RBX: %.2f, RBY: %.2f, Color: %s, Thickness: %d~~~",
  71. rect.LTX, rect.LTY, rect.RBX, rect.RBY,
  72. rect.Color.c_str(), rect.Thickness);
  73. if (!rect.Text.Text.empty())
  74. {
  75. TZLogInfo("Text: %s~~~", rect.Text.Text.c_str());
  76. }
  77. cv::Scalar color;
  78. {
  79. std::stringstream colorStream(rect.Color);
  80. int r, g, b;
  81. char comma;
  82. colorStream >> r >> comma >> g >> comma >> b;
  83. color = cv::Scalar(b, g, r);
  84. }
  85. cv::Point topLeft(rect.LTX * imgWidth, rect.LTY * imgHeight);
  86. cv::Point bottomRight(rect.RBX * imgWidth, rect.RBY * imgHeight);
  87. cv::rectangle(*img, topLeft, bottomRight, color, rect.Thickness);
  88. #if RUN_TEXT_DRAWING
  89. if (!rect.Text.Text.empty())
  90. {
  91. cv::putText(*img, rect.Text.Text,
  92. cv::Point(topLeft.x, topLeft.y - 10),
  93. cv::FONT_HERSHEY_SIMPLEX, 0.8, color, 2);
  94. }
  95. #endif
  96. }
  97. }
  98. else
  99. {
  100. TZLogInfo("No Draw Info available.~~~");
  101. }
  102. if (detProducing->DetMedia)
  103. {
  104. const auto& media = detProducing->DetMedia;
  105. TZLogInfo("Media Length: %d~~~", media->Length);
  106. TZLogInfo("Media DataType: %d~~~", media->DataType);
  107. TZLogInfo("Media Height: %d, Width: %d~~~", media->Height, media->Width);
  108. }
  109. }
  110. // Process the strategy inside the callback
  111. TZ_INT strategyResult = strategy->DoStrategy(media);
  112. if (strategyResult != masd::MEC_OK)
  113. {
  114. TZLogError("Headcount strategy failed to process the stream info!!!");
  115. return -1;
  116. }
  117. TZLogInfo("Headcount strategy processed the stream info successfully~~~");
  118. SPtr<masd::StraProducing> straProducing = media->GetStraProducing();
  119. if (straProducing)
  120. {
  121. std::string headcountResult = straProducing->Result.RstName;
  122. TZLogInfo("Detected headcount: %s", headcountResult.c_str());
  123. }
  124. else
  125. {
  126. TZLogWarn("No headcount result found in the stream info.");
  127. }
  128. if (cv::imwrite("DetRst.jpg", *img))
  129. {
  130. TZLogInfo("Image saved as DetRst.jpg~~~");
  131. }
  132. else
  133. {
  134. TZLogError("Failed to save the image!!!");
  135. }
  136. return 0;
  137. }
  138. int main()
  139. {
  140. // Initialize log
  141. INITIALIZE_LOGGER_NORMAL("test", "./test.log", 1, 100, 6, 1, 1);
  142. // Initialize memory pool
  143. masd::MemPool *pool = masd::MEMPOOL;
  144. if (pool->Initialize() != masd::MEC_OK)
  145. {
  146. TZLogError("Memory pool initialization failed!!!");
  147. return -1;
  148. }
  149. /* Calling libyolocrowddetector and libheadcountstrategy */
  150. // Step 1:
  151. // Initialize the SDK
  152. TZ_INT initResult = Initialize();
  153. if (initResult != masd::MEC_OK)
  154. {
  155. TZLogError("Failed to initialize the SDK!!!");
  156. return -1;
  157. }
  158. TZLogInfo("SDK Initialized Successfully~~~");
  159. // Step 2:
  160. // Build yolo-crowd detector
  161. masd::Detector* detector = BuildDetector();
  162. if (detector == nullptr)
  163. {
  164. TZLogError("Failed to build yolo-crowd detector!!!");
  165. Dispose();
  166. return -1;
  167. }
  168. TZLogInfo("Yolo-crowd detector built successfully~~~");
  169. // Build headcount strategy
  170. masd::Strategy* strategy = BuildStrategy();
  171. if(strategy == nullptr)
  172. {
  173. TZLogError("Failed to build headcount strategy!!!");
  174. Dispose();
  175. return -1;
  176. }
  177. TZLogInfo("Headcount strategy built successfully~~~");
  178. // Step 3:
  179. // Initialize the yolo-crowd detector with configuration parameters
  180. std::string initParam =
  181. "{\"gpu_id\": 0, \"max_objects\": 1024, "
  182. "\"confidence_threshold\": 0.2, \"nms_threshold\": 0.5, "
  183. "\"model_path\": \"../../models/yolo-crowd-output0.trt\"}";
  184. TZ_INT initDetResult = detector->Initialize(initParam);
  185. if (initDetResult != masd::MEC_OK)
  186. {
  187. TZLogError("Failed to initialize the yolo-crowd detector!!!");
  188. DestroyDetector(detector);
  189. DestroyStrategy(strategy);
  190. Dispose();
  191. return -1;
  192. }
  193. TZLogInfo("Yolo-crowd detector initialized successfully~~~");
  194. // Initialize the headcount strategy
  195. TZ_INT initStraResult = strategy->Initialize();
  196. if (initStraResult != masd::MEC_OK)
  197. {
  198. TZLogError("Failed to initialize the headcount detector!!!");
  199. DestroyDetector(detector);
  200. DestroyStrategy(strategy);
  201. Dispose();
  202. return -1;
  203. }
  204. TZLogInfo("Headcount strategy initialized successfully~~~");
  205. // Step 4:
  206. // Set yolo-crowd detection configuration (optional)
  207. std::string detectConfig = R"({
  208. "freq": 0,
  209. "target": {
  210. "target_class": 0,
  211. "target_threshold": 0.25
  212. },
  213. "focusArea": [
  214. { "LTX": 0.0, "LTY": 0.0, "RBX": 1.0, "RBY": 1.0 }
  215. ],
  216. "ignoreArea": [
  217. { "LTX": 0.0, "LTY": 0.0, "RBX": 0.0, "RBY": 0.0 }
  218. ]
  219. })";
  220. TZ_INT setDetCfgResult = detector->SetDetectCfg(detectConfig);
  221. if (setDetCfgResult != masd::MEC_OK)
  222. {
  223. TZLogError("Failed to set yolo-crowd detection configuration!!!");
  224. DestroyDetector(detector);
  225. DestroyStrategy(strategy);
  226. Dispose();
  227. return -1;
  228. }
  229. TZLogInfo("Yolo-crowd detection configuration set successfully~~~");
  230. // Set headcount strategy configuration (optional)
  231. std::string headcountConfig = R"({
  232. "TimeThreshold": 1
  233. })";
  234. TZ_INT setStraCfgResult = strategy->SetStrategyCfg(headcountConfig);
  235. if (setStraCfgResult != masd::MEC_OK)
  236. {
  237. TZLogError("Failed to set headcount strategy configuration!!!");
  238. DestroyDetector(detector);
  239. DestroyStrategy(strategy);
  240. Dispose();
  241. return -1;
  242. }
  243. TZLogInfo("Headcount strategy configuration set successfully~~~");
  244. // Step 5:
  245. // Simulate frame processing with using test image
  246. cv::Mat testImage = cv::imread("../../media/image.jpg");
  247. if (testImage.empty())
  248. {
  249. TZLogError("Failed to load test image!!!");
  250. DestroyDetector(detector);
  251. DestroyStrategy(strategy);
  252. Dispose();
  253. return -1;
  254. }
  255. TZ_INT length = testImage.total() * testImage.elemSize();
  256. SPtr<masd::Media> mediaResource = std::make_shared<masd::Media>(length);
  257. mediaResource->Width = testImage.cols;
  258. mediaResource->Height = testImage.rows;
  259. mediaResource->DataType = testImage.type();
  260. mediaResource->Mem = testImage.data;
  261. SPtr<masd::StreamInfo> streamInfo = std::make_shared<masd::StreamInfo>();
  262. streamInfo->SetMediaRsc(mediaResource);
  263. CallbackContext callbackContext{strategy, &testImage};
  264. detector->DoDetect(streamInfo, DetectionCallback, &callbackContext);
  265. // Step 6:
  266. // Print DetGetInformation
  267. char detectorInfo[4096];
  268. TZ_INT infoResult = GetInformation(detectorInfo);
  269. if (infoResult != masd::MEC_OK)
  270. {
  271. TZLogError("Failed to get detector information!!!");
  272. Dispose();
  273. return -1;
  274. }
  275. SaveDetectorInfo(detectorInfo);
  276. // Step 7:
  277. // Destroy the detector
  278. DestroyDetector(detector);
  279. TZLogInfo("Detector destroyed successfully~~~");
  280. // Destroy the strategy
  281. DestroyStrategy(strategy);
  282. TZLogInfo("Detector strategy successfully~~~");
  283. // Step 8:
  284. // Dispose the SDK
  285. TZ_INT disposeResult = Dispose();
  286. if (disposeResult != masd::MEC_OK)
  287. {
  288. TZLogError("Failed to dispose the SDK!!!");
  289. return -1;
  290. }
  291. TZLogInfo("SDK disposed successfully~~~");
  292. return 0;
  293. }