任意個攝像頭數據採集與顯示

       C++中的OpenCV打開多個攝像頭需要聲明多個VideoCapture對象,這是大部分同學能夠想到的。但是如果在不清楚自己設備上連接有多少個攝像頭的情況下,這樣的方式打開攝像頭並採集數據會非常的麻煩。於是本文爲了解決這一問題,有一種新的解決辦法,主要的思想是通過創建指針的形式來完成,並且把創建的指針放入vector中。具體如下:

vector<VideoCapture*> devices  // 指向不同攝像頭

for k=1:n

    VideoCapture* vc = new VideoCapture()  // 這個步驟比較的關鍵

    devices.push_back(vc)

end

       如何達到打開任意個攝像頭呢?本文具體的做法是設定了一個攝像頭個數的最大上限值。通過open函數來判斷是否打開或者存在。最後也比較關鍵的一步是,通過new創建的對象,需要手動釋放空間,用delete對創建的對象做刪除。最後打開任意攝像頭的具體實現如下:

void openAllCameras(bool is_write)
{
        int max_camera_num = 10;
	std::vector<cv::VideoCapture*> devices;
	std::vector<cv::VideoWriter*> writers;
	for (int i = 0; i < max_camera_num; i++)
	{
		cv::VideoCapture* vc = new cv::VideoCapture();
		cv::VideoWriter* vw = new cv::VideoWriter();
		if (vc->open(i)) { 
			std::cout << "open the camera" + std::to_string(i) + " success!" << std::endl;
			devices.push_back(vc);
			if (is_write)  // 寫入視頻到磁盤的對象創建
			{
				vw->open("camera" + std::to_string(i) + ".avi", cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), 
					20.0, cv::Size(vc->get(cv::CAP_PROP_FRAME_WIDTH), vc->get(cv::CAP_PROP_FRAME_HEIGHT)), true);
				writers.push_back(vw);
			}
		} 
		else { // 否則刪除
			delete vc;
			delete vw;
		}
	}

	std::cout << "devices size: "<<devices.size()<<", writers size:"<<writers.size() << std::endl;
	
        
        for (;;) {
		cv::Mat frame;
		for (int i = 0; i < devices.size(); i++) {
			*devices[i] >> frame;
			if (is_write && !writers.empty())
			{
				*writers[i] << frame;
			}
			cv::namedWindow("camera" + std::to_string(i), cv::WINDOW_NORMAL);
			cv::imshow("camera" + std::to_string(i), frame);
		}
		int c = cv::waitKey(33);
		if (c == 27) break;
	}


	for (int i = 0; i < devices.size(); i++)
	{
		delete devices[i];
		delete writers[i];
	}
}

 

發佈了35 篇原創文章 · 獲贊 4 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章