Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

mo.image(): visualize NumPy array, torch.tensor, scipy.sparse matrix (#964)

Dylan Madisetti9b4a66d7f818
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index 29e68d9774..76d2bdfe2d 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -67,6 +67,21 @@ class DependencyManager:
+ "You can install it with 'pip install altair'"
) from None
+ @staticmethod
+ def require_pillow(why: str) -> None:
+ """
+ Raise an ModuleNotFoundError if pillow is not installed.
+
+ Args:
+ why: A string of the form "for <reason>" that will be appended
+
+ """
+ if not DependencyManager.has_pillow():
+ raise ModuleNotFoundError(
+ f"pillow is required {why}. "
+ + "You can install it with 'pip install pillow'"
+ ) from None
+
@staticmethod
def require_plotly(why: str) -> None:
"""
@@ -107,6 +122,11 @@ class DependencyManager:
"""Return True if altair is installed."""
return importlib.util.find_spec("altair") is not None
+ @staticmethod
+ def has_pillow() -> bool:
+ """Return True if pillow is installed."""
+ return importlib.util.find_spec("PIL") is not None
+
@staticmethod
def has_plotly() -> bool:
"""Return True if plotly is installed."""
diff --git a/marimo/_plugins/stateless/image.py b/marimo/_plugins/stateless/image.py
index 571578a16d..8d0d3d089b 100644
--- a/marimo/_plugins/stateless/image.py
+++ b/marimo/_plugins/stateless/image.py
@@ -6,16 +6,88 @@ import os
from typing import Any, Optional, Union
import marimo._output.data.data as mo_data
+from marimo._dependencies.dependencies import DependencyManager
from marimo._output.builder import h
from marimo._output.hypertext import Html
from marimo._output.rich_help import mddoc
from marimo._output.utils import create_style
from marimo._plugins.core.media import io_to_data_url
+Image = Union[str, bytes, io.BytesIO, io.BufferedReader]
+# Union[list, torch.Tensor, jax.numpy.ndarray,
+# np.ndarray, scipy.sparse.spmatrix]
+Tensor = Any
+ImageLike = Union[Image, Tensor]
+
+
+def _normalize_image(src: ImageLike) -> Image:
+ """
+ Normalize an image-like object to a standard format.
+
+ This function handles a variety of input types, including lists, arrays,
+ and tensors, and converts them to a BytesIO object representing a PNG
+ image.
+
+ Typical convention for handling images is to use `PIL`, which is exactly
+ what `matplotlib` does behind the scenes. `PIL` requires a `ndarray`
+ (validated with the numpy specific `__array_interface__` attribute). In
+ turn, numpy can cast lists, and objects with the `__array__` method (like
+ jax, torch tensors). `scipy.sparse` breaks this convention but does have a
+ `toarray` method, which is general enough that a specific check is
+ performed here.
+
+ **Args.**
+
+ - `src`: An image-like object. This can be a list, array, tensor, or a
+ file-like object.
+
+ **Returns.**
+
+ A BytesIO object or other Image type.
+
+ **Raises.**
+
+ - `ModuleNotFoundError`: If the required `PIL` or `numpy` packages are not
+ available.
+ - `ValueError`: If the input is not a valid image-like object.
+ """
+ if (
+ isinstance(src, list)
+ or hasattr(src, "__array__")
+ or hasattr(src, "toarray")
+ ):
+ DependencyManager.require_pillow(
+ "to render images from arrays in `mo.image`"
+ )
+ from PIL import Image as _Image
+
+ if not hasattr(src, "__array_interface__"):
+ DependencyManager.require_numpy(
+ "to render images from generic arrays in `mo.image`"
+ )
+ import numpy
+
+ # Capture those sparse cases
+ if hasattr(src, "toarray"):
+ src = src.toarray()
+ src = numpy.array(src)
+ src = (src - src.min()) / (src.max() - src.min()) * 255.0
+ img = _Image.fromarray(src.astype("uint8"))
+ # io.BytesIO is one of the Image types.
+ normalized_src: Image = io.BytesIO()
+ img.save(normalized_src, format="PNG")
+ return normalized_src
+ # Verify that this is a image object
+ if not isinstance(src, (str, bytes, io.BytesIO, io.BufferedReader)):
+ raise ValueError(
+ f"Expected an image object, but got {type(src)} instead."
+ )
+ return src
+
@mddoc
def image(
- src: Union[str, bytes, io.BytesIO, io.BufferedReader],
+ src: ImageLike,
alt: Optional[str] = None,
width: Optional[int] = None,
height: Optional[int] = None,
@@ -44,8 +116,8 @@ def image(
**Args.**
- - `src`: a path or URL to an image, or a file-like object
- (opened in binary mode)
+ - `src`: a path or URL to an image, a file-like object
+ (opened in binary mode), or array-like object.
- `alt`: the alt text of the image
- `width`: the width of the image in pixels
- `height`: the height of the image in pixels
@@ -58,6 +130,10 @@ def image(
"""
# Convert to virtual file
resolved_src: Optional[str]
+ src = _normalize_image(src)
+ # TODO: Consider downsampling here. This is something matplotlib does
+ # implicitly, and can potentially remove the bottle-neck of very large
+ # images.
if isinstance(src, io.BufferedReader) or isinstance(src, io.BytesIO):
src.seek(0)
resolved_src = mo_data.image(src.read()).url
diff --git a/pyproject.toml b/pyproject.toml
index 14672b9d7c..88e142932b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -73,6 +73,9 @@ dev = [
# For testing mo.ui.chart
"pandas>=1.3.0",
"pandas-stubs>=1.3.0",
+ # For testing mo.image
+ "pillow~=10.2.0",
+ "types-Pillow~=10.2.0.20240311",
# polars 0.19.13 requires building maturn from source, but we don't
# have the rust toolchain installed on CI
"polars==0.19.12",
@@ -109,6 +112,8 @@ testoptional = [
"altair>=5.0.0",
"pandas>=1.3.0",
"pandas-stubs>=1.3.0",
+ "pillow~=10.2.0",
+ "types-Pillow~=10.2.0.20240311",
# polars 0.19.13 requires building maturn from source, but we don't
# have the rust toolchain installed on CI
"polars==0.19.12",
diff --git a/scripts/pycheck.sh b/scripts/pycheck.sh
index 3a22906dbd..e50a15afd6 100755
--- a/scripts/pycheck.sh
+++ b/scripts/pycheck.sh
@@ -1,4 +1,4 @@
-#!/bin/bash
+#!/bin/sh
echo "[check: lint]"
ruff marimo/
diff --git a/scripts/pycopyright.sh b/scripts/pycopyright.sh
index a3e3517a72..9e366d28ce 100755
--- a/scripts/pycopyright.sh
+++ b/scripts/pycopyright.sh
@@ -1,4 +1,4 @@
-#!/bin/bash
+#!/usr/bin/env bash
# Directories to scan
dir="marimo"
diff --git a/tests/_plugins/stateless/test_image.py b/tests/_plugins/stateless/test_image.py
index 7e60355223..c185755c57 100644
--- a/tests/_plugins/stateless/test_image.py
+++ b/tests/_plugins/stateless/test_image.py
@@ -3,11 +3,14 @@ import sys
import pytest
+from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.stateless.image import image
from marimo._runtime.context import get_context
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
+HAS_DEPS = DependencyManager.has_numpy() and DependencyManager.has_pillow()
+
async def test_image() -> None:
result = image(
@@ -66,6 +69,43 @@ async def test_image_str(k: Kernel, exec_req: ExecReqProvider) -> None:
assert len(get_context().virtual_file_registry.registry) == 0
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+async def test_image_array(k: Kernel, exec_req: ExecReqProvider) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ data = [[[255, 0, 0], [0, 255, 0], [0, 0, 255]]]
+ image = mo.image(data)
+ """
+ ),
+ ]
+ )
+ assert len(get_context().virtual_file_registry.registry) == 1
+ for fname, _ in get_context().virtual_file_registry.registry.items():
+ assert fname.endswith(".png")
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+async def test_image_numpy(k: Kernel, exec_req: ExecReqProvider) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ import numpy as np
+ data = np.random.rand(10, 10)
+ image = mo.image(data)
+ """
+ ),
+ ]
+ )
+ assert len(get_context().virtual_file_registry.registry) == 1
+ for fname, _ in get_context().virtual_file_registry.registry.items():
+ assert fname.endswith(".png")
+
+
# TODO(akshayka): Debug on Windows
@pytest.mark.skipif(sys.platform == "win32", reason="Failing on Windows CI")
async def test_image_local_file(k: Kernel, exec_req: ExecReqProvider) -> None: