In this tutorial, you will learn how to use OpenCV and the cv2.imread
function to:
- Load an input image from disk
- Determine the image’s width, height, and number of channels
- Display the loaded image to our screen
- Write the image back out to disk as a different image filetype
By the end of this guide, you will have a good understanding of how to load images from disk with OpenCV.
To learn how to load an image from disk using OpenCV and cv2.imread
, just keep reading.
Looking for the source code to this post?
Jump Right To The Downloads SectionOpenCV load image (cv2.imread)
In the first part of this tutorial, we’ll discuss how to load an image from disk using OpenCV and the cv2.imread
function.
From there, you’ll learn how to configure your development environment to install OpenCV.
We will then review our project directory structure, followed by implementing
, a Python script that will load input images from disk using OpenCV and the load_image_opencv.py
cv2.imread
function.
We’ll wrap up this tutorial with a discussion of our results.
How do we load images from disk with OpenCV?
To load an input image from disk using OpenCV, we must use the cv2.imread
function (Figure 1).
The cv2.imread
function accepts a single parameter, the path to where your image lives on your disk:
image = cv2.imread("path/to/image.png")
The OpenCV cv2.imread
function then returns either of two values:
- A NumPy array representing the image with the shape
(num_rows, num_cols, num_channels)
, which we’ll discuss later in this tutorial - A
NoneType
object, implying that the image could not be loaded
Typically, the cv2.imread
function will return None
if the path to the input image is invalid, so be sure to double-check and triple-check your input image paths! The function will also fail for unsupported image file types, although OpenCV can read a wide variety of them, including JPEG, PNG, TIFF, and GIF.
Let’s see how to obtain the OpenCV library before putting the cv2.imread
function into action.
Configuring your development environment
Before digging into image loading with OpenCV, you’ll need to have the library installed on your system.
Luckily, OpenCV is pip-installable:
$ pip install opencv-contrib-python
If you need help configuring your development environment for OpenCV 4.3+, I highly recommend that you read my pip install OpenCV guide — it will have you up and running in a matter of minutes.
Having problems configuring your development environment?
All that said, are you:
- Short on time?
- Learning on your employer’s administratively locked system?
- Wanting to skip the hassle of fighting with the command line, package managers, and virtual environments?
- Ready to run the code right now on your Windows, macOS, or Linux systems?
Then join PyImageSearch Plus today!
Gain access to Jupyter Notebooks for this tutorial and other PyImageSearch guides that are pre-configured to run on Google Colab’s ecosystem right in your web browser! No installation required.
And best of all, these Jupyter Notebooks will run on Windows, macOS, and Linux!
Project structure
Let’s review our project structure. Grab the source code from the “Downloads” section, unzip the content, and navigate to where you saved it:
$ tree . --dirsfirst . ├── 30th_birthday.png ├── jurassic_park.png ├── load_image_opencv.py └── newimage.jpg 0 directories, 4 files
Our project contains a single Python script named
and a couple of test images.load_image_opencv.py
In our script, we’ll first load an image from disk using the OpenCV
function and then display it on screen for assessment. Finally, we’ll save the displayed image back to disk with OpenCV as a new file named cv2.imread
newimage.jpg
.
Let’s now implement our image-loading Python script using OpenCV!
Implementing our OpenCV image loading script
Let’s get started learning how to load an input image from disk using OpenCV.
Create a Python script named load_image_opencv.py
, and insert the following code:
# import the necessary packages import argparse import cv2 # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to input image") args = vars(ap.parse_args())
Start by importing the Python utility package argparse
for command line arguments parsing on Line 2 and the OpenCV library on Line 3.
Notice that the OpenCV developers adopted the name cv2
from version 2.0 of the library and kept this naming convention regardless of the release we’re using (e.g., 3.x, 4.x). We’ll be using the latest version 4.3+ installed as detailed in the previous section.
The argparse
package allows us to pass dynamic arguments to our Python script such that we do not have to hardcode parameter variables that need to be manually changed every time we’d like to alter their values.
If you are unfamiliar with how the argparse
package works, be sure to read my tutorial on the subject.
Lines 6-9 set up our command line argument parser with a single argument containing the path to our input --image
. We set the argument as required, ensuring that a value must always be passed when invoking our Python script.
With our input --image
path dynamically defined, it’s now easy to load the image using OpenCV:
# load the image from disk via "cv2.imread" and then grab the spatial # dimensions, including width, height, and number of channels image = cv2.imread(args["image"]) (h, w, c) = image.shape[:3] # display the image width, height, and number of channels to our # terminal print("width: {} pixels".format(w)) print("height: {} pixels".format(h)) print("channels: {}".format(c))
OpenCV makes reading a wide range of image file types from disk a breeze with the
function.cv2.imread
We load the input
to memory on Line 13 using --image
cv2.imread
, which returns the
as a NumPy array. Upon success, we obtain the image dimensions image
from the shape of the array (Line 14) — I’ll provide more information about caveats regarding this line of code later.(h, w, c)
We can now print the image dimensions (width, height, and number of channels) to the terminal for review (Lines 18-20).
In a future blog post, we’ll talk about what image channels are, but for now keep in mind that the number of channels will be three for color images, representing the Red, Green, and Blue (RGB) components of pixel colors.
But hey, what good is it having an image in memory if we do not know whether it was read correctly by OpenCV? Let’s display the image on screen for verification:
# show the image and wait for a keypress cv2.imshow("Image", image) cv2.waitKey(0) # save the image back to disk (OpenCV handles converting image # filetypes automatically) cv2.imwrite("newimage.jpg", image)
The
OpenCV function is very convenient here, as it displays an image on our screen using only two parameters (Line 23). The first is a string representing the name assigned to the window that will be opened to hold the figure; the second is the cv2.imshow
we want to display.image
From there, we need to call the
function to keep the window opened until a key is pressed (Line 24). This function receives a single parameter corresponding to the time delay (in milliseconds) used to keep the window alive if no key is pressed. The parameter value cv2.waitKey
instructs the 0
cv2.waitKey
function to wait indefinitely.
Finally, Line 28 saves the
back to disk. The OpenCV image
function accepts a filename as the first parameter and the cv2.imwrite
as the second.image
The
function saves a file named cv2.imwrite
that automatically converts the “newimage.jpg”
to JPG format based on the filename extension.image
You should now be able to apply OpenCV to:
- Load an image from disk
- Display it on screen
- Write it back to disk
We’ll review some of the results of those operations in the next section.
OpenCV image loading results
Now it’s time to load images from the disk using OpenCV!
Start by accessing the “Downloads” section of this tutorial to retrieve the source code and example images.
From there, open a terminal, and execute the following command:
$ python load_image_opencv.py --image 30th_birthday.png width: 720 pixels height: 764 pixels channels: 3
For my 30th birthday a couple of years ago, my wife rented a near-replica jeep from Jurassic Park (my favorite movie) for us to drive around for the day.
In Figure 3, you can see that our input image, 30th_birthday.png
, has been loaded from disk using OpenCV and then displayed to your screen.
This image has a width of 720 pixels, a height of 764 pixels, and three channels (one for each Red, Green, and Blue channel, respectively).
Additionally, if you check the contents of our project directory after running the script, you will see a file named newimage.jpg
:
$ ls 30th_birthday.png jurassic_park.png load_image_opencv.py newimage.jpg
This image was saved to disk via OpenCV using the
function.cv2.imwrite
Note that while the
image was a PNG file type, OpenCV has automatically converted the image to a JPG file type for us.30th_birthday.png
Let’s try another image:
$ python load_image_opencv.py --image jurassic_park.png width: 577 pixels height: 433 pixels channels: 3
Continuing on with the Jurassic Park theme in this tutorial, here we have a photo of Ray Arnold (played by Samuel L. Jackson).
This image has a width of 577 pixels, a height of 433 pixels, and three channels.
If you’re brand-new to OpenCV, I suggest you now take the time to play around with the cv2.imread
function. Specifically, experiment with:
- Loading your own images via
cv2.imread
- Trying various image file types and noting which ones OpenCV does/does not support
- Purposely passing incorrect file paths to
cv2.imread
(i.e., what doescv2.imread
return if the input image path is valid)
Speaking of that final bullet item, let’s give that a try now …
What happens if we pass an invalid image path to “cv2.imread”?
You might be wondering what happens if we pass an invalid file path (meaning the path to the input image does not exist on disk) to OpenCV and
?cv2.imread
Let’s find out:
$ python load_image_opencv.py --image path/does/not/exist.png Traceback (most recent call last): File "load_image_opencv.py", line 17, in <module> (h, w, c) = image.shape[:3] AttributeError: 'NoneType' object has no attribute 'shape'
Here I am purposely providing an image path that does not exist on my disk.
When I pass an invalid image path to OpenCV’s cv2.imread
function, cv2.imread
returns None
.
And when I try to grab the image width, height, and number of channels, Python errors out with an AttributeError
, saying that the NoneType
object does not have a shape
attribute.
This error makes sense when you think about it:
- If you supply an invalid image path to
cv2.imread
, the function will returnNone
. - However, our code assumes the image path is correct and thus returns a NumPy array.
- But if the returned
image
isNone
, then it is not a valid NumPy array, hence the error.
Anytime you see these None
or NoneType
errors, your first step in diagnosing and resolving them is to investigate whether your image was successfully read from disk correctly. 99% of the time the error is due to your code assuming a valid image, but in fact the image was not properly read from disk!
What's next? I recommend PyImageSearch University.
30+ total classes • 39h 44m video • Last updated: 12/2021
★★★★★ 4.84 (128 Ratings) • 3,000+ Students Enrolled
I strongly believe that if you had the right teacher you could master computer vision and deep learning.
Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?
That’s not the case.
All you need to master computer vision and deep learning is for someone to explain things to you in simple, intuitive terms. And that’s exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.
If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to successfully and confidently apply computer vision to your work, research, and projects. Join me in computer vision mastery.
Inside PyImageSearch University you'll find:
- ✓ 30+ courses on essential computer vision, deep learning, and OpenCV topics
- ✓ 30+ Certificates of Completion
- ✓ 39h 44m on-demand video
- ✓ Brand new courses released every month, ensuring you can keep up with state-of-the-art techniques
- ✓ Pre-configured Jupyter Notebooks in Google Colab
- ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
- ✓ Access to centralized code repos for all 500+ tutorials on PyImageSearch
- ✓ Easy one-click downloads for code, datasets, pre-trained models, etc.
- ✓ Access on mobile, laptop, desktop, etc.
Summary
In this tutorial, you learned how to load images using OpenCV and the cv2.imread
function.
We created a Python script to:
- Load an image from disk as a NumPy array using the
functioncv2.imread
- Display the image on screen with
cv2.imshow
- Save the image back to disk with
cv2.imwrite
OpenCV conveniently handles reading and writing a wide variety of image file formats (e.g., JPG, PNG, TIFF). The library also simplifies displaying an image on screen and allowing user interaction with the opened window.
If an image cannot be read by OpenCV, you should carefully check if the input filename was given correctly, as the cv2.imread
function returns a
Python object upon failure. The function will fail if the file does not exist or if the image format is unsupported by OpenCV.NoneType
We have also printed the image dimensions to the terminal (width, height, and number of channels), based on the values of the underlying NumPy array shape. Our script then saved the image to disk using the JPG format, taking advantage of OpenCV’s ability to automatically convert the image to the desired file type.
In the next tutorial in this series, you will learn about OpenCV image basics, including what a pixel is, an overview of the image coordinate system, and how to access individual pixel values.
To download the source code to this post (and be notified when future tutorials are published here on PyImageSearch), simply enter your email address in the form below!
Download the Source Code and FREE 17-page Resource Guide
Enter your email address below to get a .zip of the code and a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!
Comment section
Hey, Adrian Rosebrock here, author and creator of PyImageSearch. While I love hearing from readers, a couple years ago I made the tough decision to no longer offer 1:1 help over blog post comments.
At the time I was receiving 200+ emails per day and another 100+ blog post comments. I simply did not have the time to moderate and respond to them all, and the sheer volume of requests was taking a toll on me.
Instead, my goal is to do the most good for the computer vision, deep learning, and OpenCV community at large by focusing my time on authoring high-quality blog posts, tutorials, and books/courses.
If you need help learning computer vision and deep learning, I suggest you refer to my full catalog of books and courses — they have helped tens of thousands of developers, students, and researchers just like yourself learn Computer Vision, Deep Learning, and OpenCV.
Click here to browse my full catalog.