Imshow in Python
How to display image data in Python with Plotly.
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.
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
.
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()
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()
Display single-channel 2D data as a heatmap¶
For a 2D image, px.imshow
uses a colorscale to map scalar data to colors. The default colorscale is the one of the active template (see the tutorial on templates).
import plotly.express as px
import numpy as np
img = np.arange(15**2).reshape((15, 15))
fig = px.imshow(img)
fig.show()
Choose the colorscale to display a single-channel image¶
You can customize the continuous color scale just like with any other Plotly Express function. However, color_continuous_scale
is ignored when using binary_string=True
, since the image is always represented as grayscale (and no colorbar is displayed).
import plotly.express as px
import numpy as np
img = np.arange(100).reshape((10, 10))
fig = px.imshow(img, binary_string=True)
fig.show()
You can use this to make the image grayscale as well:
import plotly.express as px
import numpy as np
img = np.arange(100).reshape((10, 10))
fig = px.imshow(img, color_continuous_scale='gray')
fig.show()
Hiding the colorbar and axis labels¶
See the continuous color and cartesian axes pages for more details.
import plotly.express as px
from skimage import data
img = data.camera()
fig = px.imshow(img, color_continuous_scale='gray')
fig.update_layout(coloraxis_showscale=False)
fig.update_xaxes(showticklabels=False)
fig.update_yaxes(showticklabels=False)
fig.show()