Jupyter notebook ipywidgets interact does not show Pillow images

1k Views Asked by At

I want to use ipywidgets.interact to show Pillow images similar to what someone already did here. However, in my case Jupyter would not render the image. Instead it looks like this:

Screenshot of Jupyter

If I output the image separately into a cell then it displays. Does anyone know how I can fix this?

1

There are 1 best solutions below

7
On

I suspect you didn't have your environment set up quite right with the matching versions. Or maybe not imported everything needed.

If you go here and run that code it will work because the environment served via MyBinder.org specified here has ipywidgets and current versions of everything necessary. (It actually isn't listed there but voila has it as a dependency and so it's installed in the build; you'll see it listed if you run %pip list in a cell in the notebook.)

When that notebook shows up after a few seconds, execute the entire thing by selecting Run > Run All Cells from the toolbar menu. Importantly, You won't see the adjustable image when you first open the notebook, without running it actively there.

After running it, now the slider should work for adjusting.

The code that I used with ipywidgets.interact to show a Pillow image so that it's adjustable:

%matplotlib inline
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets

from PIL import Image
img = Image.open('picture.png').convert('L')

@interact
def binarize(th: (0, 255, 1)):
    return img.point(lambda p: 255 if p > th else 0)

I just tried it and that %matplotlib inline isn't needed at this time, consider it optional.