Code, Computer Vision, Technology And Science

Multi-camera Capture using OpenCV (Single-threaded)

I have been working on a project which requires me to stream multiple cameras. So, here I provide an example code to show how I can stream multiple usb cameras simultaneously using OpenCV. I assume you have installed it properly on your PC and already have basic knowledge about it. Without further ado, here is the simplest and cleanest code that I have made:

#include <opencv2\videoio.hpp>
#include <opencv2\highgui.hpp>

using namespace cv;
using namespace std;

void main()
{
	//The number of connected USB camera(s)
	const uint CAM_NUM = 3;

	//This will hold the VideoCapture objects
	VideoCapture camCaptures[CAM_NUM];

	//This will hold the resulting frames from each camera
	Mat camFrames[CAM_NUM];

	//This will be used for highgui window name
	string labels[CAM_NUM];

	//Initialization of VideoCaptures
	for (int i = 0; i < CAM_NUM; i++)
	{
		//Init label for highgui window name
		labels[i] = "Camera " + to_string(i);

		//Opening camera capture stream
		camCaptures[i].open(i);
	}

	//continous loop until 'Esc' key is pressed
	while (waitKey(1) != 27){
		for (int i = 0; i < CAM_NUM; i++)
		{
			//capturing frame-by-frame from each capture
			camCaptures[i] >> camFrames[i];

			//showing the resulting frame using highgui
			imshow(labels[i], camFrames[i]);
		}
	}

	//Releasing all VideoCapture resources
	for (int i = 0; i < CAM_NUM; i++)
	{
		camCaptures[i].release();
	}
}

Please note that this implementation is single-threaded, so it may lag sometimes depending on various aspects (usb bandwidth, cpu, etc). I will try to make a multi-threaded approach next time. I hope this will be helpful for others who also learn about OpenCV in C++.

2 thoughts on “Multi-camera Capture using OpenCV (Single-threaded)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s