The Image Mark

Image is a Mark object, used to visualize images in standard format (png, jpg etc...), in a bqplot Figure

It takes as input an ipywidgets Image widget

The ipywidgets Image


In [ ]:
import ipywidgets as widgets
import os

image_path = os.path.abspath('../../data_files/trees.jpg')

with open(image_path, 'rb') as f:
    raw_image = f.read()
ipyimage = widgets.Image(value=raw_image, format='jpg')
ipyimage

Displaying the image inside a bqplot Figure


In [ ]:
from bqplot import LinearScale, Figure, Lines, Axis, Image

# Create the scales for the image coordinates
scales={'x': LinearScale(), 'y': LinearScale()}
# Define the bqplot Image mark
image = Image(image=ipyimage, scales=scales)
# Create the bqplot Figure to display the mark
fig = Figure(title='Trees', marks=[image], padding_x=0, padding_y=0)
fig

Mixing with other marks

Image is a mark like any other, so they can be mixed and matched together.


In [ ]:
scales = {'x': LinearScale(min=-1, max=2), 'y': LinearScale(min=-0.5, max=2)}
image = Image(image=ipyimage, scales=scales)
lines = Lines(x=[0, 1, 1, 0, 0], y=[0, 0, 1, 1, 0], scales=scales, colors=['red'])
fig = Figure(marks=[image, lines], padding_x=0, padding_y=0, animation_duration=1000)
fig.axes = [Axis(scale=scales['x']), Axis(scale=scales['y'], orientation='vertical')]
fig

Its traits (attributes) will also respond dynamically to a change from the backend


In [ ]:
# Full screen
image.x = [-1, 2]
image.y = [-.5, 2]

Interactions

Like other bqplot marks, you can watch for mouse clicks. For the image mark, the position of the click (on the x/y scale set up in the figure) is returned.


In [ ]:
def print_event(_, target):
    print(target)
    
image.on_element_click(print_event)

Pyplot

It may seem verbose to first open the image file, create an ipywidgets Image, then create the scales and so forth.

The pyplot api does all of that for you, via the imshow function.


In [ ]:
import bqplot.pyplot as bqp

bqp.figure()
bqp.imshow(image_path, 'filename')
bqp.show()

The signature is

bqp.imshow(image, format)

  • image is the Image data, depending on the passed format, can be one of:
    • an instance of an ipywidgets Image
    • a file name
    • a raw byte string
  • format: {'widget', 'filename', ...} Type of the input argument. If not 'widget' or 'filename', must be a format supported by the ipywidgets Image.