Matplotlib How to Show Figure2 Again
I call back a better title for this weblog post might be: How I lost a mean solar day of productivity to Ubuntu, virtual environments, matplotlib, and rendering backends.
Over the weekend I was playing around with deep learning on my Ubuntu system and went to plot the accuracy scores of my classifier. I coded up a quick Python script using matplotlib, executed the script, only to non have the figure displayed to my screen.
My script executed simply fine. No fault messages. No warnings. Just there was withal no plot to be found!
This is really a common problem I've ran into over the by few months, especially when working with Debian based operating systems such every bit Ubuntu and Raspbian. This issue is only further compounded when utilizing virtual environments via the virtualenv and virtualenvwrapper packages.
The issue actually stems from the matplotlib backend not being properly set, or from a missing dependency when compiling and installing matplotlib. Luckily, later a lot of trial and error (and spending an entire mean solar day trying to come up with a solution), I have been able to resolve the trouble and become matplotlib figures to show up and brandish on my screen on both the Ubuntu and Raspbian operating systems (and when using Python virtual environments).
While this mail is not exactly related to computer vision or OpenCV, I still desire to share my experience and solution with other PyImageSearch readers. Matplotlib is a heavily used packet in the Python scientific community and I hope that this article helps other readers resolve this strange and hard to pinpoint upshot.
Setting the stage
Let'south go ahead and set the stage.
- We're using a Debian based operating system such as Ubuntu or Raspbian.
- We're (optionally) utilizing Python virtual environments via virtualenv and virtualenvwrapper.
- And our goal is to take the following image (left) and compute a grayscale pixel intensity histogram for it using matplotlib (right):
Since nosotros are using matplotlib, let's create a new virtual environment chosen plotting
:
$ mkvirtualenv plotting
Now that we're in the plotting
environs, permit'southward install numpy
, scipy
, and matplotlib
:
$ pip install numpy $ pip install scipy $ pip install matplotlib
Crawly — all of our Python dependencies are installed. At present, let'due south write a few lines of code to load the image, convert it to grayscale, compute a histogram over the grayscale image, and finally brandish it to our screen. I'll throw all this lawmaking into a file named grayscale_histogram.py
:
# import the necessary packages from matplotlib import pyplot as plt import cv2 # load the image, catechumen it to grayscale, and show it image = cv2.imread("raptors.jpg") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imshow("Prototype", image) cv2.imshow("Greyness", gray) cv2.waitKey(0) # construct a grayscale histogram hist = cv2.calcHist([gray], [0], None, [256], [0, 256]) # plot the histogram plt.figure() plt.championship("Grayscale Histogram") plt.xlabel("Bins") plt.ylabel("# of Pixels") plt.plot(hist) plt.xlim([0, 256]) plt.show() cv2.waitKey(0)
The lawmaking hither is fairly straightforward. Lines i and 2 import matplotlib
and cv2
. We then load our image and convert information technology to grayscale (Lines four-9). From in that location the cv2.calcHist
function is used to compute a histogram over the grayscale pixel intensities. Finally, Lines 14-22 plot the histogram using matplotlib
.
To execute our script, all nosotros need to do is fire upwardly and trounce and consequence the following control:
$ python grayscale_histogram.py
When I execute the code on my OSX machine in the plotting
virtual surround, the histogram is computed and both the grayscale paradigm and histogram are displayed to my screen:
Withal, when I go over to my Ubuntu 14.04 machine and execute the exact same lawmaking all I run across are my images:
Which leads to the question: "Where is the histogram?"
As we tin come across from the final output, the script executed only fine. No errors were displayed. No warning letters printed to my console. Simply nevertheless there is not plot!
Resolved: Matplotlib figures not showing upwardly or displaying
As I hinted at earlier in this post, the missing figure issue is related to the matplotlib backend that does all the heavy lifting behind the scenes to set up the figure.
Popping into a vanquish, I tin can access the matplotlib backend using the matplotlib.get_backend()
:
$ python Python iii.4.0 (default, April eleven 2014, xiii:05:11) [GCC 4.eight.two] on linux Type "help", "copyright", "credits" or "license" for more than data. >>> import matplotlib >>> matplotlib.get_backend() 'agg'
On my Ubuntu automobile this gives me a value of agg
; yet, through my testing and debugging, this value needs to exist TkAgg
for the TkInter windowing arrangement (at least when using Ubuntu and Raspbian).
Luckily, we can resolve this outcome by using apt-get
to install a few libraries:
$ sudo apt-get install tcl-dev tk-dev python-tk python3-tk
Simply we're not quite washed yet. In order to get matplotlib to recognize the TkInter GUI library, nosotros need to:
- Footstep ane: Access our
plotting
virtual environment viaworkon plotting
. - Footstep ii: Use pip to uninstall
matplotlib
(since we installed information technology via pip earlier in this article). - Step three: Pull downwards matplotlib from the GitHub repo.
- Footstep 4: Install
matplotlib
from source usingsetup.py
.
I can accomplish these steps using the following commands:
$ workon plotting $ pip uninstall matplotlib $ git clone https://github.com/matplotlib/matplotlib.git $ cd matplotlib $ python setup.py install
Again, you'll want to ensure that you have installed TkInter via apt-get
before performing these steps.
Later matplotlib
has been installed via source, permit's execute the get_backend()
office again:
$ python Python 3.4.0 (default, April 11 2014, xiii:05:11) [GCC 4.8.2] on linux Blazon "aid", "copyright", "credits" or "license" for more information. >>> import matplotlib >>> matplotlib.get_backend() 'TkAgg'
Certain enough, we at present run across the TkAgg
is existence used as the matplotlib
backend.
Notation: You tin can explicitly instruct matplotlib
to use the TkAgg
backend by making a call to matplotlib.use("TkAgg")
; however, this won't practice you much expert if the TkInter dependencies are not installed.
And now when we execute our grayscale_histogram.py
script, but like above:
$ python grayscale_histogram.py
Nosotros should now see both our grayscale image along with our histogram:
We have now fixed our issue — matplotlib figures are successfully being displayed on our screen!
Granted, this solution is a bit of a pain in the ass, simply it's fairly straightforward and gets the task done. If you accept any other suggestions or comments, please feel free to leave them in the comments department.
What about the Raspberry Pi?
The Raspbian operating arrangement, which many Raspberry Pi's run, is Debian based just similar Ubuntu. If you are having the same problems with matplotlib figures not displaying on your Raspberry Pi, the fix detailed in this blog post will resolve your plotting woes.
Can't you merely install matplotlib via apt-get?
The acute Debian user may be wondering why I didn't simply install matplotlib
via apt-get
, like this:
$ sudo apt-become install python-matplotlib
The reason is because I'yard a heavy user of Python virtual environments and strictly believe in keeping my Python environments sequestered and independent of each other. If you lot utilise apt-get
to install matplotlib
yous lose control over what version of matplotlib
you lot want to install — yous simply have to use with whatever version is in the apt-get
repository. This also muddles your system install of Python which I effort to keep as make clean as possible.
All that said, every fourth dimension I take installed matplotlib
via apt-get
all of my dependencies were correctly installed and I was able to display my figures without a trouble, and then if you do non care about Python virtual environments, then the apt-get
solution is a good mode to get. Simply again, I really recommend using virtual environments.
What's adjacent? I recommend PyImageSearch University.
Course information:
35+ total classes • 39h 44m video • Terminal updated: April 2022
★★★★★ 4.84 (128 Ratings) • 13,800+ Students Enrolled
I strongly believe that if you had the right teacher you could principal computer vision and deep learning.
Practice you think learning reckoner 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 estimator science?
That's not the instance.
All you need to primary computer vision and deep learning is for someone to explain things to you lot in simple, intuitive terms. And that'southward exactly what I practice. My mission is to change pedagogy and how complex Artificial Intelligence topics are taught.
If yous're serious near learning calculator vision, your next finish should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV grade online today. Here you'll learn how to successfully and confidently use computer vision to your work, research, and projects. Bring together me in computer vision mastery.
Inside PyImageSearch University y'all'll observe:
- ✓ 35+ courses on essential reckoner vision, deep learning, and OpenCV topics
- ✓ 35+ Certificates of Completion
- ✓ 39+ hours of on-demand video
- ✓ Brand new courses released regularly , ensuring yous can proceed up with country-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 environs configuration required!)
- ✓ Access to centralized code repos for all 450+ tutorials on PyImageSearch
- ✓ Easy one-click downloads for code, datasets, pre-trained models, etc.
- ✓ Access on mobile, laptop, desktop, etc.
Click here to bring together PyImageSearch University
Summary
In this blog post I detailed how to resolve a pesky issue where matplotlib
figures are non displayed to your screen. Symptoms of this problem include clean script execution (i.due east. no error messages and no warnings) printed to your last, and even so your plot is not displayed. I have regularly encountered this problem when using Debian based operating systems such equally Ubuntu and Raspbian. The problem is only farther compounded when using Python virtual environments.
Resolving this matplotlib
event involves manually installing dependencies via apt-get
and adjusting the matplotlib backend to employ TkAgg
, followed past compiling and installing matplotlib
from source. Afterwards, the outcome seems to exist resolved.
While this post wasn't related to computer vision, the matplotlib
library is heavily used in the scientific Python community, so not having your matplotlib
figures displayed can be extremely frustrating and annoying. I promise this mail service helps other readers who encounter a like problem.
I'll be back next week with more computer vision posts!
Join the PyImageSearch Newsletter and Take hold of My FREE 17-folio Resource Guide PDF
Enter your e-mail address below to join the PyImageSearch Newsletter and download my FREE 17-folio Resources Guide PDF on Estimator Vision, OpenCV, and Deep Learning.
Source: https://pyimagesearch.com/2015/08/24/resolved-matplotlib-figures-not-showing-up-or-displaying/
0 Response to "Matplotlib How to Show Figure2 Again"
Post a Comment