diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index 760235b6284d..754347b9d7ca 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -1544,7 +1544,8 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, extension of *fname*, if any, and from :rc:`savefig.format` otherwise. If *format* is set, it determines the output format. arr : array-like - The image data. The shape can be one of + The image data. Accepts NumPy arrays or sequences + (e.g., lists or tuples). The shape can be one of MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA). vmin, vmax : float, optional *vmin* and *vmax* set the color scaling for the image by fixing the @@ -1575,6 +1576,10 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, default 'Software' key. """ from matplotlib.figure import Figure + + # Normalizing input (e.g., list or tuples) to NumPy array if needed + arr = np.asanyarray(arr) + if isinstance(fname, os.PathLike): fname = os.fspath(fname) if format is None: diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index 93124141487f..0570bc28f72f 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -184,6 +184,27 @@ def test_imsave(fmt): assert_array_equal(arr_dpi1, arr_dpi100) +def test_imsave_python_sequences(): + # Tests saving an image with data passed using Python sequence types + # such as lists or tuples. + + # RGB image: 3 rows × 2 columns, with float values in [0.0, 1.0] + img_data = [ + [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0)], + [(0.0, 0.0, 1.0), (1.0, 1.0, 0.0)], + [(0.0, 1.0, 1.0), (1.0, 0.0, 1.0)], + ] + + buff = io.BytesIO() + plt.imsave(buff, img_data, format="png") + buff.seek(0) + read_img = plt.imread(buff) + + assert_array_equal( + np.array(img_data), + read_img[:, :, :3] # Drop alpha if present + ) + @pytest.mark.parametrize("origin", ["upper", "lower"]) def test_imsave_rgba_origin(origin): # test that imsave always passes c-contiguous arrays down to pillow
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: