StraDemo.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. #include <chrono>
  2. #include <fstream>
  3. #include <opencv2/opencv.hpp>
  4. #include "Logger.h"
  5. #include "OSTime.h"
  6. #include "SysUtils.h"
  7. #include "Semaphore.h"
  8. #include "MemPool.h"
  9. #include "DetUtils.h"
  10. #include "DetectorAPI.h"
  11. #include "AbandObjDetector.h"
  12. #include "ClipDetector.h"
  13. #include "StrategyAPI.h"
  14. #include "AbandClipStrategy.h"
  15. struct DetectionResult
  16. {
  17. cv::Rect rect;
  18. std::string label;
  19. std::chrono::steady_clock::time_point timestamp;
  20. };
  21. struct CallbackContext
  22. {
  23. masd::Strategy *strategy;
  24. cv::Mat *img;
  25. cv::VideoWriter *videoWriter;
  26. std::vector<DetectionResult> detections;
  27. };
  28. CallbackContext callbackContext;
  29. tzc::Semaphore SEMA;
  30. void SaveDetectorInfo(const char *info)
  31. {
  32. std::ofstream outFile("detector_info.json", std::ios::out | std::ios::app);
  33. if (outFile.is_open())
  34. {
  35. outFile << "{\n\t\"Detector Information\": \"" << info << "\"\n}" << std::endl;
  36. outFile.close();
  37. TZLogInfo("Detector information saved to detector_info.json~~~");
  38. }
  39. else
  40. {
  41. TZLogError("Failed to open file for writing!!!");
  42. }
  43. }
  44. TZ_INT DetectionCallback(SPtr<masd::StreamInfo> &media, void *ctx)
  45. {
  46. CallbackContext *callbackContext = reinterpret_cast<CallbackContext *>(ctx);
  47. if (!callbackContext || !callbackContext->img || callbackContext->strategy == nullptr)
  48. return -1;
  49. cv::Mat *img = callbackContext->img;
  50. masd::Strategy *strategy = callbackContext->strategy;
  51. if (img->empty())
  52. return -1;
  53. auto allDetRst = media->GetAllDetRst();
  54. std::vector<DetectionResult> currentDetections;
  55. for (const auto &detPair : allDetRst)
  56. {
  57. const std::string &detKey = detPair.first;
  58. const auto &detProducing = detPair.second;
  59. cv::Rect bbox;
  60. std::string label;
  61. if (detKey == "Clip")
  62. {
  63. masd::clip::ClipDetectResult clipResult;
  64. if (masd::clip::ClipDetectResult::fromJson(detProducing->Result, clipResult))
  65. {
  66. for (const auto &box : clipResult.boxes)
  67. bbox = cv::Rect(box.x, box.y, box.w, box.h);
  68. }
  69. strategy->DoStrategy(media);
  70. SPtr<masd::StraProducing> straProducing = media->GetStraProducing();
  71. label = straProducing ? straProducing->Result.RstName : "Unknown";
  72. }
  73. currentDetections.push_back({bbox, label, std::chrono::steady_clock::now()});
  74. }
  75. auto &cachedDetections = callbackContext->detections;
  76. const auto now = std::chrono::steady_clock::now();
  77. const std::chrono::seconds timeout(4);
  78. std::vector<DetectionResult> updatedDetections;
  79. for (const auto &detection : cachedDetections)
  80. {
  81. if (now - detection.timestamp < timeout)
  82. updatedDetections.push_back(detection);
  83. }
  84. updatedDetections.insert(updatedDetections.end(), currentDetections.begin(), currentDetections.end());
  85. callbackContext->detections = std::move(updatedDetections);
  86. for (const auto &detection : callbackContext->detections)
  87. {
  88. cv::rectangle(*img, detection.rect, cv::Scalar(0, 255, 0), 2);
  89. cv::putText(*img, detection.label, detection.rect.tl() - cv::Point(0, 10),
  90. cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(0, 255, 0), 2);
  91. }
  92. SEMA.Signal();
  93. return 0;
  94. }
  95. int main()
  96. {
  97. INITIALIZE_LOGGER_NORMAL("test", "./test.log", 1, 100, 6, 1, 1);
  98. masd::MemPool *pool = masd::MEMPOOL;
  99. if (pool->Initialize() != masd::MEC_OK)
  100. return -1;
  101. masd::Detector *abandObjDet = new masd::abandobj::AbandObjDetector("AbandObj", "遗留物检测");
  102. if (abandObjDet == nullptr)
  103. {
  104. Dispose();
  105. return -1;
  106. }
  107. masd::Detector *clipDet = new masd::clip::ClipDetector("Clip", "Clip检测");
  108. if (clipDet == nullptr)
  109. {
  110. Dispose();
  111. return -1;
  112. }
  113. masd::Strategy *strategy = new masd::abandclip::AbandClipStrategy();
  114. if (strategy == nullptr)
  115. {
  116. Dispose();
  117. return -1;
  118. }
  119. std::string initAbandObjParam = "{\"algo\": \"MOG2\", \"factor\": 4, \"short_term_rate\": 0.01, \"short_term_history\": 200, \"long_term_rate\": 0.0005, \"long_term_history\": 5000, \"var_threshold\": 16.0, \"detect_shadows\": true, \"iou_threshold\": 0.6, \"area_threshold\": 625.0, \"perimeter_threshold\": 100.0}";
  120. if (abandObjDet->Initialize(initAbandObjParam) != masd::MEC_OK)
  121. return -1;
  122. std::string initClipParam = "{\"gpu_id\": 0, \"model_path\": \"/home/flechazo/workspace/abandoned-object-detection-algo/clip/models/visual.onnx\"}";
  123. if (clipDet->Initialize(initClipParam) != masd::MEC_OK)
  124. return -1;
  125. if (strategy->Initialize() != masd::MEC_OK)
  126. return -1;
  127. std::string AbandClipConfig = "{\"FeatureThreshold\": -100.0, \"FeatureFilePath\": \"../textfeatures.json\"}";
  128. if (strategy->SetStrategyCfg(AbandClipConfig) != masd::MEC_OK)
  129. return -1;
  130. cv::VideoCapture videoCapture("../../media/video.mp4");
  131. if (!videoCapture.isOpened())
  132. return -1;
  133. cv::VideoWriter videoWriter("output_video.mp4",
  134. cv::VideoWriter::fourcc('X', '2', '6', '4'),
  135. static_cast<TZ_INT>(videoCapture.get(cv::CAP_PROP_FPS)),
  136. cv::Size(static_cast<TZ_INT>(videoCapture.get(cv::CAP_PROP_FRAME_WIDTH)),
  137. static_cast<TZ_INT>(videoCapture.get(cv::CAP_PROP_FRAME_HEIGHT))));
  138. if (!videoWriter.isOpened())
  139. return -1;
  140. cv::Mat frame;
  141. while (videoCapture.read(frame))
  142. {
  143. if (frame.empty())
  144. break;
  145. TZ_INT length = frame.total() * frame.elemSize();
  146. void *allocatedMem = pool->AllocAvailMem(length);
  147. if (!allocatedMem)
  148. break;
  149. std::memset(allocatedMem, 0, length);
  150. SPtr<masd::Media> mediaResource = std::make_shared<masd::Media>(length);
  151. mediaResource->Width = frame.cols;
  152. mediaResource->Height = frame.rows;
  153. mediaResource->DataType = frame.type();
  154. mediaResource->Mem = allocatedMem;
  155. std::memcpy(mediaResource->Mem, frame.data, length);
  156. SPtr<masd::StreamInfo> streamInfo = std::make_shared<masd::StreamInfo>();
  157. streamInfo->SetMediaRsc(mediaResource);
  158. callbackContext.img = new cv::Mat(frame.clone());
  159. callbackContext.videoWriter = &videoWriter;
  160. callbackContext.strategy = strategy;
  161. abandObjDet->DoDetect(streamInfo, DetectionCallback, &callbackContext);
  162. SEMA.Wait();
  163. clipDet->DoDetect(streamInfo, DetectionCallback, &callbackContext);
  164. SEMA.Wait();
  165. videoWriter.write(*callbackContext.img);
  166. pool->ReturnFreeMem(allocatedMem, length);
  167. delete callbackContext.img;
  168. callbackContext.img = nullptr;
  169. }
  170. char detectorInfo[65536];
  171. if (GetInformation(detectorInfo) != masd::MEC_OK)
  172. {
  173. Dispose();
  174. return -1;
  175. }
  176. SaveDetectorInfo(detectorInfo);
  177. TZ_delete(abandObjDet);
  178. TZ_delete(clipDet);
  179. TZ_delete(strategy);
  180. if (Dispose() != masd::MEC_OK)
  181. return -1;
  182. return 0;
  183. }