OpenCV: Resolving NoneType errors

nonetype_output

Each week I receive and respond to at least 2-3 emails and 3-4 blog post comments regarding NoneType  errors in OpenCV and Python.

For beginners, these errors can be hard to diagnose — by definition they aren’t very informative.

Since this question is getting asked so often I decided to dedicate an entire blog post to the topic.

While NoneType  errors can be caused for a nearly unlimited number of reasons, in my experience, both as a computer vision developer and chatting with other programmers here on PyImageSearch, in over 95% of the cases, NoneType  errors in OpenCV are caused by either:

  1. An invalid image path passed to cv2.imread .
  2. A problem reading a frame from a video stream/video file via cv2.VideoCapture  and the associated .read  method.

To learn more about NoneType  errors in OpenCV (and how to avoid them), just keep reading.

Looking for the source code to this post?
Jump right to the downloads section.

OpenCV: Resolving NoneType errors

In the first part of this blog post I’ll discuss exactly what NoneType  errors are in the Python programming language.

I’ll then discuss the two primary reasons you’ll run into NoneType  errors when using OpenCV and Python together.

Finally, I’ll put together an actual example that not only causes a NoneType  error, but also resolves it as well.

What is a NoneType error?

When using the Python programming language you’ll inevitably run into an error that looks like this:

Where something  can be replaced by whatever the name of the actual attribute is.

We see these errors when we think we are working with an instance of a particular Class or Object, but in reality we have the Python built-in type None .

As the name suggests, None  represents the absence of a value, such as when a function call returns an unexpected result or fails entirely.

Here is an example of generating a NoneType  error from the Python shell:

Here I create a variable named foo  and set it to None .

I then try to set the bar  attribute of foo  to True , but since foo  is a NoneType  object, Python will not allow this — hence the error message.

Two reasons for 95% of OpenCV NoneType errors

When using OpenCV and Python bindings, you’re bound to come across NoneType  errors at some point.

In my experience, over 95% of the time these NoneType  errors can be traced back to either an issue with cv2.imread  or cv2.VideoCapture .

I have provided details for each of the cases below.

Case #1: cv2.imread

If you are receiving a NoneType  error and your code is calling cv2.imread , then the likely cause of the error is an invalid file path supplied to cv2.imread .

The cv2.imread  function does not explicitly throw an error message if you give it an invalid file path (i.e., a path to a nonexistent file). Instead, cv2.imread  will simply return None .

Anytime you try to access an attribute of a None  image loaded from disk via cv2.imread  you’ll get a NoneType  error.

Here is an example of trying to load a nonexistent image from disk:

As you can see, cv2.imread  gladly accepts the image path (even though it doesn’t exist), realizes the image path is invalid, and returns None . This is especially confusing for Python programmers who are used to these types of functions throwing exceptions.

As an added bonus, I’ll also mention the AssertionFailed  exception.

If you try to pass an invalid image (i.e., NoneType  image) into another OpenCV function, Python + OpenCV will complain that the image doesn’t have any width, height, or depth information — and how could it, the “image” is a None  object after all!

Here is an example of an error message you might see when loading a nonexistent image from disk and followed by immediately calling an OpenCV function on it:

These types of errors can be harder to debug since there are many reasons why an AssertionError  could be thrown. But in most cases, your first step should be be ensuring that your image was correctly loaded from disk.

A final, more rare problem you may encounter with cv2.imread  is that your image does exist on disk, but you didn’t compile OpenCV with the given image I/O libraries installed.

For example, let’s say you have a .JPEG file on disk and you knew you had the correct path to it.

You then try to load the JPEG file via cv2.imread  and notice a NoneType  or AssertionError .

How can this be?

The file exists!

In this case, you likely forgot to compile OpenCV with JPEG file support enabled.

In Debian/Ubuntu systems, this is caused by a lack of libjpeg  being installed.

For macOS systems, you likely forgot to install the jpeg  library via Homebrew.

To resolve this problem, regardless of operating system, you’ll need to re-compile and re-install OpenCV. Please see this page for more details on how to compile and install OpenCV on your particular system.

Case #2: cv2.VideoCapture and .read

Just like we see NoneType  errors and AssertionError  exceptions when using cv2.imread , you’ll also see these errors when working with video streams/video files as well.

To access a video stream, OpenCV uses the cv2.VideoCapture  which accepts a single argument, either:

  1. string representing the path to a video file on disk.
  2. An integer representing the index of a webcam on your computer.

Working with video streams and video files with OpenCV is more complex than simply loading an image via cv2.imread , but the same rules apply.

If you try to call the .read  method of an instantiated cv2.VideoCapture  (regardless if it’s a video file or webcam stream) and notice a NoneType  error or  AssertionError , then you likely have a problem with either:

  1. The path to your input video file (it’s probably incorrect).
  2. Not having the proper video codecs installed, in which case you’ll need to install the codecs, followed by re-compiling and re-installing OpenCV (see this page for a complete list of tutorials).
  3. Your webcam not being accessible via OpenCV. This could be for any number of reasons, including missing drivers, an incorrect index passed to cv2.VideoCapture , or simply your webcam is not properly attached to your system.

Again, working with video files is more complex than working with simple image files, so make sure you’re systematic in resolving the issue.

First, try to access your webcam via a separate piece of software than OpenCV.

Or, try to load your video file in a movie player.

If both of those work, you likely have a problem with your OpenCV install.

Otherwise, it’s most likely a codec or driver issue.

An example of creating and resolving an OpenCV NoneType error

To demonstrate a NoneType  error in action I decided to create a highly simplified Python + OpenCV script that represents what you might see elsewhere on the PyImageSearch blog.

Open up a new file, name it display_image.py , and insert the following code:

All this script does is:

  • Parse command line arguments.
  • (Attempts to) load an image from disk.
  • Prints the width, height, and depth of the image to the terminal.
  • Displays the image to our screen.

For most Python developers who are familiar with the command line, this script won’t give you any trouble.

But if you’re new to the command line and are unfamiliar/uncomfortable with command line arguments, you can easily run into a NoneType  error if you’re not careful.

How, you might say?

The answer lies in not properly using/understanding command line arguments.

Over the past few years of running this blog, I’ve seen many emails and blog post comments from readers who are trying to modify the .add_argument  function to supply the path to their image file.

DON’T DO THIS — you don’t have to change a single line of argument parsing code.

Instead, what you should do is spend the next 10 minutes reading through this excellent article that explains what command line arguments are and how to use them in Python:

https://www.pyimagesearch.com/2018/03/12/python-argparse-command-line-arguments/

This is required reading if you expect to follow tutorials here on the PyImageSearch blog.

Working with the command line, and therefore command line arguments, are a big part of what it means to be a computer scientist — a lack of command line skills is only going to harm youYou’ll thank me later.

Going back to the example, let’s check the contents of my local directory:

As we can see, I have two files:

  1. display_image.py : My Python script that I’ll be executing shortly.
  2. jemma.png : The photo I’ll be loading from disk.

If I execute the following command I’ll see the jemma.png  image displayed to my screen, along with information on the dimensions of the image:

Figure 1: Loading and displaying an image to my screen with OpenCV and Python.

Figure 1: Loading and displaying an image to my screen with OpenCV and Python.

However, let’s try to load an image path that does not exist:

Sure enough, there is our NoneType  error.

In this case, it was caused because I did not supply a valid image path to cv2.imread .

Summary

In this blog post I discussed NoneType  errors and AssertionError  exceptions in OpenCV and Python.

In the vast majority of these situations, these errors can be attributed to either the cv2.imread  or cv2.VideoCapture  methods.

Whenever you encounter one of these errors, make sure you can load your image/read your frame before continuing. In over 95% of circumstances, your image/frame was not properly read.

