Skip to content

FIX: make_image should not modify original array #29892

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

Merged
merged 1 commit into from
Apr 13, 2025
Merged
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
5 changes: 5 additions & 0 deletions lib/matplotlib/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,8 @@ def _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification=1.0,
if not (A.ndim == 2 or A.ndim == 3 and A.shape[-1] in (3, 4)):
raise ValueError(f"Invalid shape {A.shape} for image data")

float_rgba_in = A.ndim == 3 and A.shape[-1] == 4 and A.dtype.kind == 'f'

# if antialiased, this needs to change as window sizes
# change:
interpolation_stage = self._interpolation_stage
Expand Down Expand Up @@ -520,6 +522,9 @@ def _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification=1.0,
# Resample in premultiplied alpha space. (TODO: Consider
# implementing premultiplied-space resampling in
# span_image_resample_rgba_affine::generate?)
if float_rgba_in and np.ndim(alpha) == 0 and np.any(A[..., 3] < 1):
# Do not modify original RGBA input
A = A.copy()
A[..., :3] *= A[..., 3:]
res = _resample(self, A, out_shape, t)
np.divide(res[..., :3], res[..., 3:], out=res[..., :3],
Expand Down
27 changes: 27 additions & 0 deletions lib/matplotlib/tests/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,33 @@ def test_imshow_alpha(fig_test, fig_ref):
ax3.imshow(rgbau)


@pytest.mark.parametrize('n_channels, is_int, alpha_arr, opaque',
[(3, False, False, False), # RGB float
(4, False, False, False), # RGBA float
(4, False, True, False), # RGBA float with alpha array
(4, False, False, True), # RGBA float with solid color
(4, True, False, False)]) # RGBA unint8
def test_imshow_multi_draw(n_channels, is_int, alpha_arr, opaque):
if is_int:
array = np.random.randint(0, 256, (2, 2, n_channels))
else:
array = np.random.random((2, 2, n_channels))
if opaque:
array[:, :, 3] = 1

if alpha_arr:
alpha = np.array([[0.3, 0.5], [1, 0.8]])
else:
alpha = None

fig, ax = plt.subplots()
im = ax.imshow(array, alpha=alpha)
fig.draw_without_rendering()

# Draw should not modify original array
np.testing.assert_array_equal(array, im._A)


def test_cursor_data():
from matplotlib.backend_bases import MouseEvent

Expand Down
Loading