10000 Merge pull request #29931 from guillermodotn/imsave-seq-fix · matplotlib/matplotlib@6d98336 · GitHub
[go: up one dir, main page]

Skip to content

Commit 6d98336

Browse files
authored
Merge pull request #29931 from guillermodotn/imsave-seq-fix
Allow Python native sequences in Matplotlib `imsave()`.
2 parents f017a0e + fb0c9ac commit 6d98336

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

lib/matplotlib/image.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1544,7 +1544,8 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
15441544
extension of *fname*, if any, and from :rc:`savefig.format` otherwise.
15451545
If *format* is set, it determines the output format.
15461546
arr : array-like
1547-
The image data. The shape can be one of
1547+
The image data. Accepts NumPy arrays or sequences
1548+
(e.g., lists or tuples). The shape can be one of
15481549
MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA).
15491550
vmin, vmax : float, optional
15501551
*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,
15751576
default 'Software' key.
15761577
"""
15771578
from matplotlib.figure import Figure
1579+
1580+
# Normalizing input (e.g., list or tuples) to NumPy array if needed
1581+
arr = np.asanyarray(arr)
1582+
15781583
if isinstance(fname, os.PathLike):
15791584
fname = os.fspath(fname)
15801585
if format is None:

lib/matplotlib/tests/test_image.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,27 @@ def test_imsave(fmt):
184184
assert_array_equal(arr_dpi1, arr_dpi100)
185185

186186

187+
def test_imsave_python_sequences():
188+
# Tests saving an image with data passed using Python sequence types
189+
# such as lists or tuples.
190+
191+
# RGB image: 3 rows × 2 columns, with float values in [0.0, 1.0]
192+
img_data = [
193+
[(1.0, 0.0, 0.0), (0.0, 1.0, 0.0)],
194+
[(0.0, 0.0, 1.0), (1.0, 1.0, 0.0)],
195+
[(0.0, 1.0, 1.0), (1.0, 0.0, 1.0)],
196+
]
197+
198+
buff = io.BytesIO()
199+
plt.imsave(buff, img_data, format="png")
200+
buff.seek(0)
201+
read_img = plt.imread(buff)
202+
203+
assert_array_equal(
204+
np.array(img_data),
205+
read_img[:, :, :3] # Drop alpha if present
206+
)
207+
187208
@pytest.mark.parametrize("origin", ["upper", "lower"])
188209
def test_imsave_rgba_origin(origin):
189210
# test that imsave always passes c-contiguous arrays down to pillow

0 commit comments

Comments
 (0)
0