Open In App

Reading and Displaying an image in OpenCV using C++

In this article, we will discuss to open an image using OpenCV (Open Source Computer Vision) in C++. Unlike python, any additional libraries in C++ are not required. OpenCV C++ comes with this amazing image container Mat that handles everything for us. The only change seen from a standard C++ program is the inclusion of namespace cv which contains all the OpenCV functions, classes, and data structures. Following functions are required for reading and displaying an image in OPenCV:

imread(): This function is used to read images and takes the following 2 arguments:



Output: returns Image as a Mat Object

Usage:



// Reading the image file
 Mat image = imread(“C:/users/downloads/default.jpg”, IMREAD_grayscale); 

imshow(): This function is used to display images and takes the following two arguments:

Output: Create a window displaying the image.

Usage:

// Show our image inside the created window
imshow(“Window Name”, image);

Mat::empty(): This helps us in error handling in case the imread() function fails to load the image or the image doesn’t exist at the specified path and tells us if the Mat container is empty or not.

WaitKey(): This function helps to display images for a longer duration by keeping the window open until the user presses a key.

Below is the program for the same:




// C++ program for the above approach
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
  
// Driver code
int main(int argc, char** argv)
{
    // Read the image file as
    // imread("default.jpg");
    Mat image = imread("Enter the Address"
                       "of Input Image",
                       IMREAD_GRAYSCALE);
  
    // Error Handling
    if (image.empty()) {
        cout << "Image File "
             << "Not Found" << endl;
  
        // wait for any key press
        cin.get();
        return -1;
    }
  
    // Show Image inside a window with
    // the name provided
    imshow("Window Name", image);
  
    // Wait for any keystroke
    waitKey(0);
    return 0;
}

Input Image:

Output Image:


Article Tags :