How to show image in c++ using opencv

Learn how to display or show an image using C++ using OpenCV. In order to display images, we need to have “openCV” with 2 modules which are “core” and “highgui”. These should be downloaded prior to executing the code.

Libraries used in this program

  • core
  • highgui

How to show image in C++ using OpenCV

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main( )
       Mat img;
       img=imread("image.jpg", CV_LOAD_IMAGE_COLOR);   
              cout<<"Could not find the image";
              return -1;
       namedWindow( "window", CV_WINDOW_AUTOSIZE );
       imshow( "window", img ); 
       return 0;

So firstly download the two libraries and include them in your program. Now we include the namespace cv. Then Mat is a keyword that indicates a matrix of that particular image. And then using “imread” method indicating image read function.

We pass either the name of the image file or the address i.e full path as a parameter with “.jpg” extension. And we can even pass color type.  And we check whether the image read is empty or not. If it is empty we return -1 displaying could not find the image as the message. If the image is read, then a new window is created to display the image and the image is shown by method “imshow()” with parameters(“windows”,img) and then returning 0.

So that is how we can display an image using opencv in c++. But we need to download the required modules of “opencv” and include them. We can even run this code in visual studio code by setting up the c/c++ environment and setting the environment variable path.

Also read:

Leave a Reply

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