diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index e193e0d9fd3e..e9547cd8d6c6 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -1677,6 +1677,23 @@ def test__resample_valid_output(): resample(np.zeros((9, 9)), out) +def test__resample_nonaffine_mesh_shape(): + # A non-affine transform whose inverse returns the wrong number of mesh + # points must be rejected rather than read past the mesh buffer. + class BadMeshTransform(Transform): + input_dims = output_dims = 2 + + def inverted(self): + return self + + def transform(self, values): + return np.zeros((1, 2)) + + with pytest.raises(RuntimeError, match="mesh array should have shape"): + mpl._image.resample(np.zeros((9, 9)), np.zeros((9, 9)), + BadMeshTransform()) + + @pytest.mark.parametrize("data, interpolation, expected", [(np.array([[0.1, 0.3, 0.2]]), mimage.NEAREST, np.array([[0.1, 0.1, 0.1, 0.3, 0.3, 0.3, 0.3, 0.2, 0.2, 0.2]])), diff --git a/src/_image_wrapper.cpp b/src/_image_wrapper.cpp index 8944a2d44041..d53f47d55ebb 100644 --- a/src/_image_wrapper.cpp +++ b/src/_image_wrapper.cpp @@ -86,6 +86,14 @@ _get_transform_mesh(const py::object& transform, const py::ssize_t *dims) output_mesh_array.ndim())); } + if (output_mesh_array.shape(0) != mesh_dims[0] || + output_mesh_array.shape(1) != mesh_dims[1]) { + throw std::runtime_error( + "Inverse transformed mesh array should have shape ({}, {}) not ({}, {})"_s.format( + mesh_dims[0], mesh_dims[1], + output_mesh_array.shape(0), output_mesh_array.shape(1))); + } + return output_mesh_array; }