From c4fe04845df857c0450079aec42989024bba3316 Mon Sep 17 00:00:00 2001 From: Yogeshwaran Date: Fri, 8 Aug 2025 14:09:08 +0530 Subject: [PATCH] Fix imshow to support array alpha values and add corresponding test --- lib/matplotlib/image.py | 11 +++++++++-- .../tests/test_axes/test_imshow_alpha_array.py | 11 +++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 lib/matplotlib/tests/test_axes/test_imshow_alpha_array.py diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index c1846f92608c..3894013ff665 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -903,6 +903,10 @@ def __init__(self, ax, **kwargs ) + #support array value in imshow + if isinstance(self._alpha, np.ndarray): + self._set_alpha_for_array(self._alpha) + def get_window_extent(self, renderer=None): x0, x1, y0, y1 = self._extent bbox = Bbox.from_extents([x0, y0, x1, y1]) @@ -1579,8 +1583,10 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, .. note:: - If you want to save a single channel image as gray scale please use an - image I/O library (such as pillow, tifffile, or imageio) directly. + If *arr* is a single-channel (MxN) image and you want to save it as a grayscale image + (instead of applying a colormap), consider using a dedicated image I/O library like + Pillow, imageio, or tifffile. `imsave` will apply a colormap by default. + Parameters ---------- @@ -1658,6 +1664,7 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, else: sm = mcolorizer.Colorizer(cmap=cmap) sm.set_clim(vmin, vmax) + rgba = sm.to_rgba(arr, bytes=True) if pil_kwargs is None: pil_kwargs = {} diff --git a/lib/matplotlib/tests/test_axes/test_imshow_alpha_array.py b/lib/matplotlib/tests/test_axes/test_imshow_alpha_array.py new file mode 100644 index 000000000000..af2ce22f7ba2 --- /dev/null +++ b/lib/matplotlib/tests/test_axes/test_imshow_alpha_array.py @@ -0,0 +1,11 @@ +import matplotlib.pyplot as plt +import numpy as np + +def test_imshow_alpha_array(): + data = np.random.rand(10, 10) + alpha = np.linspace(0, 1, 100).reshape(10, 10) + + fig, ax = plt.subplots() + im = ax.imshow(data, alpha=alpha) + plt.colorbar(im, ax=ax) + return fig