From 066aff1a5c71e7dff17d569386e943c26456944b Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Thu, 26 Nov 2026 09:50:51 +1000 Subject: [PATCH 1/2] feat: plane() and planes() take copy=True for an independent, C-contiguous result The default is unchanged: a single plane is a view that shares its pixels with the image. Co-Authored-By: Claude Sonnet 5.5 --- src/machinevisiontoolbox/ImageCore.py | 46 ++++++++++++++------- tests/test_image_core.py | 57 +++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 14 deletions(-) diff --git a/src/machinevisiontoolbox/ImageCore.py b/src/machinevisiontoolbox/ImageCore.py index c5b41d7c..3ec71219 100644 --- a/src/machinevisiontoolbox/ImageCore.py +++ b/src/machinevisiontoolbox/ImageCore.py @@ -2633,17 +2633,25 @@ def nplanes(self) -> int: else: return int(self._A.shape[-1]) - def planes(self) -> Iterator[Image]: + def planes(self, copy: bool = False) -> Iterator[Image]: """ Iterator for image planes + :param copy: if True each plane is an independent, C-contiguous copy, + otherwise it is a view that shares its pixels with the image, + defaults to False + :type copy: bool, optional :return out: image containing a single plane :rtype: :class:`Image` Iterator that returns sequential image planes. - .. note:: Each plane is a view that shares its pixels with the image, and is - not C-contiguous. See :meth:`__getitem__`. + .. note:: By default each plane is a view that shares its pixels with the + image, and is not C-contiguous. Use ``copy=True`` for planes that can be + drawn into, or changed without changing the image. See :meth:`plane`. + + .. versionchanged:: 2.5.0 + Added the ``copy`` option. .. rubric:: Examples @@ -2655,14 +2663,20 @@ def planes(self) -> Iterator[Image]: >>> print(plane) """ for i in range(self.nplanes): - yield self.plane(i) + yield self.plane(i, copy=copy) - def plane(self, planes: int | str | list[int] | tuple[int, ...]) -> "Image": + def plane( + self, planes: int | str | list[int] | tuple[int, ...], copy: bool = False + ) -> "Image": """ Extract plane(s) from color image :param planes: planes to extract :type planes: int, list, str + :param copy: if True the result is an independent, C-contiguous copy, + otherwise a single plane is a view that shares its pixels with the + image, defaults to False + :type copy: bool, optional :raises ValueError: if image is not color :return out: image containing only the selected planes :rtype: :class:`Image` @@ -2697,11 +2711,15 @@ def plane(self, planes: int | str | list[int] | tuple[int, ...]) -> "Image": - To select more than one plane, use either a sequence of integers or a string of colon separated plane names. - For a single-plane image the index must be zero. - - A single plane, selected by an int or a name, is a view that shares its pixels - with the image. Several planes, selected by a name string or a list, are a - new array, but a planar one. Neither is C-contiguous, so drawing into the - result raises a ``ValueError``; use ``Image(out.A, copy=True)`` to make a - contiguous copy. See :class:`Image`. + - By default a single plane, selected by an int or a name, is a view that + shares its pixels with the image. Several planes, selected by a name string + or a list, are a new array, but a planar one. Neither is C-contiguous, so + drawing into the result raises a ``ValueError``. With ``copy=True`` the + result is always an independent, C-contiguous copy that can be drawn into, + and changing it does not change the image. See :class:`Image`. + + .. versionchanged:: 2.5.0 + Added the ``copy`` option. .. seealso:: :meth:`red` :meth:`green` :meth:`blue` :meth:``__getitem__`` """ @@ -2710,7 +2728,7 @@ def plane(self, planes: int | str | list[int] | tuple[int, ...]) -> "Image": iplanes: Any if isinstance(planes, int): if planes == 0 and self.nplanes == 1: - return self + return self.copy() if copy else self if planes < 0 or planes >= self.nplanes: raise ValueError("plane index out of range") iplanes = [planes] @@ -2746,7 +2764,7 @@ def plane(self, planes: int | str | list[int] | tuple[int, ...]) -> "Image": if isinstance(iplanes, list) and len(iplanes) == 1: iplanes = iplanes[0] colororder = None - return self.__class__(self._A[:, :, iplanes], colororder=colororder) + return self.__class__(self._A[:, :, iplanes], colororder=colororder, copy=copy) def __getitem__( self, keys: int | str | tuple[slice, slice] | tuple[slice, slice, slice] @@ -2822,8 +2840,8 @@ def __getitem__( C-contiguous: a plane of a color image, a region of interest and a reversed slice are all strided, and a string such as ``"BGR"`` gives a planar layout. The ``draw_*`` methods and OpenCV functions that write into an image refuse such - an array. Use ``Image(img[...].A, copy=True)`` to make a contiguous copy that - shares nothing with ``img``. See :class:`Image`. + an array. Use ``Image(img[...].A, copy=True)``, or :meth:`plane` with ``copy=True``, + to make a contiguous copy that shares nothing with ``img``. See :class:`Image`. .. warning:: The order of the indices is column, row and plane. This is the opposite of the order used for NumPy index on the underlying diff --git a/tests/test_image_core.py b/tests/test_image_core.py index 944b1c5e..b06c555f 100644 --- a/tests/test_image_core.py +++ b/tests/test_image_core.py @@ -188,6 +188,63 @@ def test_getitem_invalid_key_type(self): with self.assertRaises(ValueError): im[1.5] + def test_plane_copy_is_independent_and_contiguous(self): + a = np.arange(60, dtype=np.uint8).reshape((5, 4, 3)) + im = Image(a, colororder="RGB") + for key in (1, "G", "BGR", "B:R", [0, 2], (2, 1)): + out = im.plane(key, copy=True) + self.assertTrue(out.array.flags.c_contiguous, key) + self.assertFalse(np.shares_memory(out.array, a), key) + out._A[...] = 0 # changing the copy leaves the image alone + nt.assert_array_equal(im.array, a) + nt.assert_array_equal(out.array.shape, im.plane(key).array.shape) + + def test_plane_copy_keeps_values_and_colororder(self): + a = np.arange(60, dtype=np.uint8).reshape((5, 4, 3)) + im = Image(a, colororder="RGB") + for key in (1, "BGR", "B:R", [0, 2]): + view, copy = im.plane(key), im.plane(key, copy=True) + nt.assert_array_equal(copy.array, view.array) + self.assertEqual(copy.colororder_str, view.colororder_str) + + def test_plane_default_stays_a_view_for_a_single_plane(self): + a = np.arange(60, dtype=np.uint8).reshape((5, 4, 3)) + im = Image(a, colororder="RGB") + self.assertTrue(np.shares_memory(im.plane(1).array, a)) + self.assertTrue(np.shares_memory(im.plane("G").array, a)) + self.assertTrue(np.shares_memory(im.plane(1, copy=False).array, a)) + + def test_plane_copy_can_be_drawn_into(self): + im = Image(np.zeros((8, 10, 3), dtype=np.uint8), colororder="RGB") + with self.assertRaises(ValueError): + im.plane(1).draw_circle((3, 3), 2, color=[255]) + green = im.plane(1, copy=True) + green.draw_circle((3, 3), 2, color=[255]) + self.assertEqual(green.array.max(), 255) + self.assertEqual(im.array.max(), 0) # the original is untouched + bgr = im.plane("BGR", copy=True) + bgr.draw_circle((3, 3), 2, color=[1, 2, 3]) + + def test_plane_copy_of_a_greyscale_image(self): + a = np.arange(20, dtype=np.uint8).reshape((5, 4)) + im = Image(a) + self.assertIs(im.plane(0), im) + out = im.plane(0, copy=True) + self.assertIsNot(out, im) + self.assertFalse(np.shares_memory(out.array, a)) + nt.assert_array_equal(out.array, a) + + def test_planes_copy(self): + a = np.arange(60, dtype=np.uint8).reshape((5, 4, 3)) + im = Image(a, colororder="RGB") + for p in im.planes(copy=True): + self.assertTrue(p.array.flags.c_contiguous) + self.assertFalse(np.shares_memory(p.array, a)) + copies = list(im.planes(copy=True)) + self.assertEqual(len(copies), 3) + for i, p in enumerate(copies): + nt.assert_array_equal(p.array, a[:, :, i]) + def test_colordict(self): cdict = Image.colororder2dict("RGBA") self.assertIsInstance(cdict, dict) From 62efe010957a327067197924334f5c1a24e38ac9 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Thu, 26 Nov 2026 10:06:06 +1000 Subject: [PATCH 2/2] docs: plane and planes refer to each other in their seealso Co-Authored-By: Claude Sonnet 5.5 --- src/machinevisiontoolbox/ImageCore.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/machinevisiontoolbox/ImageCore.py b/src/machinevisiontoolbox/ImageCore.py index 3ec71219..d156ba31 100644 --- a/src/machinevisiontoolbox/ImageCore.py +++ b/src/machinevisiontoolbox/ImageCore.py @@ -2661,6 +2661,8 @@ def planes(self, copy: bool = False) -> Iterator[Image]: >>> img = Image.Read("flowers4.png") # in RGB order >>> for plane in img.planes(): >>> print(plane) + + .. seealso:: :meth:`plane` :meth:`__getitem__` """ for i in range(self.nplanes): yield self.plane(i, copy=copy) @@ -2721,7 +2723,7 @@ def plane( .. versionchanged:: 2.5.0 Added the ``copy`` option. - .. seealso:: :meth:`red` :meth:`green` :meth:`blue` :meth:``__getitem__`` + .. seealso:: :meth:`planes` :meth:`red` :meth:`green` :meth:`blue` :meth:`__getitem__` """ colororder: dict[str, Any] | None