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

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


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


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()))