Capturing Video in OpenCV

Capturing video in OpenCV 4.0.1 is quiet simple. In just about 20 lines code you can capture the video from the camera (webcam) of your Computer and manipulate it as you wish. The code is below.

#include "opencv2/opencv.hpp"

using namespace cv;

int main(int, char**)
	VideoCapture cap(0); // open the default camera
	if (!cap.isOpened())  // check if we succeeded
		return -1;

	for (;;)
		Mat frame;
		cap >> frame; // get a new frame from camera
		flip(frame, frame, +1); //flip image horizontally
		imshow("OPENCV Video", frame);

		if (waitKey(30) >= 0) break;
	// the camera will be deinitialized automatically in VideoCapture destructor
	return 0;

Insert the code above in your IDE, build and run ( I use Visual Studio 2015 ); the result is shown below:

For comparison, I ran the built-in windows camera app. The result is shown below:

From here on you can perform any manipulations you wish. Like this cool color inversion.

Just by adding :

frame= ~frame;

before imshow  function.

Hope this was fun and informative. Don’t stop here, keep experimenting and have fun along the way.

Leave a comment

Your email address will not be published. Required fields are marked *