Load & Display Image


Load Image from File and Display


In this section, I will show you how to load an image from a file and display the image using OpenCV library functions.

First of all, open your C++ IDE and create a new project. Then you have to configure the new project for OpenCV. If you have not installed OpenCV or configured the visual studio projects for OpenCV yet, please refer to Installing OpenCV with Visual Studio.

//Uncomment the following line if you are compiling this code in Visual Studio
//#include "stdafx.h"

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
 // Read the image file
 Mat image = imread("D:/My OpenCV Website/Lady with a Guitar.jpg");

 // Check for failure
 if (image.empty()) 
 {
  cout << "Could not open or find the image" << endl;
  cin.get(); //wait for any key press
  return -1;
 }

 String windowName = "The Guitar"; //Name of the window

 namedWindow(windowName); // Create a window

 imshow(windowName, image); // Show our image inside the created window.

 waitKey(0); // Wait for any keystroke in the window

 destroyWindow(windowName); //destroy the created window

 return 0;
}


Copy and paste above simple code snippet into your IDE and run it. Please note that you have to replace "D:/My OpenCV Website/Lady with a Guitar.jpg" in the code with a valid location to an image in your computer. Then you should see a output like the below image.


Loading and Displaying an image with OpenCV


Explanation


Let's go through the above OpenCV program line by line.


//#include "stdafx.h" 
This is the pre-compiled header file generated by Visual Studio IDE. If you are using Visual Studio, please uncomment this line. Otherwise it will give you a compile error.



#include <opencv2/opencv.hpp>
#include <iostream>
opencv2/opencv.hpp header file itself will include all other neccessary header files in OpenCV library. You have to include only this header file in order to compile your OpenCV codes. For more information, please refer OpenCV C++ API. iostream header file should also be included because we use cout in our program to print an error message to the console.



using namespace cv;
using namespace std;
All OpenCV functions, classes and data structures are declared inside cv namespace. So, we have to add the above line in the top of our program. Otherwise we have to append 'cv::' specifier before each OpenCV functions, classes and data structures. (e.g - cv::Mat, cv::imread() , etc). For more information, please refer OpenCV C++ API. We have to use the std namespace also because cout and endl is inside std namespace.



Mat image = imread("D:/My OpenCV Website/Lady with a Guitar.jpg");
The function imread loads an image from a file and returns it as a Mat object. If the function cannot load the image, it will return an empty Mat object.

Arguments of imread(const String& filename, int flags = IMREAD_COLOR)

  1. filename - You have to give the relative or absolute path of an image file. If you are giving the relative path, it should be relative to your cpp file. jped, jpg, bmp, png, tiff and tif image file types are always supported. Other image file types are supported depending on your platform and installed codecs.
  2. flags - There are several possible values for the flag argument. In the above program, I did not pass any value to this argument such that default IMREAD_COLOR argument will be used.
    • IMREAD_UNCHANGED - The image will be loaded as it is. If you want to get the alpha channel in your input image (if it is available), you have to use this flag.
    • IMREAD_GRAYSCALE - The image will be load as a gray-scale image (i.e. - Single channel image, Black and white image)
    • IMREAD_COLOR - The image will be loaded as a BGR image (i.e. - 3 channel image, color image)



 // Check for failure
 if (image.empty()) 
 {
   cout << "Could not open or find the image" << endl;
   cin.get(); //wait for any key press
   return -1;
 }
If imread() function fails to load the image, the returned Mat object will be empty. If the Mat object is empty, image.empty() function will return true. In such scenarios, our program will print an error message to the console and wait for any key press. When the user press any key in the keyboard, the program will exit returning -1. It's a good practice to check whether the image is empty and exit the program. Otherwise your program will crash while trying to execute the imshow() function.



namedWindow(windowName); // Create a window
This function creates a window which can be used to place images and track bars. If a window already exists with the given name, this function does nothing.

Arguments of void namedWindow(const String& winname, int flags = WINDOW_AUTOSIZE)
  1. winname - Title of the window. That name will display in the title bar of the newly created window. This name is the identifier for this window and it will be used in the later OpenCV function calls.
  2. flags - Determine the size of the window. In the above program, I did not pass any value to this argument such that default WINDOW_AUTOSIZE argument will be used.
    • WINDOW_AUTOSIZE - User cannot resize the window. Image will be displayed in its original size. 
    • WINDOW_NORMAL- User can resize the window.



