Opencv open image python
In this tutorial you will learn how to:
- Read an image from file (using cv::imread)
- Display an image in an OpenCV window (using cv::imshow)
- Write an image to a file (using cv::imwrite)
Source Code
Explanation
In OpenCV 3 we have multiple modules. Each one takes care of a different area or approach towards image processing. You could already observe this in the structure of the user guide of these tutorials itself. Before you use any of them you first need to include the header files where the content of each individual module is declared.
You’ll almost always end up using the:
- core section, as here are defined the basic building blocks of the library
- imgcodecs module, which provides functions for reading and writing
- highgui module, as this contains the functions to show an image in a window
We also include the iostream to facilitate console line output and input.
By declaring using namespace cv; , in the following, the library functions can be accessed without explicitly stating the namespace.
As a first step, the OpenCV python library is imported. The proper way to do this is to additionally assign it the name cv, which is used in the following to reference the library.
Now, let’s analyze the main code. As a first step, we read the image «starry_night.jpg» from the OpenCV samples. In order to do so, a call to the cv::imread function loads the image using the file path specified by the first argument. The second argument is optional and specifies the format in which we want the image. This may be:
- IMREAD_COLOR loads the image in the BGR 8-bit format. This is the default that is used here.
- IMREAD_UNCHANGED loads the image as is (including the alpha channel if present)
- IMREAD_GRAYSCALE loads the image as an intensity one
After reading in the image data will be stored in a cv::Mat object.
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:
- imread() helps us read an image
- imshow() displays an image in a window
- imwrite() writes an image into the file directory
- Reading an Image
- Displaying an Image
- Writing an Image
- Summary
We will use the following image to demonstrate all the functions here.
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.
Python
# 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.waitKey(0) # cv2.destroyAllWindows() simply destroys all the windows we created. cv2.destroyAllWindows() # The function cv2.imwrite() is used to write an image. cv2.imwrite('grayscale.jpg',img_grayscale)
Download Code To easily follow along this tutorial, please download code by clicking on the button below. It’s FREE!
C++
//Include Libraries #include #include // 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. waitKey(0); // Destroys all the windows created destroyAllWindows(); // 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).
Python:
# 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() ).
C++:
//Include Libraries #include #include // 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:
- The first argument is the image name, which requires a fully qualified pathname to the file.
- 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
Master Generative AI for CV
Get expert guidance, insider tips & tricks. Create stunning images, learn to fine tune diffusion models, advanced Image editing techniques like In-Painting, Instruct Pix2Pix and many more
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.
Python
# 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)
C++
// 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);
Or
Python
img_color = cv2.imread('test.jpg',1) img_grayscale = cv2.imread('test.jpg',0) img_unchanged = cv2.imread('test.jpg',-1)
C++
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:
This function also takes two arguments:
- The first argument is the window name that will be displayed on the window.
- 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.
Python
#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 cv2.waitKey(0) # Destroys all the windows created cv2.destroyAllwindows()
C++
// 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. waitKey(0); // Destroys all the windows created destroyAllWindows();
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:
- The first image is displayed in color
- The next as grayscale
- The third is again in color, as this was the original format of the image (which was read using cv2.IMREAD_UNCHANGED )
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:
- 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.
- 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.
Python
cv2.imwrite('grayscale.jpg',img_grayscale)
C++
imwrite("grayscale.jpg", img_grayscale);
Summary
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.
Subscribe & Download Code
If you liked this article and would like to download code (C++ and Python) and example images used in this post, please click here. Alternately, sign up to receive a free Computer Vision Resource Guide. In our newsletter, we share OpenCV tutorials and examples written in C++/Python, and Computer Vision and Machine Learning algorithms and news.