Title: OpenCV Load Image (cv2.imread) - PyImageSearch

URL Source: https://pyimagesearch.com/2021/01/20/opencv-load-image-cv2-imread/

Published Time: 2021-01-20T09:17:35+00:00

Markdown Content:
In this tutorial, you will learn how to use OpenCV and the `cv2.imread` function to:

1.  Load an input image from disk
2.  Determine the image’s width, height, and number of channels
3.  Display the loaded image to our screen
4.  Write the image back out to disk as a different image filetype

![Image 1](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20700%20396'%3E%3C/svg%3E)

By the end of this guide, you will have a good understanding of how to load images from disk with OpenCV.

A dataset of images is essential to practice and understand the operation of the OpenCV library. It allows us to deal with images of different formats and sizes, thus broadening our understanding of how to manipulate images using OpenCV.

[Roboflow](https://roboflow.com/?ref=pyimagesearch) has free tools for each stage of the computer vision pipeline that will streamline your workflows and supercharge your productivity.

Sign up or Log in to your [Roboflow account](https://roboflow.com/?ref=pyimagesearch) to access state of the art dataset libaries and revolutionize your computer vision pipeline.

You can start by choosing your own datasets or using our [PyimageSearch’s assorted library of useful datasets](https://universe.roboflow.com/pyimagesearch?ref=pyimagesearch).

Bring data in any of 40+ formats to [Roboflow](https://roboflow.com/?ref=pyimagesearch), train using any state-of-the-art model architectures, deploy across multiple platforms (API, NVIDIA, browser, iOS, etc), and connect to applications or 3rd party tools.

**To learn how to load an image from disk using OpenCV and** `cv2.imread`**, _just keep reading._**

![Image 2](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20128%20128'%3E%3C/svg%3E)

#### Looking for the source code to this post?

[Jump Right To The Downloads Section](#download-the-code)

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 `` `load_image_opencv.py` ``, a Python script that will load input images from disk using OpenCV and the `cv2.imread` function.

We’ll wrap up this tutorial with a discussion of our results.

### **How do we load images from disk with OpenCV?**

![Image 3](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20700%20396'%3E%3C/svg%3E)

**Figure 1:** To load an image from disk with OpenCV, we can use the `cv2.imread` function.

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:

1.  A **NumPy array** representing the image with the shape `(num_rows, num_cols, num_channels)`, which we’ll discuss later in this tutorial
2.  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](https://pyimagesearch.com/2018/09/19/pip-install-opencv/)** — it will have you up and running in a matter of minutes.

### **Having problems configuring your development environment?**

[![Image 4: Screenshot of PyImageSearch Plus and Google Colab Notebook with Jupyter logo overlaid](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20334'%3E%3C/svg%3E)](https://pyimagesearch.com/pyimagesearch-plus/)

**Figure 2:** Having trouble configuring your dev environment? Want access to pre-configured Jupyter Notebooks running on Google Colab? Be sure to join [PyImageSearch Plus](https://pyimagesearch.com/pyimagesearch-plus/) — you’ll be up and running with this tutorial in a matter of minutes.

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](https://pyimagesearch.com/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 `` `load_image_opencv.py` `` and a couple of test images.

In our script, we’ll first load an image from disk using the OpenCV `` `cv2.imread` `` 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 `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.

**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 `` `cv2.imread` `` function.

We load the input `` `--image` `` to memory on **Line 13** using `cv2.imread`, which returns the `` `image` `` as a NumPy array. Upon success, we obtain the image dimensions `` `(h, w, c)` `` from the shape of the array (**Line 14**) — **I’ll provide more information about caveats regarding this line of code later**.

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 `` `cv2.imshow` `` 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 `` `image` `` we want to display.

From there, we need to call the `` `cv2.waitKey` `` 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 `` `0` `` instructs the `cv2.waitKey` function to wait indefinitely.

Finally, **Line 28** saves the `` `image` `` back to disk. The OpenCV `` `cv2.imwrite` `` function accepts a filename as the first parameter and the `` `image` `` as the second.

The `` `cv2.imwrite` `` function saves a file named `` `“newimage.jpg”` `` that _automatically converts_ the `` `image` `` to JPG format based on the filename extension.

You should now be able to apply OpenCV to:

1.  Load an image from disk
2.  Display it on screen
3.  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

![Image 5](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20463%20500'%3E%3C/svg%3E)

**Figure 3:** Loading an image from disk using OpenCV and `cv2.imread`.

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 `` `cv2.imwrite` `` function.

Note that while the `` `30th_birthday.png` `` image was a PNG file type, OpenCV has _automatically_ converted the image to a JPG file type for us.

Let’s try another image:

$ python load\_image\_opencv.py --image jurassic\_park.png 
width: 577 pixels
height: 433  pixels
channels: 3

![Image 6](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20613%20500'%3E%3C/svg%3E)

**Figure 4:** OpenCV image loading with `cv2.imread`.

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 does `cv2.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:

1.  If you supply an invalid image path to `cv2.imread`, the function will return `None`.
2.  However, our code _assumes_ the image path is correct and thus returns a NumPy array.
3.  But if the returned `image` is `None`, 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? We recommend [PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend).

**Course information:**  
84 total classes • 114+ hours of on-demand code walkthrough videos • Last updated: February 2024  
★★★★★ 4.84 (128 Ratings) • 16,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:**

*   ✓ **84 courses** on essential computer vision, deep learning, and OpenCV topics
*   ✓ **84 Certificates** of Completion
*   ✓ **114+ hours** of on-demand video
*   ✓ **Brand new courses released _regularly_**, 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_ 536+ tutorials** on PyImageSearch
*   ✓ **Easy one-click downloads** for code, datasets, pre-trained models, etc.
*   ✓ **Access** on mobile, laptop, desktop, etc.

[Click here to join PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend)

**Summary**
-----------

In this tutorial, you learned how to load images using OpenCV and the `cv2.imread` function.

We created a Python script to:

1.  Load an image from disk as a NumPy array using the `` `cv2.imread` `` function
2.  Display the image on screen with `cv2.imshow`
3.  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 `` `NoneType` `` Python object upon failure. The function will fail if the file does not exist or if the image format is unsupported by OpenCV.

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!_**

![Image 7](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20410%20567'%3E%3C/svg%3E)

#### 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!