Black Lives Matter. Please consider donating to Black Girls Code today.

Imshow in Python

How to display image data in Python with Plotly.


If you're using Dash Enterprise's Data Science Workspaces, you can copy/paste any of these cells into a Workspace Jupyter notebook.
Alternatively, download this entire tutorial as a Jupyter notebook and import it into your Workspace.
Find out if your company is using Dash Enterprise.


New to Plotly?

Plotly is a free and open-source graphing library for Python. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

This tutorial shows how to display and explore image data. If you would like instead a logo or static image, use go.layout.Image as explained here.

Displaying RBG image data with px.imshow

px.imshow displays multichannel (RGB) or single-channel ("grayscale") image data.

In [1]:
import plotly.express as px
import numpy as np
img_rgb = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]],
                    [[0, 255, 0], [0, 0, 255], [255, 0, 0]]
                   ], dtype=np.uint8)
fig = px.imshow(img_rgb)
fig.show()

Read image arrays from image files

In order to create a numerical array to be passed to px.imshow, you can use a third-party library like PIL, scikit-image or opencv. We show below how to open an image from a file with skimage.io.imread, and alternatively how to load a demo image from skimage.data.

In [2]:
import plotly.express as px
from skimage import io
img = io.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Crab_Nebula.jpg/240px-Crab_Nebula.jpg')
fig = px.imshow(img)
fig.show()
In [3]:
import plotly.express as px
from skimage import data
img = data.astronaut()
fig = px.imshow(img, binary_format="jpeg", binary_compression_level=0)
fig.show("notebook")