imshow(windowName, image); // Show our image inside the created window.
This function shows the image in a window specified by winname. If the window is created with WINDOW_AUTOSIZE flag, image will be displayed in its original size. Otherwise image may be scaled to the size of the window. If the window has not been created by calling to namedWindow() function, this function will create a window with the WINDOW_AUTOSIZE flag.

Arguments of void imshow(const String& winname, InputArray mat)
  1. winname -  Name of the window which created by namedWindow() function.
  2. mat - Mat object which holds the image




  • int waitKey(int delay = 0)
waitKey() function wait for keypress for certain time, specified by delay (in milliseconds). If delay is zero or negative, it will wait for infinite time. If any key is pressed, this function returns the ASCII value of the key and your program will continue. If there is no key press for the specified time, it will return -1 and program will continue.
  • void destroyWindow(const string& winname)
This function closes the opened window, with the title of winname and deallocate any associated memory usage. This function is not essential for this application because when the program exits, operating system usually close all the opened windows and deallocate any associated memory usage.


Summary

When running this program, the image of 'MyPic.JPG' is loaded into the variable, 'img' of type Mat. Then a window named 'MyWindow' is opened. After that  'img' is loaded to that window. The window with the image will be displayed until any key is pressed.



Create a Blank Image & Display

This program is also very much similar to the previous application. The only difference is that this program creates a blank image instead of loading an existing image from a file.

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include 

using namespace cv;
using namespace std;

int main( int argc, const char** argv )
{
  Mat img(500, 1000, CV_8UC3, Scalar(0,0, 100)); //create an image ( 3 channels, 8 bit image depth, 500 high, 1000 wide, (0, 0, 100) assigned for Blue, Green and Red plane respectively. )

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;
}

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

waitKey(0);  //wait infinite time for a keypress

     destroyWindow("MyWindow"); //destroy the window with the name, "MyWindow"

return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


Before you run this program, put any image file (MyPic.JPG) into the folder where your c++ file is.Otherwise you have to change the first argument of imread() function and give the absolute path to your image file.

You can download this OpenCV visual c++ project from here. (The downloaded file is a compressed .rar folder. So, you have to extract it using Winrar or other suitable software)

Create & Display Image
Create & Display Image

New OpenCV functions
  •  Mat::Mat(int rows, int cols, int type, const Scalar& s);
This is the one of the many constructor available in Mat class. It initialize the Mat object with the value given by the Scalar object

Parameters :
    • rows - Number of rows in the 2D array ( height of the image in pixels)
    • cols - Number of columns in the 2D array ( width of the image in pixels)
    • type - specify the bit depth, data type and number of channels of the image. I gave CV_8UC3 and it specify 8 bit unsigned integers with 3 channels. Here are some of possible inputs for this parameter
      • CV_8UC1 - 8 bit unsigned integers with single channel
      • CV_8UC3 - 8 bit unsigned integers with 3 channels
      • CV_64FC1 - 64 bit floating point value with 1 channels
If you want more details about this, please refer to Data Types for Arrays in the Basics of OpenCV API

    • s - Initialize each array element with the value given by s. In the above application, I gave Scalar(0,0,100). So, it initialize my first channel (Blue plane) with 0, 2nd channel (Green plane) with 0 and 3rd channel (Red Plane) with 100. So, my final image is red. You can try different combinations of these three and see the output image.
Summary
In this program, I created a 3 channel image with 500 height and 1000 width. 8 bit unsigned integer is allocated for each pixel in each channel. (8x3 = 24 bits per each pixel)  And each pixel is assigned with (0,0,100) scalar value. That means 1st channel is all zero, 2nd channel is also all zero and the 3rd channel is all 100. Therefore we can see a red image as the output of the program.



Next Tutorial : Video from File or Webcam



2 comments:

  1. what does return -1 in if function mean?

    ReplyDelete
    Replies
    1. The program will terminate with the exit code of -1. Terminating with non-zero exit code indicates that program does not run successfully.

      Delete