Skip to content
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
50 changes: 35 additions & 15 deletions src/machinevisiontoolbox/ImageCore.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -2653,16 +2661,24 @@ def planes(self) -> 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)
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`
Expand Down Expand Up @@ -2697,20 +2713,24 @@ 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__``
.. seealso:: :meth:`planes` :meth:`red` :meth:`green` :meth:`blue` :meth:`__getitem__`
"""

colororder: dict[str, Any] | None
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]
Expand Down Expand Up @@ -2746,7 +2766,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]
Expand Down Expand Up @@ -2822,8 +2842,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
Expand Down
57 changes: 57 additions & 0 deletions tests/test_image_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading