No image pop-up or display for plt.imshow() and pl

2019-08-14 14:26发布

问题:

I was trying to recreate the cocoapi demo script by copy pasting it into my own local script instead of running it on a Jupyter notebook. Everything works fine and there's definitely an image read and can be displayed because I've tested it with openCV's imshow() function (and the image pops up). However, when I tried opening the image with plt.imshow() and plt.show(), the image would not appear.

I went online to search for solution at they suggested its a backend issue? However, when I ran matplotlib.get_backend(), it returned: 'TkAgg'.

I also ran: sudo apt-get install tcl-dev tk-dev python-tk python3-tk with no errors nor issues.

from __future__ import print_function
from pycocotools.coco import COCO
import os, sys, zipfile
import urllib.request
import shutil
import numpy as np
import skimage.io as io
import matplotlib.pyplot as plt
import pylab
pylab.rcParams['figure.figsize'] = (8.0, 10.0)
...
# load and display image
I = io.imread('%s/images/%s/%s'%(dataDir,dataType,img['file_name']))
plt.axis('off')
plt.imshow(I)
plt.show()

Versions
* Operating system: Ubuntu 16.04
* Matplotlib version: 2.2.3
* Matplotlib backend (print(matplotlib.get_backend())): TkAgg
* Python version: 3.5.2

回答1:

There's two solutions to this. The first solution is kindly pointed out by @ImportanceOfBeingErnest and it is to switch backends. The solution is stated in this thread

As @ImportanceOfBeingErnest has pointed out, the second solution is less ideal because it involves changing source code. But if for whatever reasons the first method doesn't work, feel free to try the second one.

Second solution: When I ran matplotlib.get_backend(), it returned: 'TkAgg' so I was confused why it still didn't work. Turns out that it returned 'TkAgg' because I did something like that in terminal:

Python 3.5.2 (default, Nov 23 2017, 16:37:01)  
[GCC 5.4.0 20160609] on linux  
Type "help", "copyright", "credits" or "license" for more information.  
import matplotlib  
matplotlib.get_backend()  

But with the line

from pycocotools.coco import COCO

From terminal:

This call to matplotlib.use() has no effect because the backend has already
been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.

In the cocoapi/PythonAPI/pycocotools/coco.py file, the third import line was:

import matplotlib; matplotlib.use('Agg')

Change this to:

import matplotlib; matplotlib.use('TkAgg')

and things should be fine.