Subscribe for More
Subscribe for More
Edit Content
Click on the Edit Content button to edit/add the content.

Read, Display and Write an Image using OpenCV

Reading, displaying, and writing images are basic to image processing and computer vision.  Even when cropping, resizing, rotating, or applying different filters to process images, you’ll need to first read in the images. So it’s important that you master these basic operations.

OpenCV, the largest computer vision library in the world has these three built-in functions, let’s find out what exactly each one does:

  1. imread() helps us read an image
  2. imshow() displays an image in a window
  3. imwrite() writes an image into the file directory
We assume you already have OpenCV in your system. If you need to install OpenCV, please visit the relevant link below.
  1. Install OpenCV on Windows
  2. Install OpenCV on MacOS
  3. Install OpenCV on Ubuntu

We will use the following image to demonstrate all the functions here.

Image with a rose flower with snow on top, in foreground and brown background. We will use this same image throughout the post, to demonstrate read, display and write an image.
Example input image we will use throughout this blog.

First, go through this code example. It reads and displays the above image. See, how it contains all the three functions, we just mentioned. As you proceed further, we will discuss every single function used in this implementation. 


# import the cv2 library
import cv2

# The function cv2.imread() is used to read an image.
img_grayscale = cv2.imread('test.jpg',0)

# The function cv2.imshow() is used to display an image in a window.
cv2.imshow('graycsale image',img_grayscale)

# waitKey() waits for a key press to close the window and 0 specifies indefinite loop

# cv2.destroyAllWindows() simply destroys all the windows we created.

# The function cv2.imwrite() is used to write an image.
Download Code To easily follow along this tutorial, please download code by clicking on the button below. It's FREE!


//Include Libraries

// Namespace nullifies the use of cv::function(); 
using namespace std;
using namespace cv;

// Read an image 
Mat img_grayscale = imread("test.jpg", 0);

// Display the image.
imshow("grayscale image", img_grayscale); 

// Wait for a keystroke.   

// Destroys all the windows created                         

// Write the image in the same directory
imwrite("grayscale.jpg", img_grayscale);

Let’s begin by importing the OpenCV library in Python and C++ (as shown below).


# import the cv2 library 
import cv2

In C++, use #include (as shown below) to accomplish the same. Also specifying the namespaces for it lets you refer to function names directly. No need to prepend them with the namespace (e.g. instead of cv::imread(), you can just directly use read()).


//Include Libraries

// Namespace nullifies the use of cv::function(); 
using namespace std;
using namespace cv;

Reading an Image

For reading an image, use the imread() function in OpenCV. Here’s the syntax:

imread(filename, flags)

It takes two arguments:

  1. The first argument is the image name, which requires a fully qualified pathname to the file.
  2. The second argument is an optional flag that lets you specify how the image should be represented. OpenCV offers several options for this flag, but those that are most common include:
  • cv2.IMREAD_UNCHANGED  or -1
  • cv2.IMREAD_GRAYSCALE  or 0
  • cv2.IMREAD_COLOR  or 1

The default value for flags is 1, which will read in the image as a Colored image.  When you want to read in an image in a particular format,  just specify the appropriate flag. To check out the different flag options, click here

It’s also important to note at this point that OpenCV reads color images in BGR format, whereas most other computer vision libraries use the RGB channel format order. So, when using OpenCV with other toolkits, don’t forget to swap the blue and red color channels, as you switch from one library to another.

As shown in the code sections below, we will first read in the test image, using all three flag values described above.


# Read an image
img_color = cv2.imread('test.jpg',cv2.IMREAD_COLOR)
img_grayscale = cv2.imread('test.jpg',cv2.IMREAD_GRAYSCALE)
img_unchanged = cv2.imread('test.jpg',cv2.IMREAD_UNCHANGED)


// Read an image 
Mat img_color = imread("test.jpg", IMREAD_COLOR);
Mat img_grayscale = imread("test.jpg", IMREAD_GRAYSCALE);
Mat img_unchanged = imread("test.jpg", IMREAD_UNCHANGED);



img_color = cv2.imread('test.jpg',1)
img_grayscale = cv2.imread('test.jpg',0)
img_unchanged = cv2.imread('test.jpg',-1)


Mat img_color = imread("test.jpg", 1);
Mat img_grayscale = imread("test.jpg", 0);
Mat img_unchanged = imread("test.jpg", -1);

Displaying an Image

In OpenCV, you display an image using the imshow() function. Here’s the syntax:

imshow(window_name, image)

