How to Display a Matplotlib RGB Image

Displaying Matplotlib RGB images

So we know that matplotlib is awesome for generating graphs and figures.

But what if we wanted to display a simple RGB image? Can we do that with matplotlib?

Of course!

This blog post will show you how to display a Matplotlib RGB image in only a few lines of code…as well as clear up any caveats that you may run into when using OpenCV and matplotlib together.

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

Tutorial: How to Display a Matplotlib RGB Image

Alright, let’s not waste any time. Let’s jump into some code:

The first thing we are going to do is import our matplotlib package. Then we’re going to import the image sub-package of matplotlib, aliasing it as mpimg for convenience. This sub-package handles matplotlib’s image manipulations.

A simple call to the imread method loads our image as a multi-dimensional NumPy array (one for each Red, Green, and Blue component, respectively) and imshow displays our image to our screen.

We can see our image below:

Figure 1: Displaying a Matplotlib RGB image (note how the axes are labeled).

Figure 1: Displaying a Matplotlib RGB image (note how the axes are labeled).

That’s a good start, but how about getting rid of the numbered axes?

By calling plt.axis("off") we can remove our numbered axes.

Executing our code we end up with:

Figure 1: Displaying a Matplotlib RGB image, this time, turning off our axes.

Figure 2: Displaying a Matplotlib RGB image, this time, turning off our axes.

Nothing to it! You can now see that the numbered axes are gone.

The OpenCV Caveat

But of course, we use OpenCV a lot on this blog.

So let’s load up an image using OpenCV and display it with matplotlib:

Again, the code is simple.

But the results aren’t as expected:

Figure 3: Loading an image with OpenCV and displaying it with matplotlib.

Figure 3: Loading an image with OpenCV and displaying it with matplotlib.

Uh-oh. That’s not good.

The colors of our image are clearly wrong!

Why is this?

The answer lies as a caveat with OpenCV.

OpenCV represents RGB images as multi-dimensional NumPy arrays…but in reverse order!

This means that images are actually represented in BGR order rather than RGB!

There’s an easy fix though.

All we need to do is convert the image from BGR to RGB:

Running our script we can see that the colors of our image are now correct:

Figure 4: When using OpenCV and displaying an image using matplotlib, be sure to call cv2.cvtColor first.

Figure 4: When using OpenCV and displaying an image using matplotlib, be sure to call cv2.cvtColor first.

As I said, there’s nothing to displaying matplotlib RGB images!

Summary

In this blog post I showed you how to display matplotlib RGB images.

We made use of matplotlib, pyplot and mpimg to load and display our images.

To remove the axes of the figure, make a call to plt.axis("off").

Just remember that if you are using OpenCV that your images are stored in BGR order rather than RGB!

As long as you remember that, you won’t have any issues!

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!

, ,

