Good morning SO,
Setup :
Windows 7 (I know)
Sublime Text 3
Python 3.6
My problem :
I have some 28x28 images in a file, say one of them is at the relative path 'MyDir/myimage.png'
I'm trying to display the example image using the display module in the package IPython
from IPython.display import display,Image
img=Image(filename='MyDir/myimage.png')
display(img)
The problem is that instead of outputing the image in a figure, it only outputs the type of the object img in the console (display displays only in console).
Output :
<IPython.core.display.Image object>
Any ideas?
IPython (interactive python) won't work as expected in the console.
But in jupyter notebook, for instance, all goes well:
There's also qtconsole which sounds like it's just a more console-like jupyter notebook. I haven't checked it out, since between vscode and jupyter notebook, I've been fine thus far.
To learn more, you could search for comparisons between tools like jupyter and qt. And also take a look at the IPython docs. But if you just want the darn thing to show you an image, you could run your python script in jupyter or the like. Or use PIL as this answer to another question mentions.
Also, you could use matplotlib.pyplot to show images instead (this works in console and in jupyter):
from matplotlib.pyplot import figure, imshow, axis, show
from matplotlib.image import imread
import numpy as np
import os
imageDirectory = "c:\\some\\directory\\of\\images"
list_of_files = np.array(os.listdir(imageDirectory))[0:20] # just show the first 20 images
fig = figure()
number_of_files = len(list_of_files)
for i in range(number_of_files):
a=fig.add_subplot(1,number_of_files,i+1)
image = imread(os.path.join(imageDirectory, list_of_files[i]))
imshow(image,cmap='Greys_r')
axis('off')
show()
Related
#%%
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
I have a cell that looks like this:
from IPython.display import Image
i = Image(filename='test.png')
i
print("test")
The output is just:
test
I don't see the image in the output. I checked to see that the file exists (anyway, if it did not exist, you get an error).
Any clues?
creating the image with
i = Image(filename='test.png')
only creates the object to display. Objects are displayed by one of two actions:
a direct call to IPython.display.display(obj), e.g.
from IPython.display import display
display(i)
the displayhook, which automatically displays the result of the cell, which is to say putting i on the last line of the cell. The lone i in your example doesn't display because it is not the last thing in the cell. So while this doesn't display the image:
i = Image(filename='test.png')
i
print("test")
This would:
i = Image(filename='test.png')
print("test")
i
I had the same problem.
Matplot lib expects to show figs outside the command line, for example in the GTK or QT.
Use this: get_ipython().magic(u'matplotlib inline')
It will enable inline backend for usage with IPython notebook.
See more here and here.
After looking into the code, I can say, that under Windows, as of IPython 7.1.0, this is only supported with %matplotlib inline, which does not work under the interactive IPython shell.
There is extra code in Jupyter. The following example works with
jupyter qtconsole
jupyter notebook
jupyter console in principle, but only via external program, and then for the example the temporary file got deleted
def test_display():
import pyx
c = pyx.canvas.canvas()
circle = pyx.path.circle(0, 0, 2)
c.stroke(circle, [pyx.style.linewidth.Thick,pyx.color.rgb.red])
return c
display(test_display())
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
In the past I was able to do simple animations with matplotlib with a for loop, but this hasn't worked for some time now.
The standard answer is that you have to turn interactive mode on and/or force a redraw with matplotlib.pyplot.draw(). Here is my minimal working example:
import numpy as np
import matplotlib
matplotlib.use('Qt4Agg')
import matplotlib.pyplot as mplot
mplot.ion()
fig = mplot.figure(1)
ax = fig.add_subplot(111)
for ii in np.arange(0,10):
x = 200*np.random.rand(30)
ax.plot(x)
mplot.draw()
filename = ("img_%d.png" % ii)
mplot.savefig(filename)
When I run this in Interactive Python Editor, I get one figure at the very end with all the plots in it (this also happens with mplot.show())
When I run this in IPython 3.1 (with Python 3.3.5) from the command line, I get nothing at all.
The mplot.savefig(filename) line does seem to work, as the images are generated.
(It's possible this is a bug in the Qt4 backend.)
Try deleting the line matplotlib.use('Qt4Agg'). Works for me. Also works with matplotlib.use('TkAgg'). So it is a backend problem. There is another way to do animations.
Has anyone encountered this problem using spyder in debug mode (PDB)? It works fine in the interactive mode.
One suggested solution was to use pause(1) instead of show() after imshow(img).
Is there a better way to see my figures in debug mode? If there was, it would be a real Matlab killer!
To answer my own question. Apparently this is bug and the pause(1) is the only way to see plot figures in PDB mode.
The other method is to run the entire program as a script by cutting and pasting it into the command line. This way show() can be used instead of pause(1). The advantage to doing it this way, is one can zoom in on the plot. When using pause(1) this is only possible during the pause.
For example:
import numpy as np
from matplotlib import pyplot as plt
import cv2
file_name = 'myimage.jpg'
img = cv2.imread(file_name)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,150,100,apertureSize = 3)
#display image
plt.figure(1)
plt.imshow(edges)
plt.title('edges of image')
plt.show()
Edit:
I just discovered a nice alternative plotting tool in python called guiqwt.
It works with pdb unlike matplotlib
import numpy as np
from guiqwt.pyplot import *
figure("simple plot")
subplot(1, 2, 1)
plot(x, np.tanh(x+np.sin(12*x)), "g-", label="Tanh")
legend()
subplot(1, 2, 2)
plot(x, np.sinh(x), "r:", label="SinH")
show()
You can get it as part of the included packages in python(x,y) or you can download it from here
Edit2:
I just found out the latest IDE released by Pycharm supports matplotlib much better. You can use plt.imshow(img) and don't even have to use plt.show() to display the image in debug mode