This function also takes two arguments:

  1. The first argument is the window name that will be displayed on the window.
  2.  The second argument is the image that you want to display. 

To display multiple images at once, specify a new window name for every image you want to display. 

The imshow() function is designed to be used along  with the waitKey() and destroyAllWindows() / destroyWindow() functions. 

The waitKey() function is a keyboard-binding function. 

  • It takes a single argument, which is the time (in milliseconds), for which the window will be displayed.
  • If the user presses any key within this time period, the program continues.
  • If 0 is passed, the program waits indefinitely for a keystroke.
  • You can also set the function to detect specific keystrokes like the Q key or the ESC key on the keyboard, thereby telling more explicitly which key shall trigger which behavior. 

The function destroyAllWindows() destroys all the windows we created. If a specific window needs to be destroyed, give that exact window name as the argument. Using destroyAllWindows() also clears the window or image from the main memory of the system.The code examples below show how the imshow() function is used to display the images you read in.


#Displays image inside a window
cv2.imshow('color image',img_color)  
cv2.imshow('grayscale image',img_grayscale)
cv2.imshow('unchanged image',img_unchanged)

# Waits for a keystroke

# Destroys all the windows created


// Create a window.
namedWindow( "color image", WINDOW_AUTOSIZE );
namedWindow( "grayscale image", WINDOW_AUTOSIZE );
namedWindow( "unchanged image", WINDOW_AUTOSIZE );

// Show the image inside it.
imshow( "color image", img_color ); 
imshow( "grayscale image", img_grayscale );
imshow( "unchanged image", img_unchanged ); 

// Wait for a keystroke.   

// Destroys all the windows created                         

Below is the GIF demonstrating the process of executing the code, visualizing the outputs, and closing the output window:

In the three output screens shown below, you can see:

  1.  The first image is displayed in color
  2.  The next  as grayscale
  3. The third is again in color, as this was the original format of the image (which was read using cv2.IMREAD_UNCHANGED)
Output of the imshow() function. A color image is shown as per options specified in code.
Displaying an image in color using the imshow() function.
Output of the imshow() function. A grayscale image is shown as per options specified in code.
Displaying an image in grayscale using the imshow() function.
Output of the imshow() function. An unchanged image is shown as per options specified in code.
Displaying an unchanged image using the imshow() function.

The below GIF shows execution of the code to read and display the image but without waitKey(). The window gets destroyed within milliseconds, and no output is shown on the screen.

Writing an Image

Finally, let’s discuss how to write/save an image into the file directory, using the imwrite() function. Check out its syntax:

imwrite(filename, image).

  1. The first argument is the filename, which must include the filename extension (for example .png, .jpg etc). OpenCV uses this filename extension to specify the format of the file. 
  2. The second argument is the image you want to save. The function returns True if the image is saved successfully.

Take a look at the code below. See how simple it is to write images to disk. Just specify the filename with its proper extension (with any desired path prepended).  Include the variable name that contains the image data, and you’re done. 




imwrite("grayscale.jpg", img_grayscale);


Here, you learned to use the: 

  • imread(), imshow() and imwrite() functions to read, display, and write images 
  • waitKey() and destroyAllWindows() functions, along with the display function to
    • close the image window on key press
    • and clear any open image window from the memory.

You have to experiment a lot when it comes to the waitkey() function, for it can be quite confusing. The more familiar you get with it, the better you can use it. Do download the complete code to get some hands-on experience. Practice well, as these are the basic building blocks that can actually help you learn and master the OpenCV library → OpenCV colab notebook.

This course is available for FREE only till 22nd Nov.
FREE Python Course
We have designed this Python course in collaboration with for you to build a strong foundation in the essential elements of Python, Jupyter, NumPy and Matplotlib.
FREE OpenCV Crash Course
We have designed this FREE crash course in collaboration with to help you take your first steps into the fascinating world of Artificial Intelligence and Computer Vision. The course will be delivered straight into your mailbox.

Get Started with OpenCV

Subscribe to receive the download link, receive updates, and be notified of bug fixes


Which email should I send you the download link?

Subscribe To Receive
We hate SPAM and promise to keep your email address safe.​
Subscribe Now
About LearnOpenCV

Empowering innovation through education, LearnOpenCV provides in-depth tutorials, code, and guides in AI, Computer Vision, and Deep Learning. Led by Dr. Satya Mallick, we're dedicated to nurturing a community keen on technology breakthroughs.

Copyright © 2024 – BIG VISION LLC Privacy Policy Terms and Conditions