jupyter notebook won't show images - python

#%%
from Utils.ConfigProvider import ConfigProvider
import os
import cv2
import numpy as np
from matplotlib import pyplot as plt
config = ConfigProvider.config()
and
#%%
inspected = cv2.imread(config.data.inspected_image_path, 0)
reference = cv2.imread(config.data.reference_image_path, 0)
diff = np.abs(inspected - reference)
plt.figure()
plt.title('inspected')
plt.imshow(inspected)
plt.show()
note config.data.inspected_image_path and config.data.reference_image_path are valid paths.
No errors appear, but no images are shown as well.
Running the same code from a python file does show the image.
I have something missing from the notebook.
This happens both when running using jupyter notebook and directly from PyCharm (pro)
How do I get to see images? all other answers I found just tell me to plt.show() but this obviously does not work.
I don't mind a cv2 solution as well.

You need to set a matplotlib backend.
You can do this with
%matplotlib inline
If you want to be able to interact with the plot, use
%matplotlib notebook

Related

Processing Only One Image Uses All of Ram

I am running this code in google colab (I also tried at my local). I use only one image and it uses all of the ram. Do I do something wrong? Is it normal to use 16 gb ram? I added %matplotlib inline and it still crashes?
import cv2
import matplotlib.pyplot as plt
import numpy as np
f = cv2.imread('/content/gdrive/MyDrive/grass.png')
f = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY).astype(float)
plt.imshow(f)
plt.colorbar()
def gauss1(sigma, width):
hwidth = round((width-1)/2)
x = np.arange(-hwidth, hwidth+1,1)
g = np.exp(-x**2/(2*sigma**2))
return g/np.sum(g)
g1=gauss1(2,11)
g1=np.reshape(g1,(1,-1))
plt.imshow(g1)
f1 = cv2.filter2D(f,-1,g1)
fig = plt.figure(figsize=(10, 20))
fig.add_subplot(1,2,1)
plt.imshow(f)
fig.add_subplot(1,2,2)
plt.imshow(f1)
It does not even produce last code snippet's output.
Use:
If you're using terminal/console, use plt.show() to show the matplotlib output.
Use %matplotlib inline if you are using any ipython notebook kernel such as jupyter notebooks, google colab or kaggle notebooks.

Jupyter NoteBook: draw a graph on the Notebook instead of save the file to the disk

I have the following code:
Is it possible to print the graph just inside the Notebook instead of saving as a file? Thanks!
If you are looking to plot the plots inline inside your jupiter-notebook:
import matplotlib.pyplot as plt
%matplotlib inline
Yes, use matplotlib:
import matplotlib.pyplot as plt
nx.draw(G)
plt.show()
source
Use draw in the following manner :
draw(G, show='ipynb')
If you want all graphs to be drawn inline, then you can set a global parameter.
from nxpd import nxpdParams
nxpdParams['show'] = 'ipynb'
draw(G)
But im not sure this will work with Jupyter, this will work for ipython though.

Ipython notebook (jupyter),opencv (cv2) and plotting?

Is there a way to use and plot with opencv2 with ipython notebook?
I am fairly new to python image analysis. I decided to go with the notebook work flow to make nice record as I process and it has been working out quite well using matplotlib/pylab to plot things.
An initial hurdle I had was how to plot things within the notebook. Easy, just use magic:
%matplotlib inline
Later, I wanted to perform manipulations with interactive plots but plotting in a dedicated window would always freeze. Fine, I learnt again that you need to use magic. Instead of just importing the modules:
%pylab
Now I have moved onto working with opencv. I am now back to the same problem, where I either want to plot inline or use dedicated, interactive windows depending on the task at hand. Is there similar magic to use? Is there another way to get things working? Or am I stuck and need to just go back to running a program from IDLE?
As a side note: I know that opencv has installed correctly. Firstly, because I got no errors either installing or importing the cv2 module. Secondly, because I can read in images with cv2 and then plot them with something else.
This is my empty template:
import cv2
import matplotlib.pyplot as plt
import numpy as np
import sys
%matplotlib inline
im = cv2.imread('IMG_FILENAME',0)
h,w = im.shape[:2]
print(im.shape)
plt.imshow(im,cmap='gray')
plt.show()
See online sample
For a Jupyter notebook running on Python 3.5 I had to modify this to:
import io
import cv2
import numpy as np
from IPython.display import clear_output, Image, display
import PIL.Image
def showarray(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
f = io.BytesIO()
PIL.Image.fromarray(a).save(f, fmt)
display(Image(data=f.getvalue()))
There is also that little function that was used into the Google Deepdream Notebook:
import cv2
import numpy as np
from IPython.display import clear_output, Image, display
from cStringIO import StringIO
import PIL.Image
def showarray(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
display(Image(data=f.getvalue()))
Then you can do :
img = cv2.imread("an_image.jpg")
And simply :
showarray(img)
Each time you need to render the image in a cell

Is there any way to ask Basemap not show the plot?

I am trying to use mpl_toolkits.basemap on python and everytime I use a function for plotting like drawcoastlines() or any other, the program automatically shows the plot on the screen.
My problem is that I am trying to use those programs later on an external server and it returns 'SystemExit: Unable to access the X Display, is $DISPLAY set properly?'
Is there any way I can avoid the plot to be shown when I use a Basemap function on it?
I just want to save it to a file so later I can read it externally.
My code is:
from mpl_toolkits.basemap import Basemap
import numpy as np
m = Basemap(projection='robin',lon_0=0)
m.drawcoastlines()
#m.fillcontinents(color='coral',lake_color='aqua')
# draw parallels and meridians.
m.drawparallels(np.arange(-90.,120.,10.))
m.drawmeridians(np.arange(0.,360.,60.))
Use the Agg backend, it doesn't require a graphical environment:
Do this at the very beginning of your script:
import matplotlib as mpl
mpl.use('Agg')
See also the FAQ on Generate images without having a window appear.
The easiest way is to put off the interactive mode of matplotlib.
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
#NOT SHOW
plt.ioff()
m = Basemap(projection='robin',lon_0=0)
m.drawcoastlines()
#m.fillcontinents(color='coral',lake_color='aqua')
# draw parallels and meridians.
m.drawparallels(np.arange(-90.,120.,10.))
m.drawmeridians(np.arange(0.,360.,60.))

Automatic detection of display availability with matplotlib

I'm generating matplotlib figures in a script which I run alternatively with or without a graphical display. I'd like the script to adjust automatically: with display, it should show the figures interactively, while without a display, it should just save them into a file.
From an answer to the question Generating matplotlib graphs without a running X server, I learnt that one can use the Agg backend for non-interactive plotting.
So I am trying with this code:
import matplotlib
try:
import matplotlib.pyplot as plt
fig = plt.figure()
havedisplay = True
except:
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig = plt.figure()
havedisplay = False
# do the plotting
if havedisplay:
plt.show()
else:
fig.savefig("myfig.png")
This works as excepted in the case with a display. However, without a display, the call to matplotlib.use is not effective, since the display has already been chosen. It's clear that I should call matplotlib.use before import matplotlib.pyplot, but then I don't know how to test whether a display is available or not.
I have also tried with the experimental function matplotlib.switch_backend instead of matplotlib.use, but this generates a RuntimeError.
Does someone have an idea how to make the above code work as intended, or can suggest an alternative way to detect whether a display is available for matplotlib or not?
You can detect directly if you have a display with the OS module in python.
in my case it's
>>> import os
>>> os.environ["DISPLAY"]
':0.0'
The code below works for me in Linux and Windows (where it assumes there is a display device):
import os
import matplotlib
if os.name == 'posix' and "DISPLAY" not in os.environ:
matplotlib.use('Agg')
See https://stackoverflow.com/a/1325587/896111.
Note that the line matplotlib.use('Agg') must appear after the first import of matplotlib (otherwise you will get an error).
try this?
import matplotlib,os
r = os.system('python -c "import matplotlib.pyplot as plt;plt.figure()"')
if r != 0:
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig = plt.figure()
fig.savefig('myfig.png')
else:
import matplotlib.pyplot as plt
fig = plt.figure()
plt.show()
By combining both of the approaches above, you'll get perhaps the best solution:
havedisplay = "DISPLAY" in os.environ
if not havedisplay:
exitval = os.system('python -c "import matplotlib.pyplot as plt; plt.figure()"')
havedisplay = (exitval == 0)
The reason for this combo is that the run time of the os.system command may take a while. So when you are sure you have the display (judging by the os.environ value), you can save that time.
On the other hand, even if the DISPLAY key is not set in the os.environ variable, there is still a chance that the plotting methods will work with the graphical interface (e.g. when using Windows command line).
when use GUI backend the figure object has show() method, you can use it to do the switch:
import matplotlib
#matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig = plt.figure()
havedisplay = False
if hasattr(fig, "show"):
plt.show()
else:
print "save fig"
fig.savefig("myfig.png")
The solution offered by #Oz123 generated a syntax error for me. However, i was able to easily detect the display using:
import os
havedisplay = "DISPLAY" in os.environ
#plotting...
That was the simplest thing i could find, anyway.
import os
have_display = bool(os.environ.get('DISPLAY', None))
have_display is False if DISPLAY is not in the environment or is an empty string. otherwise, it's True

Categories

Resources