28 Responses to How to Display a Matplotlib RGB Image

  1. ChaoYue May 14, 2015 at 6:23 am #

    Hello, very nice tutorial. Actually when I tried to right-click the first image and save it, it can only be saved as *.jpg format, but isn’t it a *png format?

    • Adrian Rosebrock May 14, 2015 at 6:37 am #

      Hey, download the source code to the blog post to grab the original .png image used in the example. I used .jpg in my screenshots just so save bandwidth (since .jpg files are usually smaller than .png files).

  2. Akshay May 19, 2015 at 4:54 am #

    Brilliant! I’d been using the GTK framework instead of QT so I couldn’t see the x,y position of the mouse pointer using the conventional cv2.imshow method. Using matplotlib is so much more useful ! ๐Ÿ™‚

    • Adrian Rosebrock May 19, 2015 at 6:50 am #

      Indeed, matplotlib is quite useful! I’m glad to see that the post helped Akshay!

  3. Ajay December 8, 2015 at 8:41 am #

    The difference in color representation between open cv and mathplot was exactly what I was looking for. Thanks a ton ๐Ÿ™‚

    • Adrian Rosebrock December 8, 2015 at 2:40 pm #

      Happy to help Ajay!

  4. vineetha February 23, 2016 at 9:05 am #

    this is what I was looking for t. thank you!!!

  5. Hami June 13, 2016 at 6:44 am #

    Thanks Adrian,
    I thought it’s because of ‘cmap’ option in imshow.

  6. Juergen Rose August 21, 2016 at 11:13 am #

    It seems, that my issue comes from the combination of matplotlib-1.5.1 and qt-5.7.0. See also https://github.com/matplotlib/matplotlib/issues/6853 .

  7. shubham May 4, 2017 at 8:54 am #

    Hello Adrian,

    I am having 3 numpy (R,G,B)arrays which I am stacking together to plot an RGB image ,so I used “k=np.dstack([R,G,B])”. Now, when I am plotting the image using “plt.imshow(k)”. The RGB image is not displayed correctly.

    I have followed many posts on stackoverflow related to color normalization but still I am not able to display the image correctly. Kindly help.

    • Adrian Rosebrock May 4, 2017 at 12:27 pm #

      Hi Shubham — what do you mean by “the RGB image is not displayed correctly”? What is “incorrect” about it?

      • SHUBHAM May 4, 2017 at 1:58 pm #

        If I am visualising each array(channel either R,G or B) through plt.imshow(), I can see the image clearly but once I use np.dstack and then visualise the RGB image, it is just mixed up and looks like a hotch potch of pixels.Do I need to normalize in plt.imshow(). I have done that but still not able to get the image perfectly.

        Kindly specify if there is another way to display the image.

        • Adrian Rosebrock May 8, 2017 at 12:45 pm #

          It sounds like you’re not properly stacking your channels. Try this:

  8. nueh July 27, 2017 at 6:34 pm #

    Hello Adrian, Is there a way to save the turned pale (like “Figure 3”) imagefile?
    I need to get a “wrong” imagefile.
    (Does “cv2.imwrite” automatically determines BGR or RGB? )

    • Adrian Rosebrock July 28, 2017 at 9:46 am #

      The cv2.imwrite does not automatically determine BGR versus RGB. If you have an RGB image and want to write it back to disk, convert to BGR and then call cv2.imwrite.

  9. Tiago September 21, 2017 at 2:17 am #

    Hello,
    A simplier way is just to do:
    plt.imshow(img[:,:,::-1])

    ๐Ÿ™‚

    • Adrian Rosebrock September 21, 2017 at 7:13 am #

      Yes, that also works as well.

    • Nicola Onofri February 23, 2019 at 11:08 am #

      Even simpler:
      plt.imshow(img[…,::-1])

      ๐Ÿ™‚

  10. Rawan January 28, 2018 at 5:06 am #

    hi,
    I’m facing the same problem with my code.
    my code does a non linear transformation on the image and then i’m plotting the image using matplotlip only and the colors of the image are not the same as the original.
    not using cv2 at all.
    any suggestions?

    • Adrian Rosebrock January 30, 2018 at 10:30 am #

      RGB images are typically have values in the range [0, 255]. If you’re applying a non-linear transform to the image I assume this shifts your pixels outside this range. I would suggest scaling the pixels back in to the appropriate range before displaying them.

  11. Akbar H July 11, 2018 at 12:08 am #

    i got an error like this

    error: (-215) depth == 0 || depth == 2 || depth == 5 in function cvtColor

    how to solve that? thanks

    • Adrian Rosebrock July 13, 2018 at 5:25 am #

      Double-check your input path to “cv2.imread”. The path is invalid, causing “cv2.imread” to return “None”. You can read more about NoneType errors (and how to fix them) in this guide.

  12. Pierre-yves BALOCHE February 28, 2019 at 11:42 pm #

    Hi Adrian,
    Just to share that, if one is using virtualenv settings, the mathplot library raises the issue on MacOX:
    RuntimeError: Python is not installed as a framework.

    Adding the following 2 lines did the trick for me to have it run without problem, no matter the version of mathplot:

    import matplotlib as mpl
    mpl.use(‘TkAgg’)

    Cheers ๐Ÿ˜‰

    • Adrian Rosebrock March 1, 2019 at 5:26 am #

      Awesome, thanks for sharing! ๐Ÿ™‚

  13. asasasassa July 21, 2019 at 5:45 am #

    thank you, article did help

    • Adrian Rosebrock July 25, 2019 at 9:34 am #

      You are welcome!

  14. Akash Jain August 16, 2019 at 1:29 am #

    Exactly what I was looking for ! ๐Ÿ˜

    • Adrian Rosebrock August 16, 2019 at 5:22 am #

      I’m glad it helped you!

Before you leave a comment...

Hey, Adrian here, author of the PyImageSearch blog. I'd love to hear from you, but before you submit a comment, please follow these guidelines:

  1. If you have a question, read the comments first. You should also search this page (i.e., ctrl + f) for keywords related to your question. It's likely that I have already addressed your question in the comments.
  2. If you are copying and pasting code/terminal output, please don't. Reviewing another programmersโ€™ code is a very time consuming and tedious task, and due to the volume of emails and contact requests I receive, I simply cannot do it.
  3. Be respectful of the space. I put a lot of my own personal time into creating these free weekly tutorials. On average, each tutorial takes me 15-20 hours to put together. I love offering these guides to you and I take pride in the content I create. Therefore, I will not approve comments that include large code blocks/terminal output as it destroys the formatting of the page. Kindly be respectful of this space.
  4. Be patient. I receive 200+ comments and emails per day. Due to spam, and my desire to personally answer as many questions as I can, I hand moderate all new comments (typically once per week). I try to answer as many questions as I can, but I'm only one person. Please don't be offended if I cannot get to your question
  5. Do you need priority support? Consider purchasing one of my books and courses. I place customer questions and emails in a separate, special priority queue and answer them first. If you are a customer of mine you will receive a guaranteed response from me. If there's any time left over, I focus on the community at large and attempt to answer as many of those questions as I possibly can.

Thank you for keeping these guidelines in mind before submitting your comment.

Leave a Reply

[email]
[email]