VideoDemo.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. #include <fstream>
  2. #include <opencv2/dnn.hpp>
  3. #include <opencv2/opencv.hpp>
  4. // libcommon
  5. #include "Logger.h"
  6. #include "OSTime.h"
  7. #include "SysUtils.h"
  8. #include "Semaphore.h"
  9. // libmascommon
  10. #include "MemPool.h"
  11. // deps
  12. #include "DetUtils.h"
  13. // libabndobjdetector
  14. #include "DetectorAPI.h"
  15. #include "AbandObjDetector.h"
  16. // libheadcountstrategy
  17. //#include "StrategyAPI.h"
  18. //#include "HeadCountStrategy.h"
  19. struct CallbackContext
  20. {
  21. cv::Mat* img;
  22. cv::VideoWriter* videoWriter;
  23. };
  24. CallbackContext callbackContext;
  25. tzc::Semaphore SEMA;
  26. void SaveDetectorInfo(const char* info)
  27. {
  28. std::ofstream outFile("detector_info.json", std::ios::out | std::ios::app);
  29. if (outFile.is_open())
  30. {
  31. outFile << "{\n\t\"Detector Information\": \"" << info << "\"\n}" << std::endl;
  32. outFile.close();
  33. TZLogInfo("Detector information saved to detector_info.json~~~");
  34. }
  35. else
  36. {
  37. TZLogError("Failed to open file for writing!!!");
  38. }
  39. }
  40. TZ_INT DetectionCallback(SPtr<masd::StreamInfo>& media, void* ctx)
  41. {
  42. TZLogInfo("Detection callback triggered!~~~");
  43. // Retrieve the context
  44. CallbackContext* callbackContext = reinterpret_cast<CallbackContext*>(ctx);
  45. if ((callbackContext == nullptr) ||
  46. (callbackContext->img == nullptr) ||
  47. (callbackContext->videoWriter == nullptr) ||
  48. (!callbackContext->videoWriter->isOpened()))
  49. {
  50. TZLogError("Error: Invalid context, image pointer, or uninitialized video writer!!!");
  51. return -1;
  52. }
  53. cv::Mat* img = callbackContext->img;
  54. if (img->empty())
  55. {
  56. TZLogError("Error: Invalid image pointer!!!");
  57. return -1;
  58. }
  59. auto allDetRst = media->GetAllDetRst();
  60. int imgWidth = img->cols, imgHeight = img->rows;
  61. for (auto it = allDetRst.begin(); it != allDetRst.end(); ++it)
  62. {
  63. const std::string& detKey = it->first;
  64. const SPtr<masd::DetProducing>& detProducing = it->second;
  65. TZLogInfo("Detection Key: %s~~~", detKey.c_str());
  66. TZLogInfo("Detection Result: %s~~~", detProducing->Result.c_str());
  67. if (!detProducing->Draw.Rects.empty())
  68. {
  69. TZLogInfo("Processing Draw Info...~~~");
  70. for (const auto& rect : detProducing->Draw.Rects)
  71. {
  72. TZLogInfo("Rect: LTX: %.2f, LTY: %.2f, "
  73. "RBX: %.2f, RBY: %.2f, Color: %s, Thickness: %d~~~",
  74. rect.LTX, rect.LTY, rect.RBX, rect.RBY,
  75. rect.Color.c_str(), rect.Thickness);
  76. if (!rect.Text.Text.empty())
  77. {
  78. TZLogInfo("Text: %s~~~", rect.Text.Text.c_str());
  79. }
  80. cv::Scalar color;
  81. {
  82. std::stringstream colorStream(rect.Color);
  83. int r, g, b;
  84. char comma;
  85. colorStream >> r >> comma >> g >> comma >> b;
  86. color = cv::Scalar(b, g, r);
  87. }
  88. cv::Point topLeft(rect.LTX * imgWidth, rect.LTY * imgHeight);
  89. cv::Point bottomRight(rect.RBX * imgWidth, rect.RBY * imgHeight);
  90. cv::rectangle(*img, topLeft, bottomRight, color, rect.Thickness);
  91. }
  92. }
  93. else
  94. {
  95. TZLogInfo("No Draw Info available.~~~");
  96. }
  97. if (detProducing->DetMedia)
  98. {
  99. const auto& media = detProducing->DetMedia;
  100. TZLogInfo("Media Length: %d~~~", media->Length);
  101. TZLogInfo("Media DataType: %d~~~", media->DataType);
  102. TZLogInfo("Media Height: %d, Width: %d~~~", media->Height, media->Width);
  103. }
  104. }
  105. callbackContext->videoWriter->write(*img);
  106. SEMA.Signal();
  107. return 0;
  108. }
  109. int main()
  110. {
  111. // Initialize log
  112. INITIALIZE_LOGGER_NORMAL("test", "./test.log", 1, 100, 6, 1, 1);
  113. // Initialize memory pool
  114. masd::MemPool *pool = masd::MEMPOOL;
  115. if (pool->Initialize() != masd::MEC_OK)
  116. {
  117. TZLogError("Memory pool initialization failed!!!");
  118. return -1;
  119. }
  120. /* Calling libyolocrowddetector and libheadcountstrategy */
  121. // Step 1:
  122. // Initialize the SDK
  123. TZ_INT initResult = Initialize();
  124. if (initResult != masd::MEC_OK)
  125. {
  126. TZLogError("Failed to initialize the SDK!!!");
  127. return -1;
  128. }
  129. TZLogInfo("SDK Initialized Successfully~~~");
  130. // Step 2:
  131. // Build abandobj detector
  132. masd::Detector* detector = BuildDetector();
  133. if (detector == nullptr)
  134. {
  135. TZLogError("Failed to build abndobj detector!!!");
  136. Dispose();
  137. return -1;
  138. }
  139. TZLogInfo("AbandObj detector built successfully~~~");
  140. // Step 3:
  141. // Initialize the yolo-crowd detector with configuration parameters
  142. const std::string initParam = R"(
  143. {
  144. "algo": "MOG2",
  145. "video_path": "../../media/video_cutter.mp4",
  146. "factor": 4,
  147. "short_term_rate": 0.01,
  148. "short_term_history": 200,
  149. "long_term_rate": 0.0005,
  150. "long_term_history": 5000,
  151. "var_threshold": 16.0,
  152. "detect_shadows": false,
  153. "iou_threshold": 0.6,
  154. "area_threshold": 625.0,
  155. "perimeter_threshold": 100.0
  156. }
  157. )";
  158. TZ_INT initDetResult = detector->Initialize(initParam);
  159. if (initDetResult != masd::MEC_OK)
  160. {
  161. TZLogError("Failed to initialize the abandobj detector!!!");
  162. DestroyDetector(detector);
  163. Dispose();
  164. return -1;
  165. }
  166. TZLogInfo("AbandObj detector initialized successfully~~~");
  167. // Step 5:
  168. // Simulate frame processing with using test MP4
  169. cv::VideoCapture videoCapture("../../media/video.mp4");
  170. if(!videoCapture.isOpened())
  171. {
  172. TZLogError("Failed to load test video!!!");
  173. DestroyDetector(detector);
  174. Dispose();
  175. return -1;
  176. }
  177. TZ_INT videoWidth = static_cast<TZ_INT>(videoCapture.get(cv::CAP_PROP_FRAME_WIDTH));
  178. TZ_INT videoHeight = static_cast<TZ_INT>(videoCapture.get(cv::CAP_PROP_FRAME_HEIGHT));
  179. TZ_INT videoFPS = static_cast<TZ_INT>(videoCapture.get(cv::CAP_PROP_FPS));
  180. cv::VideoWriter videoWriter("output_video.mp4",
  181. cv::VideoWriter::fourcc('X', '2', '6', '4'),
  182. videoFPS, cv::Size(videoWidth, videoHeight));
  183. if (!videoWriter.isOpened())
  184. {
  185. TZLogError("Failed to open video writer!!!");
  186. DestroyDetector(detector);
  187. Dispose();
  188. return -1;
  189. }
  190. cv::Mat frame;
  191. while(videoCapture.read(frame))
  192. {
  193. if(frame.empty())
  194. {
  195. TZLogError("Failed to read frame from video!!!");
  196. break;
  197. }
  198. TZ_INT length = frame.total() * frame.elemSize();
  199. void* allocatedMem = pool->AllocAvailMem(length);
  200. if (!allocatedMem)
  201. {
  202. TZLogError("Failed to allocate memory from the pool!");
  203. break;
  204. }
  205. SPtr<masd::Media> mediaResource = std::make_shared<masd::Media>(length);
  206. mediaResource->Width = frame.cols;
  207. mediaResource->Height = frame.rows;
  208. mediaResource->DataType = frame.type();
  209. mediaResource->Mem = allocatedMem;
  210. std::memcpy(mediaResource->Mem, frame.data, length);
  211. SPtr<masd::StreamInfo> streamInfo = std::make_shared<masd::StreamInfo>();
  212. streamInfo->SetMediaRsc(mediaResource);
  213. callbackContext.img = new cv::Mat(frame.clone());
  214. callbackContext.videoWriter = &videoWriter;
  215. detector->DoDetect(streamInfo, DetectionCallback, &callbackContext);
  216. SEMA.Wait();
  217. pool->ReturnFreeMem(allocatedMem, length);
  218. TZ_delete(callbackContext.img);
  219. }
  220. // Step 6:
  221. // Print DetGetInformation
  222. char detectorInfo[4096];
  223. TZ_INT infoResult = GetInformation(detectorInfo);
  224. if (infoResult != masd::MEC_OK)
  225. {
  226. TZLogError("Failed to get detector information!!!");
  227. Dispose();
  228. return -1;
  229. }
  230. SaveDetectorInfo(detectorInfo);
  231. // Step 7:
  232. // Destroy the detector
  233. DestroyDetector(detector);
  234. TZLogInfo("Detector destroyed successfully~~~");
  235. // Step 8:
  236. // Dispose the SDK
  237. TZ_INT disposeResult = Dispose();
  238. if (disposeResult != masd::MEC_OK)
  239. {
  240. TZLogError("Failed to dispose the SDK!!!");
  241. return -1;
  242. }
  243. TZLogInfo("SDK disposed successfully~~~");
  244. return 0;
  245. }