Load and Display image using Opencv c++

Opencv is an image processing library and it is widely used for its ability to alter anything on the image. It was written initially with C language and then most of it are ported to C++ to make use of OOP concept. The reason behind moving from C to C++ is mainly of memory management because Opencv works with lot of memory for a single picture. It needs 3 bytes to store single pixel value of color image.

There are Python and Matlab wrappers available for Opencv library. So if you are more familiar with either of those then explore further. Here we will make use of c++ library directly.

Get the library from opencv github link and there are instructions to install on different platforms.

Enough said, lets see how we can load an image and display using Opencv in c++. In order to run successfully the below code please have some image named sample.jpeg in the same directory/folder and also its important to link and include the Opencv library during compilation.

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

 int main( int argc, char** argv ) {
   cv::Mat image;
   image = cv::imread("sample.jpeg" , CV_LOAD_IMAGE_COLOR);
   if(! image.data ) {
       std::cout <<  "Could not open or find the image" << std::endl ;
       return -1;
   cv::namedWindow("WINDOW-1", cv::WINDOW_AUTOSIZE);
   cv::imshow("WINDOW-1", image);
   return 0;

Command to run : g++ display.cpp -o display pkg-config --cflags --libs opencv

Little Explanation followed by

cv::Mat image;

Mat is a matrix object which is defined in cv namespace. every image will be converted to matrix object where every point in matrix contain 3 byte of information to store RGB values. if you want to see it, print the matrix into console using cout or any other way and see.

image = cv::imread(“sample.jpeg” , CV_LOAD_IMAGE_COLOR);

Imread function is used to load the image to the matrix data type.

CV_LOAD_IMAGE_COLOR, loads the image in color and any transparency will be neglected. There are other flags to load the gray scale and the original content.

cv::namedWindow(“WINDOW-1”, cv::WINDOW_AUTOSIZE);

This function creates a named window for us to display the image.

First param takes up the name of the window.

Second param takes up the flag to determine the size of the window.

Once the window is created we can display the image using imshow function.

cv::imshow(WINDOW-1, image);


This is to persist the window until the user presses any key.

Let me know if you have any queries on the comment section below.

Leave a Reply

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