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
Related
I have been working on trying to get my python program and I need to use matplotlib for image processing.
I've been having a lot of trouble but I followed all the examples that I can find online. I had a hard time getting matplotlib to install.
Image of Errors
Second image of errors
tried:
import matplotlib.pyplot as plt
import matplotlib.image as aImage
img = 'Alabama.jpg'
img_Alabama = plt.imread(img)
plt.imshow(img_Alabama)
&
img_Alabama = plt.imread('StepOne\MatLibPhotos\Alabama.jpg')
plt.imshow(img_Alabama)
#%%
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'm working with this custom Py visual in PowerBI. Unfortunately, Power BI has some Python code leading my code that pre-defines the image size (5.55555555555556,4.16666666666667).
The result is a small image surrounded by a lot of empty space:
Is there any way I can redefine the size of the image, even though I cannot modify the leading code?
Any other suggestions are welcome,
Thanks!
# Prolog - Auto Generated #
import os, uuid, matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot
import pandas
os.chdir(u'C:/Users/USER/PythonEditorWrapper_443a6d71-c4cc-4e62-ac6f-2dad3eeace3d')
dataset = pandas.read_csv('input_df_d2b6d8be-2212-4ece-902c-f85219eff22b.csv')
matplotlib.pyplot.figure(figsize=(5.55555555555556,4.16666666666667), dpi=72)
matplotlib.pyplot.show = lambda args=None,kw=None: matplotlib.pyplot.savefig(str(uuid.uuid1()))
#My code starts here, I cannot modify anything above this line.
#I wish I could add a line here to redefine figsize=(5.55555555555556,4.16666666666667)
from matplotlib import pyplot as plt
plt.figure(figsize=(15,20))
try this
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
i = Image.open('images/dot.png')
iar = np.asarray(i)
plt.imshow(iar)
plt.show()
I have the image called dot.png in the same directory but it is not working.
When I start the program no errors detected. It runs fine. But the matplotlib tool not working.
The window look like this:
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()