Viewing OpenCV matrices with matplotlib (w/ Jupyter Notebook)

While working with OpenCV, constantly popping up a new Window to view the results might not be the most effective way of work. However, we can minimize the burden if we are working on Jupyter Notebook; with matplotlib. Essentially we plot the matrices with matplotlib.pyplot.imshow.

Opening an image

It’s pretty straightforward as you may have been used to, before.

Viewing with Matplotlib

Now comes the fun part, we will use the normal imshow function from matplotlib.pyplot.

Unfortunately, you will be presented with a BGR image (Blue, Green, Red).  Your colors will shift! Let’s take a look at an example.

The image on the left is an RGB image (the original one), and on the right – the image is read on the BGR colorspace; the red and blue channels swapped. A quick fix is to convert the color channel before viewing the image.

Channels beyond RGB

You can actually pick which color channel to use while “plotting” an image with imshow. Let’s see that in action. We are converting our image to the Grayscale colorspace. But the output is not so gray (or so as it seems?)

The image looks quite greenish. The fix is to properly assert the color channel while plotting.

And that fixes the problem. Hope this brief post helps! Thanks for reading 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.