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
62 changes: 48 additions & 14 deletions src/machinevisiontoolbox/ImageBlobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@
from machinevisiontoolbox.base.graphics import mpl_styling, plot_labelbox
from machinevisiontoolbox.decorators import array_result, scalar_result

MAJOR_AXIS_STYLE: dict[str, Any] = dict(color="red", linewidth=2)
"""Default style of the major axis drawn by :meth:`Blobs.plot_axes`"""
MINOR_AXIS_STYLE: dict[str, Any] = dict(color="green", linewidth=2)
"""Default style of the minor axis drawn by :meth:`Blobs.plot_axes`"""

if TYPE_CHECKING:
pass

Expand Down Expand Up @@ -1914,15 +1919,26 @@ def plot_labelbox(
text=label.format(blob.id), fmt=fmt, lrbt=blob.bbox, **options
)

def plot_centroid(self, *args: Any, label: bool = False, **kwargs: Any) -> None:
def plot_centroid(
self,
*args: Any,
label: bool = False,
text_style: dict[str, Any] | None = None,
**kwargs: Any,
) -> None:
"""
Plot the centroid of blobs using Matplotlib

:param label: add a sequential numeric label to each point, defaults to False
:type label: bool
:param text_style: Matplotlib text options for the label, such as
``dict(color="white", fontsize=12)``, defaults to None
:param args: optional marker, such as ``'bx'``, which sets ``marker`` in ``kwargs``
:param kwargs: other arguments passed to ``plot_point``

.. versionchanged:: 2.5.0
Added ``text_style``.

Plot the major and minor axes of a blob or blobs on the current Matplotlib axes.

If no marker style is given then it will be an overlaid "o" and "x"
Expand Down Expand Up @@ -1953,19 +1969,19 @@ def plot_centroid(self, *args: Any, label: bool = False, **kwargs: Any) -> None:
blobs[3].plot_centroid(marker="P", markeredgecolor="lightsteelblue", markerfacecolor="w", fillstyle="full")
:seealso: :meth:`plot_box` :meth:`plot_perimeter` :func:`~machinevisiontoolbox.base.graphics.plot_point`
"""
if label:
text = "{:d}"
else:
text = ""

if len(args) > 0:
kwargs["marker"] = args[0]
elif "marker" not in kwargs:
kwargs["marker"] = ["bx", "bo"]
kwargs["fillstyle"] = "none"

for i, blob in enumerate(self):
smb.plot_point(pos=blob.centroid, text=text.format(i), **kwargs)
smb.plot_point(
pos=blob.centroid,
text=str(i) if label else None,
textargs=text_style,
**kwargs,
)

def plot_perimeter(
self,
Expand Down Expand Up @@ -2109,12 +2125,30 @@ def blob_frame(self) -> SE2:
frames.append(SE2(blob.uc, blob.vc, blob.orientation))
return frames

def plot_axes(self, *args: Any, **kwargs: Any) -> None:
def plot_axes(
self,
*args: Any,
major_style: dict[str, Any] | None = None,
minor_style: dict[str, Any] | None = None,
**kwargs: Any,
) -> None:
"""
Plot equivalent ellipse axes of blobs using Matplotlib

:param args: optional Matplotlib format string, such as ``"r--"``
:param kwargs: line style parameters passed to ``plot``
:param major_style: Matplotlib line options for the major axis only, such as
``dict(color="orange", linestyle="--")``, defaults to None
:param minor_style: Matplotlib line options for the minor axis only,
defaults to None
:param args: optional Matplotlib format string, such as ``"r--"``, which
applies to both axes
:param kwargs: line style parameters passed to ``plot``, which apply to both axes

The options for each axis are merged in this order, later ones winning:
the defaults (:data:`MAJOR_AXIS_STYLE` and :data:`MINOR_AXIS_STYLE`), the
format string, ``kwargs``, and finally ``major_style`` or ``minor_style``.

.. versionchanged:: 2.5.0
Added ``major_style`` and ``minor_style``.

Plot the major and minor axes of a blob or blobs on the current Matplotlib axes.
These are the axes of the equivalent ellipse and the intersection point is
Expand Down Expand Up @@ -2147,11 +2181,11 @@ def plot_axes(self, *args: Any, **kwargs: Any) -> None:
:seealso: :meth:`plot_ellipse` :meth:`plot_box` :meth:`plot_centroid`
"""
a_options = mpl_styling(
args, dict(color="red", linewidth=2), kwargs, artist=Line2D
)
args, MAJOR_AXIS_STYLE, kwargs, artist=Line2D
) | mpl_styling(None, None, major_style, artist=Line2D)
b_options = mpl_styling(
args, dict(color="green", linewidth=2), kwargs, artist=Line2D
)
args, MINOR_AXIS_STYLE, kwargs, artist=Line2D
) | mpl_styling(None, None, minor_style, artist=Line2D)

