How to load and show image in OpenCV using C++?

OpenCVC++Server Side ProgrammingProgramming

In this topic, we will determine how to load and show images using OpenCV in C++. There are the following functions required for loading and showing an image in OpenCV.

  •  Mat: Mat is not a function. It is a data structure, a type of variable. Like int, char, string variable types in C++, Mat is a variable of OpenCV, which creates a matrix data structure to load images inside it. In this program, we wrote 'Mat myImage;'. That means we are declaring a matrix variable named 'myImage'.
  •  namedWindow(): It allocates some memory and creates a window to show the image. It works like a photo frame. In OpenCV, we have to make the function as 'namedWindow("name of the window",flag)'.
  • 3. imread(): This function reads an image from a defined location. This program reads the image from 'C:' drive. To use this function, you have to write it as 'imread("location of the image/name of the image with the extension", flag)'.
  •  imshow(): This function shows the image in the defined window. To use this function you have to write as 'imshow(name of the window", name of the matrix)'.
  •  waitKey(): This is a vital function of OpenCV. To process images and executes operations, we must allow the system some time. If we don't do it, we will not

This function waits for a certain period before closing the program. If you use waitKey(10000), it will close the program after 10 seconds. If you write waitKey(0), it will get the desired output. This function will enable us to give the system the required time to operate. wait for the keystroke from the user. When the user clicks any key from the keyboard, the program will stop. This function has to be written as 'waitKey(milliseconds)'.

  •  destroyWindows(): This function closes all windows. When we create windows, we allocate some memory. destroyWindow() function releases that memory to the system.

The following program shows how to load and show an image using OpenCV Libraries.


using namespace cv;
using namespace std;
int main() {
   Mat myImage;//declaring a matrix named myImage//
   namedWindow("PhotoFrame");//declaring the window to show the image//
   myImage = imread("lakshmi.jpg");//loading the image named lakshme in the matrix//
   if (myImage.empty()) {//If the image is not loaded, show an error message//
      cout << "Couldn't load the image." << endl;
      system("pause");//pause the system and wait for users to press any key//
   imshow("PhotoFrame", myImage);//display the image which is stored in the 'myImage' in the "myWindow" window//  
   destroyWindow("Photoframe");//close the window and release allocate memory//
   waitKey(0);//wait till user press any key
   return 0;

On executing the above program, we get the following output −


Published on 10-Mar-2021 07:43:11