Read, Display and Write video/images/camera frames

The new OpenCV C++ interface has made the process of image loading and display much easier. If you are a bit familiar with MATLAB then it is even more easier for you. Because in many cases, the MATLAB function names are directly used in OpenCV.

For example, you can read, show and write images using the imread, imshow and imwrite commands respectively.


#include <stdio.h>
#include <opencv2opencv.hpp>
#include <string>
#include <fstream>

using namespace std;

int main(int argc, char* argv[])
{
	// ============= Read, Show, Write Image ===================
	// CAUTION!!! This statement requires a jpg file
        //in the current directory
	cv::Mat img = cv::imread("test.jpg");

	if(img.data!=NULL){
	   cv::Mat scaledimg(img.rows/img.cols*640,640,img.type());
		cv::resize(img,scaledimg,scaledimg.size());

		cv::namedWindow("Image");

		cv::imshow("Image",scaledimg);
// See what happens if you don't use this
		cv::waitKey();
		cv::imwrite("test_scaled.jpg",scaledimg);
	}
	return 0;
}

When the question of video comes, OpenCV has a one stop solution named VideoCapture. It can capture video frames from both a video or a webcam.

#include <stdio.h>
#include <opencv2opencv.hpp>
#include <string>
#include <fstream>

using namespace std;

int main(int argc, char* argv[])
{
	// ============== Capture Camera Frame ====================
	cv::Mat frame;
	// Capturing data from camera
        // Caution: It requires webcam to be attached
	cv::VideoCapture cap(0);
        // you can also use
        // cv::VideoCapture cap("video filename");
        // to capture the frame from a video instead of webcam
	if(!cap.isOpened())
	  printf("No Camera Detected");
	else{
		cv::namedWindow("Webcam Video");
		for(;;){
			cap >> frame; // get a new frame from camera
			cv::imshow("Webcam Video",frame);
			if(cv::waitKey(30) >= 0) break;
		}
	}
	return 0;
}

Note: This post assumes you have OpenCV 2.3 installed. If not, please check the following post
http://www.itanveer.com/2011/installing-opencv-231/

Advertisements

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