1

I am pulling PNG images from Jupyter Notebooks and manage to display with IPython.display.Image but not with matplotib.pyplot.plt. What am I missing? I use python 2.7.

I am using the following algorithm:

To open the notebook JSON content I do:

import nbformat
notebook_ = nbformat.read(file_notebook, 4)

After retrieving the relevant cell information I pull the png information from it using:

def cell_to_image(cell, out_value_item_number=1):
    if "execution_count" in cell.keys(): # i.e version >=4
        return cell["outputs"][out_value_item_number]['data']['image/png']
    elif "prompt_number" in cell.keys(): # i.e version < 4
        return cell["outputs"][out_value_item_number]['png']
    return None

cell_image = cell_to_image(cell)

The first few characters of cell_image (which is unicode) looks like:

iVBORw0KGgoAAAANSUhEUgAAA64AAAFMCAYAAADLFeHSAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\n
AAALEgAACxIB0t1+/AAAIABJREFUeJzs3Xd8jef/x/HXyTjZiYQkCGrU3ruR0tr9oq2qGtGo0dbe
\nm5pVlJpFUSMoVb6UoEZ/lCpatWuPUiNEEiMDmef3R75OexonJKUO3s/HI4/mXPd1X/d1f+LRR965
\n7/u6DSaTyYSIiIiIiIiIjbJ70hMQERERERERyYiCq4iIiIiIiNg0BVcRERERERGxaQquIiIiIiIi
\nYtMUXEVERERERMSmKbiKiIiIiIiITVNwFRGRxyIkJIRixYqxfv36+24/e/YsxYoVo3jx4v/yzGxb
\naGgoderUIS4uDoBdu3bRsmVLKlasyCuvvMKgQYOIjo622CcsLIyGDRtSunRp6tSpw8KFC62OW7p0
\naRo2bJju53Lnzh1GjRrFyy+/TNmyZWnRogW//fbbQ835q6++olGjRpQvX5769eszc+ZMkpOTzdtT
\nU1OZNGkSNWrUoHTp0jRp0oTdu3enGyc2NpZOn

I can easily plot in my Jupityer notebook using

from IPython.display import Image   
Image(cell_image)

And now to my question:

How can I manipulate cell_image to be plt.subplot friendly? (Assuming import matplotlib.pyplot as plt). I realise that plt.imshow wouldn't work because this would require an array, which is not my case (which is a string, as far as I understand).

1 Answer 1

2

If you have your image string representation in a variable string_rep, the following code should work.

from io import BytesIO

import matplotlib.image as mpimage
import matplotlib.pyplot as plt

with BytesIO(string_rep.decode('base64')) as byte_rep:
    image = mpimage.imread(byte_rep)

plt.imshow(image)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.