How to read and display image in OpenCV

OpenCV can be used to easily read an image file and display it in a window. The core and highgui modules are needed to achieve this. The image is read into a cv::Mat object. cv::Mat is the modern replacement for the old IplImage object, which came from Intel.

#include <opencv2/highgui.hpp>

// Read image from file
cv::Mat img = cv::imread("foobar.jpg");

// Create a window
cv::namedWindow("foobar");

// Display image in window
cv::imshow("foobar", img);

// Wait for user to press a key in window
cv::waitKey(0);

To be able to compile this code, link with the core and highgui modules using -lopencv_core -lopencv_highgui.

The legacy method to achieve the same using IplImage is:

#include <opencv2/opencv.hpp>

// Read image from file
IplImage* img = cvLoadImage("foobar.jpg");

// Display image in window
cvLoadImage("foobar", img);

// Wait for user to press a key in window
cvWaitKey(0);

Tried with: Ubuntu 12.04 LTS

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.