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:
- filename: The complete address of the image to be loaded is of type string. For example: “C:\users\downloads\sample.jpg”
- flag: It is an optional argument and determines the mode in which the image is read and can take several values like
- IMREAD_COLOR: The default mode in which the image is loaded if no arguments are provided. It loads the image in BGR format.
- IMREAD_UNCHANGED: It loads the image in the original form. It also includes the alpha channel if present inside the image.
- IMREAD_GRAYSCALE: It loads the image as a grayscale image.
Output: returns Image as a Mat Object
// 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:
- winname or window name: This is the title of the window displaying the image and is of type string.
- image: This is the image to be displayed. Its type is Mat, the C++ image container.
Output: Create a window displaying the image.
// 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: