Skip to content

Fixed imsave() saving incorrect color map #29203

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added build.out
Empty file.
1 change: 1 addition & 0 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5869,6 +5869,7 @@ def imshow(self, X, cmap=None, norm=None, *, aspect=None,
`~matplotlib.pyplot.imshow` expects RGB images adopting the straight
(unassociated) alpha representation.
"""

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change

im = mimage.AxesImage(self, cmap=cmap, norm=norm, colorizer=colorizer,
interpolation=interpolation, origin=origin,
extent=extent, filternorm=filternorm,
Expand Down
7 changes: 7 additions & 0 deletions lib/matplotlib/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
Affine2D, BboxBase, Bbox, BboxTransform, BboxTransformTo,
IdentityTransform, TransformedBbox)


_log = logging.getLogger(__name__)

# map interpolation strings to module constants
Expand Down Expand Up @@ -1093,6 +1094,7 @@ def set_data(self, x, y, A):
"""
Set the grid for the pixel centers, and the pixel values.


Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change

Parameters
----------
x, y : 1D array-like
Expand Down Expand Up @@ -1582,6 +1584,10 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
_api.check_in_list(('upper', 'lower'), origin=origin)
if origin == "lower":
arr = arr[::-1]

if (isinstance(arr, list)):
arr = np.asarray(arr, dtype=np.uint8)

Comment on lines +1587 to +1590
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's move the format coersion above the origin handling. While the reversal ([::-1]) also works for lists, it's more efficient and easier to understand if we ensure that we have the array already there.

Also arr = np.asanyarray(array) should be enough.

  • asanyarray() instead of asarray() Passing through array subclasses should be ok - we currently do that as well.
  • let's not do dtype conversion in this PR - we currently also don't do this for arrays. The user is responsible for passing reasonable types. Any change to that would be a separate topic.

if (isinstance(arr, memoryview) and arr.format == "B"
and arr.ndim == 3 and arr.shape[-1] == 4):
# Such an ``arr`` would also be handled fine by sm.to_rgba below
Expand Down Expand Up @@ -1630,6 +1636,7 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
background = PIL.Image.new("RGB", pil_shape, color)
background.paste(image, image)
image = background

pil_kwargs.setdefault("format", format)
pil_kwargs.setdefault("dpi", (dpi, dpi))
image.save(fname, **pil_kwargs)
Expand Down
19 changes: 19 additions & 0 deletions lib/matplotlib/tests/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,25 @@ def test_imsave_fspath(fmt):
plt.imsave(Path(os.devnull), np.array([[0, 1]]), format=fmt)


def test_imsave_python_vanilla_list():
# Initializing RGBA data
# Instead of testing numpy array, use python list
input_img = [
[[255, 0, 0, 1], [0, 255, 0, 1], [0, 0, 255, 1]],
[[0, 255, 0, 1], [0, 255, 0, 1], [0, 0, 0, 1]],
[[0, 0, 255, 1], [0, 0, 255, 1], [0, 0, 0, 1]]
]
buff = io.BytesIO()
plt.imsave(buff, input_img, format="png")
buff.seek(0)
read_img = plt.imread(buff)

# Need to multiply by 255 to adjust for normalization in imread()
read_img = (255*read_img).astype('uint8')

assert_array_equal(np.array(input_img), read_img)


def test_imsave_color_alpha():
# Test that imsave accept arrays with ndim=3 where the third dimension is
# color and alpha without raising any exceptions, and that the data is
Expand Down
Loading