From 70358acc9e08364cd574e086499468f5e758bf57 Mon Sep 17 00:00:00 2001 From: Benjamin Root Date: Sun, 9 Sep 2012 15:41:50 -0400 Subject: [PATCH 1/2] Allow imsave() to handle RGB(A) input arrays Thanks to Jostein Be Floystad for the original patch! --- lib/matplotlib/image.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index 4719667f3a9a..22df993bc41a 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -1243,7 +1243,7 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, If *format* is *None* and *fname* is a string, the output format is deduced from the extension of the filename. *arr*: - A 2D array. + An MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA) array. Keyword arguments: *vmin*/*vmax*: [ None | scalar ] *vmin* and *vmax* set the color scaling for the image by fixing the @@ -1266,7 +1266,7 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure - figsize = [x / float(dpi) for x in arr.shape[::-1]] + figsize = [x / float(dpi) for x in (arr.shape[1], arr.shape[0])] fig = Figure(figsize=figsize, dpi=dpi, frameon=False) canvas = FigureCanvas(fig) im = fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin) From 22c4a1913663c227754987914ef02ec760525b53 Mon Sep 17 00:00:00 2001 From: Benjamin Root Date: Sun, 9 Sep 2012 16:31:43 -0400 Subject: [PATCH 2/2] Added a test for imsave --- lib/matplotlib/tests/test_image.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index 4556013bc4cb..2445d715f0e1 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -128,6 +128,26 @@ def test_imsave(): assert_array_equal(arr_dpi1, arr_dpi100) +def test_imsave_color_alpha(): + # The goal is to test that imsave will accept arrays with ndim=3 where + # the third dimension is color and alpha without raising any exceptions + from numpy import random + random.seed(1) + data = random.rand(256, 128, 4) + + buff = io.BytesIO() + plt.imsave(buff, data) + + buff.seek(0) + arr_buf = plt.imread(buff) + + assert arr_buf.shape == data.shape + + # Unfortunately, the AGG process "flattens" the RGBA data + # into an equivalent RGB data with no transparency. So we + # Can't directly compare the arrays like we could in some + # other imsave tests. + @image_comparison(baseline_images=['image_clip']) def test_image_clip(): from math import pi