How to Read Image in Opencv with CPP and python

(Last Updated On: October 14, 2017)

Read Image in Opencv(C++, Python):

We can load  any image file in Opencv C++, python or android. Its steps are very simple and easy.We can show any format of image in opencv like JPG and PNG. We can use three functions from opencv to show , load and save frames   imread(), imshow()  and imwrite().

Mat cv::imread ( const String & filename, int flags = IMREAD_COLOR ) // Read image

void cv::imshow ( Window Name , Mat Object to show  ) // Show image

Void cv::imwrite (  filename, InputArray img) // Write frame in hard drive


But In this post we will only discuss imread function in opencv. Imread function is almost dame in C++ and Pyton with a little different of mat object.

C++ :Mat imread(const string& filename, int flags=IMREAD_COLOR )
Python : image = cv2.imread(filename, flags=cv2.IMREAD_COLOR)


  • Below is the complete code of  imread function in C++
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main()
 Mat src = imread("C:/Users/system/Desktop/a.jpg");

if(! ) // Check for invalid input
 cout << "Could not open or find the image" << std::endl ;
 return -1;

namedWindow( "Display window", WINDOW_AUTOSIZE );
 imshow( "Display window", src ); 

waitKey(0); // Wait for a keystroke in the window
 return 0;


  • imread function in python

import numpy as np
import cv2

img = cv2.imread(‘C:/Users/system/Desktop/a.jpg’,0)
k = cv2.waitKey(0)
if k == 27: # wait for ESC key to exit
elif k == ord(‘s’): # wait for ‘s’ key to save and exit


Write a Reply or Comment