Otherwise, if you are using command line arguments and are unfamiliar with them, there is a chance that you aren’t using them properly. In that case, make sure you educate yourself by reading this tutorial on command line arguments — you’ll thank me later.

Anyway, I hope this tutorial has helped you in your journey to OpenCV mastery!

If you’re just getting started studying computer vision and OpenCV, I would highly encourage you to take a look at my book, Practical Python and OpenCV, which will help you grasp the fundamentals.

Otherwise, make sure you enter your email address in the form below to be notified when future blog posts and tutorials are published!

Downloads:

If you would like to download the code and images used in this post, please enter your email address in the form below. Not only will you get a .zip of the code, I’ll also send you 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! Sound good? If so, enter your email address and I’ll send you the code immediately!

, , ,

29 Responses to OpenCV: Resolving NoneType errors

  1. Mika December 26, 2016 at 12:17 pm #

    Great article. If writing production code, one should be kind enough to have some basic tests for inputs. I was kind of puzzled before I tested, if the image file could be opened. OpenCV has many very not descriptive errors

    • Adrian Rosebrock December 27, 2016 at 6:40 am #

      Agreed — writing tests, especially when developing production level OpenCV + Python applications is hugely important.

  2. muhammad tamrin December 26, 2016 at 6:56 pm #

    thanks mr for imformation

  3. Hugh December 27, 2016 at 3:04 pm #

    A simple test can also help in some cases where a multi-threaded frame from a camera is not collected correctly, or an image is not ready.

    image = cv2.imread(path) # from file
    # Check that it was a valid image, otherwise try again
    if (image == None):
    continue

    frame = cthread.read() # from multi-thread USB camera
    # Check that it was a valid frame, otherwise try again
    if frame == None):
    continue

  4. Sinjon March 24, 2017 at 8:28 am #

    Hello Adrian,

    If I still get the NoneType errors when running that downloadable code, what does that mean?

    I’ve run it in terminal with and without the full address of the image, as well as adding in the, h, w and d but am still getting it.

    Any ideas?

    Thanks

    • Adrian Rosebrock March 25, 2017 at 9:24 am #

      If you are still getting NoneType errors after validating that the paths to your images are correct then your version of OpenCV was likely compiled without support to load the image file type.

  5. Ramkrishan Sharma July 6, 2017 at 1:00 am #

    Hello Sir,
    I am getting an open cv error that module object has no attribute cv2.imread ,please solve out this.

    im = cv2.imread(“photo_2.jpg”)
    AttributeError: ‘module’ object has no attribute ‘imread’

    • Adrian Rosebrock July 7, 2017 at 10:01 am #

      How did you install OpenCV? And which operating system are you using?

  6. ashish April 16, 2018 at 5:06 am #

    can i use raspberry pi camera in place of webcam

  7. michell April 30, 2018 at 12:25 pm #

    hello adrian

    I am trying to use your VideoStream code but it gives me an error in the line “freme = inutils.resize (frame, width = 400)” being the famaso error
    “AttributeError: ‘Nometype? Object has no attribute’ shape ‘”

    I have imutils installed and opencv could help me

    Thanks in advance for your attention

    • Adrian Rosebrock April 30, 2018 at 1:04 pm #

      Hi Michell — double check the image path from when you loaded the image. Printing frame to the terminal and see if you have a valid NumPy array.

      • michell April 30, 2018 at 1:47 pm #

        hello adrian

        The path of the image? but should not see the video made by the camera?

        Thank you for your availability.

      • michell May 2, 2018 at 6:21 am #

        hello adrian

        but I’m not loading image from a path but rather doing stremvideo …
        how can I solve?

        Thanks for the availability.

        • Adrian Rosebrock May 3, 2018 at 9:34 am #

          What video stream are you using? A USB camera? Built-in webcam? A Raspberry Pi camera module?

          • michell May 8, 2018 at 7:04 am #

            Hello Adrian,

            I’m using the Raspberry Pi camera module…

          • Adrian Rosebrock May 9, 2018 at 9:45 am #

            Have you validated that the “raspistill” and “raspivid” commands are properly working? What else have you done to validate that you can access your Raspberry Pi camera module?

          • Pete May 9, 2018 at 11:44 am #

            I am also having the same issues. I’m running 4.0.0-pre and using the built in camera module. I was able to test videostream and confirmed “raspistill” and “raspivid” commands are properly working. Any ideas?

          • Adrian Rosebrock May 14, 2018 at 12:25 pm #

            How are you accessing the Raspberry Pi camera via Python code? Are you using the “picamera” Python module? Or are you using OpenCV’s “cv2.VideoCapture”?

      • Dinesh Buswala August 14, 2018 at 3:01 am #

        Hi Adrian, Will you please help me regarding how to zoom in and zoom out an image. I am building my desktop map application for navigating the object from source to destination as well as detecting the object on the map.

        • Adrian Rosebrock August 15, 2018 at 8:35 am #

          OpenCV really isn’t meant to build GUI applications that zoom in and out. You may want to take a look at other dedicated GUI libraries such as Kivy, TKinter, and Qt.

  8. Pete May 9, 2018 at 1:54 pm #

    For all those using the Raspberry Pi and using the built in camera and also receiving an AttributeError: ‘NoneType’ object has no attribute ‘shape’ error:

    1 make sure the camera is enabled
    2 change:
    VideoStream(src=0).start()
    To:
    VideoStream(src=0, usePiCamera=True).start()

    The VideoStream function disables the built in camera by default

  9. Lee SJ May 30, 2018 at 11:19 pm #

    Hello Adrian!
    I’m so thank you for your perfect blogs!
    However, I had a same problem just like abvoe suggestions.

    ================================
    [INFO] loading model…
    [INFO] starting video stream…


    (h, w) = image.shape[:2]
    AttributeError: ‘NoneType’ object has no attribute ‘shape’
    ================================

    After read about your blogs including this blog,
    I found a spot with no values.

    line 35. vs = VideoStream(src=0).start()

    So, I tried to add the only one code following line.

    $ sudo modprobe bcm285-v4l2

    After insert this line, I can compile the your python code like raspberry pi object detection, real time object detection or etc. This is my solution to this problem. I wish this solution can help your blog or else.

    Thank you!

    ps. I want to say sorry about poor English.
    ps2. I successfully finished the school project with your blogs! Thank you again!

    • Adrian Rosebrock May 31, 2018 at 4:54 am #

      Congrats on completing your school project, great job!

      Question: Are you trying to use the VideoStream class on a laptop/desktop with a USB camera? Or are you trying to use your Raspberry Pi with a Raspberry Pi camera module? I need to know more about your setup.

      • Lee SJ May 31, 2018 at 9:36 pm #

        I’m sorry to reply late.
        My project is only focused on the Raspberry Pi with a Raspberry Pi camera module.

        • Adrian Rosebrock June 5, 2018 at 8:31 am #

          Got it, thank you for sharing. For any other readers who are interested — you can either install the drivers as Lee suggested or you can use the VideoStream class instead with usePiCamera=True. I personally prefer the latter.

  10. Neeraj October 2, 2018 at 2:02 pm #

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    AttributeError: module ‘cv2.cv2’ has no attribute ‘cvt’.
    please help me.
    Thanks in advance…

    • Adrian Rosebrock October 8, 2018 at 10:33 am #

      It sounds like you may have a problem with your OpenCV install. Try following one of my OpenCV install guides to help you get OpenCV installed properly.

Trackbacks/Pingbacks

  1. Image hashing with OpenCV and Python - PyImageSearch - November 27, 2017

    […] from disk, likely due to an issue with the image encoding (a phenomenon you can read more about here), so we skip the […]

Leave a Reply