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 <opencv2\opencv.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 <opencv2\opencv.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/

Share on Twitter

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>