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.

[code lang=”cpp”]

#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;
}
[/code]

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.

[code lang=”cpp”]
#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;
}
[/code]

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/