main.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. #include <opencv2/opencv.hpp>
  2. #include <opencv2/imgproc.hpp>
  3. #include <opencv2/highgui.hpp>
  4. #include <vector>
  5. #include <fstream>
  6. #include <thread>
  7. #include <cmath>
  8. #include "imageBuffer.h"
  9. #include "modulecomm.h"
  10. #include "rawpic.pb.h"
  11. #include "turnstile.pb.h"
  12. #include "yolodetect.h"
  13. #include "detect_turnstile.h"
  14. using namespace std;
  15. using namespace cv;
  16. bool start_up = true;
  17. bool broken_flag = false;
  18. bool test_video = false;
  19. string video_path = "20201231144029.avi";
  20. void * g_turnstile;
  21. string turnstiledata="turnstiledata";
  22. void * mpa_camera;
  23. string cameradata="picfront";
  24. typedef struct frame_info
  25. {
  26. cv::Mat frame;
  27. long long timestamp;
  28. }frame_info;
  29. ConsumerProducerQueue<frame_info> * imageBuffer = new ConsumerProducerQueue<frame_info>(5,true);
  30. //读取视频数据
  31. void ReadFunc(int n)
  32. {
  33. cv::VideoCapture cap(video_path);
  34. if(!cap.isOpened())
  35. {
  36. cout<<"camera failed to open"<<endl;
  37. }
  38. while(1)
  39. {
  40. frame_info frameInfo;
  41. cv::Mat frame;
  42. //读视频的时候加上,读摄像头去掉
  43. if(imageBuffer->isFull())
  44. {
  45. continue;
  46. }
  47. if(cap.read(frame))
  48. {
  49. frameInfo.frame = frame;
  50. imageBuffer->add(frameInfo);
  51. }
  52. else
  53. {
  54. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  55. }
  56. }
  57. }
  58. //从共享内存中接收摄像头数据
  59. void Listencamera(const char * strdata,const unsigned int nSize,const unsigned int index,const QDateTime * dt,const char * strmemname)
  60. {
  61. if(nSize<1000)return;
  62. iv::vision::rawpic pic;
  63. if(false == pic.ParseFromArray(strdata,nSize))
  64. {
  65. std::cout<<"picview Listenpic fail."<<std::endl;
  66. return;
  67. }
  68. cv::Mat mat(pic.height(),pic.width(),pic.mattype());
  69. if(pic.type() == 1)
  70. memcpy(mat.data,pic.picdata().data(),mat.rows*mat.cols*mat.elemSize());
  71. else
  72. {
  73. // mat.release();
  74. std::vector<unsigned char> buff(pic.picdata().data(),pic.picdata().data() + pic.picdata().size());
  75. mat = cv::imdecode(buff,cv::IMREAD_COLOR);
  76. }
  77. frame_info img_info;
  78. img_info.frame = mat;
  79. img_info.timestamp = pic.time();
  80. imageBuffer->add(img_info);
  81. mat.release();
  82. }
  83. //向共享内存中存入闸机检测结果
  84. void SendDetectResult(frame_info &img_info, bool broken_flag, void* g_name)
  85. {
  86. iv::vision::turnstile detectResult;
  87. detectResult.set_state(broken_flag);
  88. iv::vision::rawpic cameraPic;
  89. cameraPic.set_time(img_info.timestamp);
  90. cameraPic.set_elemsize(img_info.frame.elemSize());
  91. cameraPic.set_width(img_info.frame.cols);
  92. cameraPic.set_height(img_info.frame.rows);
  93. cameraPic.set_mattype(img_info.frame.type());
  94. std::vector<int> param = std::vector<int>(2);
  95. param[0] = cv::IMWRITE_JPEG_QUALITY;
  96. param[1] = 95; // default(95) 0-100
  97. std::vector<unsigned char> buff;
  98. cv::imencode(".jpg",img_info.frame,buff,param);
  99. cameraPic.set_picdata(buff.data(),buff.size());
  100. buff.clear();
  101. cameraPic.set_type(2);
  102. detectResult.mutable_pic()->CopyFrom(cameraPic);
  103. std::string out_result = detectResult.SerializeAsString();
  104. iv::modulecomm::ModuleSendMsg(g_name,out_result.data(),out_result.length());
  105. }
  106. int main(int argc, char** argv )
  107. {
  108. if(argc==3)
  109. {
  110. test_video = argv[1];
  111. video_path = argv[2];
  112. }
  113. if(argc==2)
  114. test_video = argv[1];
  115. if(test_video)
  116. std::thread * readthread = new std::thread(ReadFunc,1);
  117. else
  118. mpa_camera= iv::modulecomm::RegisterRecv(&cameradata[0],Listencamera);
  119. g_turnstile = iv::modulecomm::RegisterSend(&turnstiledata[0],1000000,1);
  120. NetworkInfo networkInfo;
  121. networkInfo.networkType = "yolov4-turnstile";
  122. networkInfo.configFilePath = "model/yolov4-turnstile.cfg";
  123. networkInfo.wtsFilePath = "model/yolov4-turnstile.weights";
  124. networkInfo.deviceType = "kGPU";
  125. networkInfo.inputBlobName = "data";
  126. std::string modelname = "model/yolov4-turnstile.engine";
  127. IExecutionContext* yolo_context{nullptr};
  128. YoloDetect detector(networkInfo,modelname);
  129. vector<string> classes = {"open", "close"};
  130. if(start_up)
  131. {
  132. //加载网络模型,0是指定第一块GPU
  133. cudaSetDevice(0);
  134. if(!detector.loadModel(yolo_context))
  135. {
  136. cout<<"load yolo model failed"<<endl;
  137. return -1;
  138. }
  139. //Size size(cap.get(CV_CAP_PROP_FRAME_WIDTH), cap.get(CV_CAP_PROP_FRAME_HEIGHT));
  140. //VideoWriter writer("./data/result.avi", cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), 25, size);
  141. vector<KalmanTracker> trackers;
  142. KalmanTracker::kf_count = 0; // tracking id relies on this, so we have to reset it in each seq.
  143. int frame_count = 0;
  144. bool calculation_flag = false;
  145. frame_info frameInfo;
  146. Mat frame;
  147. long long millseconds; //时间戳
  148. double waittime = (double)getTickCount();
  149. while (1)
  150. {
  151. // if(frame_count>45*30)
  152. //{
  153. //calculation_flag = true;
  154. //break;
  155. //}
  156. if(imageBuffer->isEmpty())
  157. {
  158. double waittotal = (double)getTickCount() - waittime;
  159. if(waittotal/cv::getTickFrequency()>30.0)
  160. {
  161. cout<<"Cant't get frame and quit"<<endl;
  162. break;
  163. }
  164. continue;
  165. }
  166. imageBuffer->consume(frameInfo);
  167. frame = frameInfo.frame;
  168. frame_count++;
  169. //cout<<"Frame_count: "<<frame_count<<" "<<frame.size()<<endl;
  170. double start = (double)getTickCount();
  171. //前向预测
  172. float ignore_thresh=0.4;
  173. float nms_thresh = 0.4;
  174. std::vector<Detection> detect_results;
  175. vector<td::bbox_t> outs;
  176. td::bbox_t result;
  177. if(detector.process(*yolo_context,frame,detect_results,0.4,0.4))
  178. {
  179. for (size_t i = 0; i < detect_results.size(); i++) {
  180. cv::Rect r = detector.get_rect(frame, detect_results[i].bbox,detector.m_input_w,detector.m_input_h);
  181. result.x = r.x;
  182. result.y = r.y;
  183. result.w = r.width;
  184. result.h = r.height;
  185. result.prob = detect_results[i].det_confidence;
  186. result.obj_id = detect_results[i].class_id;
  187. outs.push_back(result);
  188. }
  189. }
  190. double infertime = (double)getTickCount() - start;
  191. //std::cout<< "Total Cost of infertime: " <<infertime*1000.0/cv::getTickFrequency()<<" ms"<<endl;
  192. vector<td::TrackingBox>track_result;
  193. //tracking turnstile
  194. bool track_flag = td::TrackTurnstile(frame_count,trackers,outs,track_result);
  195. td::Drawer(frame, track_result, classes);
  196. double total = (double)getTickCount() - start;
  197. std::cout<< "Total Cost of Detection: " <<total*1000.0/cv::getTickFrequency()<<" ms"<<endl;
  198. SendDetectResult(frameInfo, broken_flag, g_turnstile);
  199. namedWindow("Result",WINDOW_NORMAL);
  200. imshow("Result",frame);
  201. if(waitKey(1) == 'q')
  202. break;
  203. if(waitKey(1) == 's')
  204. waitKey(0);
  205. //writer << frame;
  206. waittime = (double)getTickCount();
  207. }
  208. destroyAllWindows();
  209. if(trackers.size()>0 && calculation_flag)
  210. {
  211. cout<<">>>>>>>>Start Calculation<<<<<<<<"<<endl;
  212. for (auto it = trackers.begin(); it != trackers.end();)
  213. {
  214. int open_count = 0;
  215. int close_count = 0;
  216. int open_hit_streak = 0;
  217. int since_close = 0;
  218. unsigned int history_size = (*it).m_class_history.size();
  219. if (history_size >= 15*30)
  220. {
  221. for(unsigned int j=0;j<history_size;j++)
  222. {
  223. if((*it).m_class_history[j] == 0)
  224. {
  225. open_count ++;
  226. open_hit_streak ++;
  227. }
  228. else
  229. {
  230. close_count ++;
  231. open_hit_streak = 0;
  232. }
  233. if(open_hit_streak>12*30)
  234. {
  235. broken_flag = true;
  236. cout<<"The turnstile is broken"<<endl;
  237. break;
  238. }
  239. }
  240. if(close_count<history_size*0.2 | broken_flag)
  241. {
  242. broken_flag = true;
  243. cout<<"The turnstile is broken"<<endl;
  244. break;
  245. }
  246. it ++;
  247. }
  248. else if(history_size <15*30)
  249. it = trackers.erase(it);
  250. else
  251. it ++;
  252. }
  253. if(!broken_flag)
  254. cout<<"The turnstile is normal"<<endl;
  255. }
  256. else{
  257. cout<<"The time is not enough"<<endl;
  258. }
  259. //将结果传到共享内存
  260. if(!frameInfo.frame.empty())
  261. {
  262. SendDetectResult(frameInfo, broken_flag, g_turnstile);
  263. cout<<"Send result to share memory done !"<<endl;
  264. }
  265. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  266. trackers.clear();
  267. //cap.release();
  268. //writer.release();
  269. }
  270. yolo_context->destroy();
  271. return 0;
  272. }