Miladiouss
Miladiouss

Reputation: 4700

Outputting Images in Jupyter Notebook

The following code is able to print/output images as intended in a Jupyter notebook:

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from IPython import display
from scipy.misc import toimage
import numpy as np

n = 3
for _ in range(n):
    (toimage(np.random.rand(32, 32, 3)))
    print("----------------------------")

However, once I put it inside a function, it stops working. Why? And how can I fix it?

def print_images(n=3):
    for _ in range(n):
        (toimage(np.random.rand(32, 32, 3)))
        print("----------------------------")

print_images()

Upvotes: 1

Views: 416

Answers (1)

tel
tel

Reputation: 13999

display.display_png works:

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from IPython import display
from scipy.misc import toimage
import numpy as np

n = 3
for _ in range(n):
    display.display_png(toimage(np.random.rand(32, 32, 3)))
    print("----------------------------")

def print_images(n=3):
    for _ in range(n):
        display.display_png(toimage(np.random.rand(32, 32, 3)))
        print("----------------------------")

print_images()

You can read up more on why this works and the other way fails in the docs for IPython's display module.

Details

The object returned by toimage has a _repr_png_ method. This is what gets called by the notebook to produce the image that you actually see. For whatever reason (which I'm sure you could uncover by digging into the docs), the notebook will call x._repr_png_() automatically whenever a call to toimage produces any instance x in the top scope of a cell. However, if toimage is run in a more deeply nested scope, _repr_png_ is not automatically called. Instead, you have to manually engage that same display machinery with an explicit call to display.display_png.

Upvotes: 1

Related Questions