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 ,代碼中包含互斥鎖的句柄初始化以及加鎖解鎖代碼。
