8000 Merge pull request #1956 from Westacular/imsave_alpha · matplotlib/matplotlib@b6b9062 · GitHub
[go: up one dir, main page]

Skip to content

Commit b6b9062

Browse files
committed
Merge pull request #1956 from Westacular/imsave_alpha
Imsave now preserves the alpha channel.
2 parents 668690d + f16a1d3 commit b6b9062

File tree

2 files changed

+12
-9
lines changed

2 files changed

+12
-9
lines changed

lib/matplotlib/image.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1273,7 +1273,7 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
12731273
fig = Figure(figsize=figsize, dpi=dpi, frameon=False)
12741274
canvas = FigureCanvas(fig)
12751275
im = fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin)
1276-
fig.savefig(fname, dpi=dpi, format=format)
1276+
fig.savefig(fname, dpi=dpi, format=format, transparent=True)
12771277

12781278

12791279
def pil_to_array( pilImage ):

lib/matplotlib/tests/test_image.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from matplotlib import rcParams
66
import matplotlib.pyplot as plt
77
from nose.tools import assert_raises
8-
from numpy.testing import assert_array_equal
8+
from numpy.testing import assert_array_equal, assert_array_almost_equal
99

1010
import io
1111
import os
@@ -129,8 +129,9 @@ def test_imsave():
129129
assert_array_equal(arr_dpi1, arr_dpi100)
130130

131131
def test_imsave_color_alpha():
132-
# The goal is to test that imsave will accept arrays with ndim=3 where
133-
# the third dimension is color and alpha without raising any exceptions
132+
# Test that imsave accept arrays with ndim=3 where the third dimension is
133+
# color and alpha without raising any exceptions, and that the data is
134+
# acceptably preserved through a save/read roundtrip.
134135
from numpy import random
135136
random.seed(1)
136137
data = random.rand(256, 128, 4)
@@ -141,12 +142,14 @@ def test_imsave_color_alpha():
141142
buff.seek(0)
142143
arr_buf = plt.imread(buff)
143144

144-
assert arr_buf.shape == data.shape
145+
# Recreate the float -> uint8 -> float32 conversion of the data
146+
data = (255*data).astype('uint8').astype('float32')/255
147+
# Wherever alpha values were rounded down to 0, the rgb values all get set
148+
# to 0 during imsave (this is reasonable behaviour).
149+
# Recreate that here:
150+
data[data[:, :, 3] == 0] = 0
145151

146-
# Unfortunately, the AGG process "flattens" the RGBA data
147-
# into an equivalent RGB data with no transparency. So we
148-
# Can't directly compare the arrays like we could in some
149-
# other imsave tests.
152+
assert_array_equal(data, arr_buf)
150153

151154
@image_comparison(baseline_images=['image_clip'])
152155
def test_image_clip():

0 commit comments

Comments
 (0)
0