1 #include <opencv2/core/version.hpp> 2 #include <opencv2/calib3d/calib3d.hpp> 3 #include <opencv2/opencv.hpp> 4 5 using namespace System::Runtime::InteropServices; 6 using namespace System::IO; 7 using namespace System::Data; 8 using namespace System::Drawing; 9 using namespace System::Drawing::Imaging; 10 using namespace System::Runtime::Serialization::Formatters::Binary; 11 using namespace System::Windows::Forms; 12 using namespace System::Threading; 13 14 using namespace FRS; 15 using namespace FRS::Util; 16 using namespace DataAngine; 17 18 HANDLE hMutex = CreateMutex(NULL,FALSE,NULL); 19 20 21 cv::VideoCapture *cap; 22 void Show(){ 23 while (true){ 24 cv::Mat frame; 25 WaitForSingleObject(hMutex, INFINITE); 26 cap>>frame; 27 ReleaseMutex(hMutex); 28 imshow("video", frame); 29 cv::waitKey(1000 / cap->get(CV_CAP_PROP_FPS)); 30 } 31 } 32 int main() 33 { 34 FeatureData ^fa = gcnew FeatureData(); 35 36 //cap.open(0); 37 cap = new cv::VideoCapture(); 38 cap->open("rtsp://admin:admin12345@172.18.132.234:554"); 39 40 if (!cap->isOpened()) 41 { 42 std::cout << "open rtsp error" << std::endl; 43 return 0; 44 } 45 Thread ^showThread = gcnew Thread(gcnew ThreadStart(Show)); 46 showThread->Start(); 47 48 bool stop = true; 49 while (stop) 50 { 51 cv::Mat frame; 52 WaitForSingleObject(hMutex, INFINITE); 53 cap>>frame; 54 ReleaseMutex(hMutex); 55 if (frame.empty()) continue; 56 System::GC::Collect(); 57 58 Thread::Sleep(100); 59 } 60 }
本代码为人脸识别视频处理代码,包含两个线程,其中Show线程为opencv读取rtsp流,主线程代码自填。其中GC::Collect()为程序垃圾回收。
代码本为单线程,书写中发现VideoCapture读取视频流时存在缓存,并有缓存上限,单纯进行主线程视频处理时会因为处理时间较长发生缓存溢出问题,所以增设多线程Show()读取消耗VideoCapture缓存。
增设Show()线程时发现存在两线程同时读取缓存现象,添加互斥锁hMutex ,代码中包含互斥锁的句柄初始化以及加锁解锁代码。