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.

fix: add vmin vmax to mo.image and do not norm uint8 values (#8889)

Dylan Madisetti5a82edd559fe
diff --git a/marimo/_plugins/stateless/image.py b/marimo/_plugins/stateless/image.py
index 72fb87c054..84fa59755f 100644
--- a/marimo/_plugins/stateless/image.py
+++ b/marimo/_plugins/stateless/image.py
@@ -21,7 +21,11 @@ Tensor = Any
ImageLike = Union[Image, Tensor]
-def _normalize_image(src: ImageLike) -> Image:
+def _normalize_image(
+ src: ImageLike,
+ vmin: Optional[float] = None,
+ vmax: Optional[float] = None,
+) -> Image:
"""Normalize an image-like object to a standard format.
This function handles a variety of input types, including lists, arrays,
@@ -39,6 +43,10 @@ def _normalize_image(src: ImageLike) -> Image:
Args:
src: An image-like object. This can be a list, array, tensor, or a
file-like object.
+ vmin: Minimum value for normalization. If provided along with `vmax`,
+ values are clipped to [vmin, vmax] and scaled to [0, 255].
+ Only applies to array inputs.
+ vmax: Maximum value for normalization. See `vmin`.
Returns:
A BytesIO object or other Image type.
@@ -68,7 +76,36 @@ def _normalize_image(src: ImageLike) -> Image:
if hasattr(src, "toarray"):
src = src.toarray()
src = numpy.array(src)
- src = (src - src.min()) / (src.max() - src.min()) * 255.0
+
+ # uint8 (typestr '|u1') is already in [0, 255]; use directly
+ # see https://numpy.org/doc/stable/reference/arrays.interface.html
+ is_uint8 = src.__array_interface__["typestr"] == "|u1"
+ has_bounds = vmin is not None or vmax is not None
+
+ if not is_uint8 or has_bounds:
+ lo = float(vmin) if vmin is not None else float(src.min())
+ hi = float(vmax) if vmax is not None else float(src.max())
+ if has_bounds:
+ if lo > hi:
+ raise ValueError(
+ f"vmin ({vmin}) must be less than or equal to "
+ f"vmax ({vmax})."
+ )
+ # torch/jax/tf tensors lack __array_interface__ and are
+ # converted to numpy above, so src is always an ndarray here.
+ if not hasattr(src, "clip"):
+ raise ValueError(
+ f"Array of type {type(src)} does not support "
+ "clipping. Convert to a numpy array before passing "
+ "to `mo.image`."
+ )
+ src = src.clip(lo, hi)
+ denom = hi - lo
+ if denom == 0:
+ src = src - src # zeros, preserving shape
+ else:
+ src = (src - lo) / denom * 255.0
+
img = _Image.fromarray(src.astype("uint8"))
# io.BytesIO is one of the Image types.
normalized_src: Image = io.BytesIO()
@@ -102,6 +139,8 @@ def image(
rounded: bool = False,
style: Optional[dict[str, Any]] = None,
caption: Optional[str] = None,
+ vmin: Optional[float] = None,
+ vmax: Optional[float] = None,
) -> Html:
"""Render an image as HTML.
@@ -123,22 +162,44 @@ def image(
)
```
+ ```python3
+ # Compare images with consistent intensity scaling
+ import numpy as np
+
+ dark = np.full((100, 100), 50)
+ light = np.full((100, 100), 200)
+ mo.hstack(
+ [
+ mo.image(dark, vmin=0, vmax=255),
+ mo.image(light, vmin=0, vmax=255),
+ ]
+ )
+ ```
+
Args:
- src: a path or URL to an image, a file-like object
- (opened in binary mode), or array-like object.
+ src: a path or URL to an image, a file-like object (opened in binary
+ mode), or array-like object. When `src` is array-like, `uint8`
+ arrays are used as-is. Other dtypes are min-max normalized unless
+ `vmin`/`vmax` are provided.
alt: the alt text of the image
width: the width of the image in pixels or a string with units
height: the height of the image in pixels or a string with units
rounded: whether to round the corners of the image
style: a dictionary of CSS styles to apply to the image
caption: the caption of the image
+ vmin: minimum value for normalization when `src` is an array. Values
+ below `vmin` are clipped. If `None`, defaults to the array
+ minimum. Only used when `src` is array-like.
+ vmax: maximum value for normalization when `src` is an array. Values
+ above `vmax` are clipped. If `None`, defaults to the array
+ maximum. Only used when `src` is array-like.
Returns:
`Html` object
"""
# Convert to virtual file
resolved_src: Optional[str]
- src = _normalize_image(src)
+ src = _normalize_image(src, vmin=vmin, vmax=vmax)
# TODO: Consider downsampling here. This is something matplotlib does
# implicitly, and can potentially remove the bottle-neck of very large
# images.
diff --git a/tests/_plugins/stateless/test_image.py b/tests/_plugins/stateless/test_image.py
index 21df20b5a5..44199b5351 100644
--- a/tests/_plugins/stateless/test_image.py
+++ b/tests/_plugins/stateless/test_image.py
@@ -209,3 +209,96 @@ def test_image_constructor_pil():
Image.new("RGB", (100, 100), color="red"),
)
assert result.text.startswith("<img src='data:image/png;base64,")
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_image_uint8_no_normalization():
+ import numpy as np
+ from PIL import Image as PILImage
+
+ # uint8 uniform array should not produce division-by-zero or map to 0
+ arr = np.full((10, 10), 50, dtype=np.uint8)
+ result = image(arr)
+ assert result.text.startswith("<img src='data:image/png;base64,")
+ # Decode and verify pixel values are preserved
+ import base64
+ import io as _io
+
+ data_url = result.text.split("src='")[1].split("'")[0]
+ b64 = data_url.split(",")[1]
+ img = PILImage.open(_io.BytesIO(base64.b64decode(b64)))
+ pixels = np.array(img)
+ assert pixels.min() == 50
+ assert pixels.max() == 50
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_image_uint8_preserves_relative_intensity():
+ import base64
+ import io as _io
+
+ import numpy as np
+ from PIL import Image as PILImage
+
+ def _decode_pixels(result):
+ data_url = result.text.split("src='")[1].split("'")[0]
+ b64 = data_url.split(",")[1]
+ img = PILImage.open(_io.BytesIO(base64.b64decode(b64)))
+ return np.array(img)
+
+ dark = np.full((10, 10), 50, dtype=np.uint8)
+ light = np.full((10, 10), 200, dtype=np.uint8)
+ dark_pixels = _decode_pixels(image(dark))
+ light_pixels = _decode_pixels(image(light))
+ # Dark image should have lower pixel values than light image
+ assert dark_pixels.mean() < light_pixels.mean()
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_image_uniform_float_no_division_by_zero():
+ import numpy as np
+
+ # Uniform float array should not raise a warning or error
+ arr = np.full((10, 10), 0.5, dtype=np.float32)
+ result = image(arr)
+ assert result.text.startswith("<img src='data:image/png;base64,")
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_image_vmin_vmax():
+ import base64
+ import io as _io
+
+ import numpy as np
+ from PIL import Image as PILImage
+
+ # Float array with known range; vmin/vmax should scale correctly
+ arr = np.full((10, 10), 500.0, dtype=np.float32)
+ result = image(arr, vmin=0, vmax=1000)
+ data_url = result.text.split("src='")[1].split("'")[0]
+ b64 = data_url.split(",")[1]
+ img = PILImage.open(_io.BytesIO(base64.b64decode(b64)))
+ pixels = np.array(img)
+ # 500 / 1000 * 255 = 127 (±1 for rounding)
+ assert abs(int(pixels.mean()) - 127) <= 1
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_image_vmin_vmax_clamps():
+ import base64
+ import io as _io
+
+ import numpy as np
+ from PIL import Image as PILImage
+
+ # Values outside [vmin, vmax] should be clipped
+ # Row of pixels: 0, 128, 255 (grayscale 2D)
+ arr = np.array([[0, 128, 255]], dtype=np.uint8)
+ result = image(arr, vmin=100, vmax=200)
+ data_url = result.text.split("src='")[1].split("'")[0]
+ b64 = data_url.split(",")[1]
+ img = PILImage.open(_io.BytesIO(base64.b64decode(b64)))
+ pixels = np.array(img).flatten()
+ # 0 clipped to 100 → 0; 128 → (128-100)/100*255 ≈ 71; 255 clipped to 200 → 255
+ assert pixels[0] == 0
+ assert pixels[2] == 255