for blob in self:
T = SE2(blob.uc, blob.vc, blob.orientation)
Expand Down
84 changes: 84 additions & 0 deletions tests/test_image_blobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -733,6 +733,28 @@ def test_plot_centroid_fmt(self):
def test_plot_centroid_kwargs(self):
self._test_plot_adds("plot_centroid", self._lines, marker="x", color="red")

def test_plot_centroid_text_style(self):
fig, ax = self._fresh_ax()
self.blobs1.plot_centroid(
label=True, text_style=dict(color="white", fontsize=17)
)
(text,) = ax.texts
self.assertEqual(text.get_color(), "white")
self.assertEqual(text.get_fontsize(), 17)
plt.close(fig)

def test_plot_centroid_label_without_text_style(self):
fig, ax = self._fresh_ax()
self.blobs1.plot_centroid(label=True)
self.assertEqual(len(ax.texts), 1)
plt.close(fig)

def test_plot_centroid_text_style_without_label_adds_no_text(self):
fig, ax = self._fresh_ax()
self.blobs1.plot_centroid(text_style=dict(color="white"))
self.assertEqual(len(ax.texts), 0)
plt.close(fig)

# ------------------------------------------------------------------ #
# plot_perimeter (plt.plot → 1 Line2D per blob)
# ------------------------------------------------------------------ #
Expand Down Expand Up @@ -772,6 +794,68 @@ def test_plot_axes_fmt(self):
def test_plot_axes_kwargs(self):
self._test_plot_adds("plot_axes", self._lines, color="blue")

def _axes_lines(self, *args, **kwargs):
"""Plot the axes of one blob; return its (major, minor) Line2D."""
fig, ax = self._fresh_ax()
self.blobs1.plot_axes(*args, **kwargs)
major, minor = ax.lines[-2:]
plt.close(fig)
return major, minor

def test_plot_axes_default_colors(self):
major, minor = self._axes_lines()
self.assertEqual(major.get_color(), "red")
self.assertEqual(minor.get_color(), "green")

def test_plot_axes_kwargs_apply_to_both(self):
major, minor = self._axes_lines(color="blue", linestyle="--")
for line in (major, minor):
self.assertEqual(line.get_color(), "blue")
self.assertEqual(line.get_linestyle(), "--")

def test_plot_axes_major_style_only(self):
major, minor = self._axes_lines(major_style=dict(color="orange", linewidth=5))
self.assertEqual(major.get_color(), "orange")
self.assertEqual(major.get_linewidth(), 5)
self.assertEqual(minor.get_color(), "green") # untouched default
self.assertEqual(minor.get_linewidth(), 2)

def test_plot_axes_minor_style_only(self):
major, minor = self._axes_lines(minor_style=dict(linestyle=":"))
self.assertEqual(minor.get_linestyle(), ":")
self.assertEqual(major.get_linestyle(), "-")
self.assertEqual(minor.get_color(), "green")

def test_plot_axes_style_beats_kwargs_and_fmt(self):
major, minor = self._axes_lines(
"c--", color="blue", major_style=dict(color="orange")
)
self.assertEqual(major.get_color(), "orange") # style wins over kwargs
self.assertEqual(major.get_linestyle(), "--") # fmt still applies
self.assertEqual(minor.get_color(), "blue") # kwargs wins over fmt
self.assertEqual(minor.get_linestyle(), "--")

def test_plot_axes_style_and_kwargs_may_use_different_spellings(self):
# lw in kwargs and linewidth in the style used to be an alias clash
major, minor = self._axes_lines(lw=3, major_style=dict(linewidth=5))
self.assertEqual(major.get_linewidth(), 5)
self.assertEqual(minor.get_linewidth(), 3)
major, minor = self._axes_lines(minor_style=dict(lw=4, c="k"))
self.assertEqual(minor.get_linewidth(), 4)
self.assertEqual(minor.get_color(), "k")

def test_plot_axes_does_not_change_the_defaults(self):
from machinevisiontoolbox.ImageBlobs import MAJOR_AXIS_STYLE, MINOR_AXIS_STYLE

before = dict(MAJOR_AXIS_STYLE), dict(MINOR_AXIS_STYLE)
self._axes_lines(
"r--",
color="blue",
major_style=dict(color="k"),
minor_style=dict(linewidth=4),
)
self.assertEqual((MAJOR_AXIS_STYLE, MINOR_AXIS_STYLE), before)

# ------------------------------------------------------------------ #
# plot_aligned_box (smb.plot_polygon → 1 Line2D per blob)
# ------------------------------------------------------------------ #
Expand Down
Loading