Read and Display

In order to read and display an image in the C++ using OpenCV, you have to load “opencv2/highgui/highgui.hpp” and “opencv2/core/core.hpp”. Here, I’ve used “opencv2/highgui/highgui.hpp” only, because it calls implicitly “opencv2/core/core.hpp”.

#include "opencv2/highgui/highgui.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main()
      //read the image data in the file "MyPic.JPG" and store it in 'img'
      Mat img = imread("MyPic.JPG", CV_LOAD_IMAGE_UNCHANGED); 

      if (img.empty()) //check whether the image is loaded or not
           cout << "Error : Image cannot be loaded..!!" << endl;
           //system("pause"); //wait for a key press
           return -1;

      //create a window with the name "MyWindow"
      namedWindow("MyWindow", CV_WINDOW_AUTOSIZE);
      //display the image which is stored in the 'img' in the "MyWindow" window
      imshow("MyWindow", img); 

      //wait infinite time for a keypress

      //destroy the window with the name, "MyWindow"      

      return 0;

Before running this program, put the image in the folder of c++ or give path of image. CV_LOAD_IMAGE_UNCHANGED is used to load the image here.

To compile use

$ sudo g++ -o nameofFile nameofFile.cpp `pkg-config opencv --cflags --libs`

To run use

$ ./nameofFile

Published by


I am the one who discover myself daily through reading, writing, interacting with people and expressing my thoughts to inspire them if I would be able to bring a little change to the society through my work. I write blogs, participate in various social activities and want to be a Professional Speaker. Currently, I am pursuing my post graduation in Computer Applications from Guru Nanak Dev Engineering College, Ludhiana and I’m very much active in many technical & social communities.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

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