1. 程式人生 > >雙執行緒讀取兩路攝像頭資料

雙執行緒讀取兩路攝像頭資料


利用windows.h中的CreateThread來建立多執行緒,並基於OpenCV中的VideoCapture實現攝像頭讀取操作。在此簡單記錄一下。

#include <windows.h>
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
HANDLE HThread1, HThread2;
cv::Mat g_matFrame1, g_matFrame2;
void thread1()
{
	VideoCapture capture;
	capture.open(0);
	while (1)
	{
		capture >> g_matFrame1;
	}
}
void thread2()
{
	VideoCapture capture;
	capture.open(1);
	while (1)
	{
		capture >> g_matFrame2;
	}
}

int main()
{
	HThread1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)thread1, NULL, 0, 0);
	HThread2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)thread2, NULL, 0, 0);
	int iFrameCount = 0;
	while (1)
	{
		if (g_matFrame1.empty() || g_matFrame2.empty())
		{
			printf("empty frame!\n");
			continue;
		}
		printf("Frame: %d\n", iFrameCount);
		imshow("camera 1:", g_matFrame1);
		imshow("camera 2:", g_matFrame2);
		waitKey(30);
		iFrameCount++;
	}
	CloseHandle(HThread1);
	CloseHandle(HThread2);
	return 0;
}