loading...
  1. Load an Image and Display using OpenCV (C++)

Load an Image and Display using OpenCV (C++)

Hello again,

Today, we are going to learn how to read an image from a file and display it using OpenCV. First condition is that you should have an OpenCV Build Environment ready, if you haven’t configured your OpenCV Build environment yet, no problem, refer to this blog post (Step by Step) Install OpenCV 3.3 with Visual Studio 2015 on Windows 10 x64 (2017 DIY).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
 
using namespace cv;
using namespace std;
 
int main( int argc, const char** argv )
{
     Mat img = imread("yourpic.jpg", CV_LOAD_IMAGE_UNCHANGED); //read the image data in the file "MyPic.JPG" and store it in 'img'
 
     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 hit the F5 to run this program, make sure that you put the “yourpic.jpg” into the project folder where all your c++ file are else, you can provide the absolute path to the imread() function to your image location with trailing backslash.
For example, if you absolute path is c:\myfolder\yourpic.jpg , you can use the following:
1
Mat img = imread("c:/myfolder/yourpic.jpg");

 

 

Now, that we have run it successfully, let’s understand what all we did to make it happen. This would serve as a foundation for your later projects.

  • #include “opencv2/highgui/highgui.hpp”
All the important functions such as imread()namedWindow()imshow() and waitKey() etc. are declared in the above header file. So you must include it.
One thing to note is that we are using Mat data structure in our program which is declared in “opencv2/core/core.hpp” header file. But, why don’t we include this header file? It’s because “opencv2/highgui/highgui.hpp” header file includes that header file inside it. So, we don’t need to include it again in our program 🙂
  • using namespace cv;
All the data structures and functions in “opencv2/core/core.hpp” and “opencv2/highgui/highgui.hpp” 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 and data structures. (e.g – cv::Mat, cv::imread() , etc).
If you are not familiar with namespaces, please refer this article.
‘#include <iostream>’ and ‘using namespace std’ are added because we are using ‘cout’ to display some strings in the console.
This is basic C++ and you should be familiar with this.
 
  • Mat img = imread(const string& filename, int flags=CV_LOAD_IMAGE_COLOR)
Mat is a data structure to store images in a matrix. It is declared in “opencv2/core/core.hpp” header file.
imread() is a function declared in “opencv2/highgui/highgui.hpp” header file. It loads an image from a file and stores it in Mat data structure.
Arguments of imread() function
  • filename – location of the file. If you just give the filename only, that image should be in the same folder as your C++ file. Otherwise you have to give the full path to your image.
  • flags – There are four possible inputs
    • CV_LOAD_IMAGE_UNCHANGED – image-depth=8 bits per pixel in each channel,  no. of channels=unchanged
    • CV_LOAD_IMAGE_GRAYSCALE – image depth=8 bits,  no. of channels=1
    • CV_LOAD_IMAGE_COLOR – image-depth=?,  no. of channels=3
    • CV_LOAD_IMAGE_ANYDEPTH – image-depth=unchanged ,  no. of channels=?
    • CV_LOAD_IMAGE_ANYCOLOR – image-depth=?,  no. of channels=unchanged
You can combine these above parameters to get desired image output.
e.g –
CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR – image-depth=unchanged,  no. of channels=unchanged
CV_LOAD_IMAGE_COLOR | CV_LOAD_IMAGE_ANYDEPTH – image-depth=unchanged,  no. of channels=3
If you are not sure what to do, use CV_LOAD_IMAGE_COLOR as the 2nd parameter of imread() function.
To better understand concept of image-depth and channels, you should be familiar with image processing.
For this post, let’s discuss little bit of theory of image processing.
Any digital image consists of pixels. Any pixel should have some value. The minimum value for a pixel is 0 and it represents black and maximum being 255 which represents white.
When the value of the pixel is increased, the intensity of that pixel is also increased.
What is image-depth? The image-depth means the number of bits allocated for each pixel. If it is 8, each pixel can have a value between 0 and 255. If it is 4, each pixel can have a value between 0 to 15.
Here is a simple model of a image with image-depth of 8 bits. Each small box represents a pixel. So, each box may contain a value between 0 to 255.
Here is some properties of the following image.
    •  Image-depth 8 bit
    • 1 channel ( So, this is a grayscale image )
    • The height is 4 pixel
    • The width is 5 pixels
    • The resolution of this image is 4×5.
This is a grayscale image (black and white image) because this image has no color content. If the value of this pixel is higher, it will be shown more brighter. If the value is low, it will be shown more darker.
Color images should consist of at least 3 planes; Red, Green and Blue or RGB. Any color can be created using a particular combination of these 3 colors. Any pixel is a combination of three 3 values. (255, 0, 0) represent pure red. (0, 255, 0) represent pure green. (0, 0, 255) represents pure blue.
In the same way, you can create many color. Image-depth is 24 because each pixel is represented with 8 x 3 bits (8 bits from each channel).
Here is some properties of the following image.
    •  Image-depth 24 bit
    • 3 channels ( So, this is a color image )
    • The height is 4 pixel
    • The width is 5 pixels
    • The resolution of this image is 4×5.

In the above model, top left pixel is (23, 231, 46). It will be shown as a greenish color because the green value(231) of that pixel is larger than the red(23) and blue(46) value.

Continuing further down the code…..

  • if (img.empty())
If imread() function fails to load the image, ‘img’ will not be loaded any data. Therefore ‘img.empty()‘ should return true.
It’s a good practice to check whether the image is loaded successfully and if not exit the program. Otherwise your program will crash when executing imshow()function.
  • void namedWindow(const string& winname, int flags = WINDOW_AUTOSIZE);
This function creates a window.
Parameters –
    • winname – Title of the window. That name will display in the title bar of the newly created window
    • flags – determine the size of the window. There are two options
      • WINDOW_AUTOSIZE – User cannot resize the image. Image will be displayed in its original size
      • CV_WINDOW_NORMAL – Image will resized if you resize the the window
  • void imshow(const string& winname, InputArray mat);
This function shows the image which is stored in the ‘mat’ 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.
Parameters –
    • winname – Title of the window. This name is used to identify the window created by namedWindow() function.
    • mat – hold the image data
  • int waitKey(int delay = 15)
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 ‘YOURPic.JPG‘ is loaded into the variable, ‘img’ of type Mat. Then a window named ‘MyImageWindow‘ is opened. After that  ‘img‘ is loaded to that window. The window with the image will be displayed until any key is pressed.
Hope this posts clears a lot of your doubts and help you better understand foundation level OpenCV functions along with Best Practice.
OpenCV : Motion Tracking with Recording using WebCam (Easy Way) aka Motion Activated Security Camera
OpenCV 2.4 & 3.0 Cheatsheet and Differences (C++)




Leave a Reply

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

Welcome to OpenCV World !! Come as a Guest, stay as a Family