From e90021c019bb05521e8d19021eeaffeaa0baa23d Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Tue, 24 Nov 2026 06:03:08 +1000 Subject: [PATCH] fix: accept the short Matplotlib option names (lw, c, ...) in mpl_styling mpl_styling merged its defaults and the caller's options by key, so a caller's lw=4 sat beside the default linewidth=2 and Matplotlib refused both. Add an artist argument (Line2D, Patch, Text, ...): when given, the options are first converted to the full names for that class. The Blobs plot methods now pass it. Co-Authored-By: Claude Sonnet 5.5 --- src/machinevisiontoolbox/ImageBlobs.py | 38 +++++++--- src/machinevisiontoolbox/base/graphics.py | 20 +++++- tests/base/test_mpl_styling.py | 85 +++++++++++++++++++++++ 3 files changed, 133 insertions(+), 10 deletions(-) diff --git a/src/machinevisiontoolbox/ImageBlobs.py b/src/machinevisiontoolbox/ImageBlobs.py index 57de947a..13ce5abc 100644 --- a/src/machinevisiontoolbox/ImageBlobs.py +++ b/src/machinevisiontoolbox/ImageBlobs.py @@ -18,6 +18,8 @@ import scipy as sp import spatialmath.base as smb from ansitable import ANSITable, Column +from matplotlib.lines import Line2D +from matplotlib.patches import Patch from spatialmath import SE2 from machinevisiontoolbox._image_typing import ImageMixinBase @@ -1858,7 +1860,9 @@ def plot_box(self, *args: Any, **kwargs: Any) -> None: :seealso: :meth:`plot_labelbox` :meth:`plot_centroid` :meth:`plot_perimeter` :func:`~machinevisiontoolbox.base.graphics.plot_box` """ - options = mpl_styling(args, dict(color="yellow", linewidth=2), kwargs) + options = mpl_styling( + args, dict(color="yellow", linewidth=2), kwargs, artist=Patch + ) for blob in self: smb.plot_box(lrbt=blob.bbox, **options) @@ -1902,7 +1906,9 @@ def plot_labelbox( :seealso: :meth:`plot_box` :meth:`plot_centroid` :meth:`plot_perimeter` :func:`~machinevisiontoolbox.base.graphics.plot_labelbox` """ - options = mpl_styling(fmt, dict(color="yellow", linewidth=2), kwargs) + options = mpl_styling( + fmt, dict(color="yellow", linewidth=2), kwargs, artist=Patch + ) for blob in self: plot_labelbox( text=label.format(blob.id), fmt=fmt, lrbt=blob.bbox, **options @@ -2009,7 +2015,9 @@ def plot_perimeter( :seealso: :meth:`perimeter` :meth:`perimeter_approx` :meth:`perimeter_hull` :meth:`plot_box` :meth:`plot_centroid` """ - options = mpl_styling(args, dict(color="yellow", linewidth=2), kwargs) + options = mpl_styling( + args, dict(color="yellow", linewidth=2), kwargs, artist=Line2D + ) if show == "full": perims = self.perimeter @@ -2061,7 +2069,9 @@ def plot_ellipse(self, *args: Any, **kwargs: Any) -> None: :seealso: :meth:`plot_axes` :meth:`plot_box` :meth:`plot_centroid` :func:`~spatialmath.base.plot_ellipse` """ - options = mpl_styling(args, dict(color="cyan", linewidth=2), kwargs) + options = mpl_styling( + args, dict(color="cyan", linewidth=2), kwargs, artist=Line2D + ) for blob in self: m = blob.moments @@ -2136,8 +2146,12 @@ 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) - b_options = mpl_styling(args, dict(color="green", linewidth=2), kwargs) + a_options = mpl_styling( + args, dict(color="red", linewidth=2), kwargs, artist=Line2D + ) + b_options = mpl_styling( + args, dict(color="green", linewidth=2), kwargs, artist=Line2D + ) for blob in self: T = SE2(blob.uc, blob.vc, blob.orientation) @@ -2248,7 +2262,9 @@ def plot_aligned_box(self, *args: Any, **kwargs: Any) -> None: :seealso: :meth:`plot_box` :meth:`plot_MER`:meth:`plot_centroid` """ - options = mpl_styling(args, dict(color="yellow", linewidth=2), kwargs) + options = mpl_styling( + args, dict(color="yellow", linewidth=2), kwargs, artist=Line2D + ) boxes = self.aligned_box() if not isinstance(boxes, list): @@ -2292,7 +2308,9 @@ def plot_MEC(self, *args: Any, **kwargs: Any) -> None: :seealso: :meth:`MEC` :meth:`plot_MER` :meth:`plot_box` :meth:`plot_centroid` """ - options = mpl_styling(args, dict(color="yellow", linewidth=2), kwargs) + options = mpl_styling( + args, dict(color="yellow", linewidth=2), kwargs, artist=Line2D + ) mecs = self.MEC if not isinstance(mecs, list): @@ -2336,7 +2354,9 @@ def plot_MER(self, *args: Any, **kwargs: Any) -> None: :seealso: :meth:`MER` :meth:`MEC` :meth:`plot_box` :meth:`plot_aligned_box` :meth:`plot_centroid` """ - options = mpl_styling(args, dict(color="yellow", linewidth=2), kwargs) + options = mpl_styling( + args, dict(color="yellow", linewidth=2), kwargs, artist=Line2D + ) mers = self.MER if not isinstance(mers, list): diff --git a/src/machinevisiontoolbox/base/graphics.py b/src/machinevisiontoolbox/base/graphics.py index 53ac3534..1b1d8f12 100644 --- a/src/machinevisiontoolbox/base/graphics.py +++ b/src/machinevisiontoolbox/base/graphics.py @@ -12,6 +12,8 @@ import cv2 import numpy as np import spatialmath.base as smb +from matplotlib import cbook +from matplotlib.artist import Artist from matplotlib.patches import Rectangle from machinevisiontoolbox.base import name2color @@ -990,7 +992,8 @@ def mpl_styling( fmt: str | tuple[str] | None = None, defaults: dict | None = None, kwargs: dict | None = None, -): + artist: type[Artist] | None = None, +) -> dict[str, Any]: """Merge Matplotlib style options :param fmt: a format string, defaults to None @@ -999,6 +1002,12 @@ def mpl_styling( :type defaults: dict, optional :param kwargs: a dictionary of keyword arguments , defaults to None :type kwargs: dict, optional + :param artist: the Matplotlib class that the options will be passed to, such as + ``Line2D``, ``Patch`` or ``Text``, defaults to None + :type artist: type[Artist], optional + + .. versionchanged:: 2.5.0 + Added ``artist``. Matplotlib has two distinct ways of specifying styling for plots: @@ -1021,6 +1030,12 @@ def mpl_styling( arguments ``kwargs``. The precedence in decreasing order is: ``kwargs``, ``fmt``, ``defaults``. + Matplotlib accepts many options under two names, for example ``lw`` for + ``linewidth`` and ``c`` for ``color``, but refuses a call that has both. If + ``artist`` is given, ``defaults`` and ``kwargs`` are first converted to the + full option names for that class, so ``lw=4`` replaces a default of + ``linewidth=2``. If ``artist`` is None the options are merged by name as given. + As a convenience to users, many Toolbox functions accept a ``fmt`` argument, which is passed to this function to merge with the keyword arguments. This allows users to specify styling in a compact format string, while still allowing for more @@ -1097,6 +1112,9 @@ def parse_matplotlib_fmt(fmt: str): res = parse_matplotlib_fmt(fmt) # Override with defaults if not specified in fmt + if artist is not None: + defaults = cbook.normalize_kwargs(defaults or {}, artist) + kwargs = cbook.normalize_kwargs(kwargs or {}, artist) options = (defaults or {}) | res | (kwargs or {}) return {k: v for k, v in options.items() if v is not None} diff --git a/tests/base/test_mpl_styling.py b/tests/base/test_mpl_styling.py index cc317e14..94f88ee1 100644 --- a/tests/base/test_mpl_styling.py +++ b/tests/base/test_mpl_styling.py @@ -2,6 +2,9 @@ import matplotlib.pyplot as plt import pytest +from matplotlib.lines import Line2D +from matplotlib.patches import Patch +from matplotlib.text import Text from machinevisiontoolbox.base import mpl_styling @@ -40,3 +43,85 @@ def test_keyword_options_override_compact_marker(): "linestyle": "--", "linewidth": 2, } + + +@pytest.mark.parametrize( + "artist, short, long_name", + [ + (Line2D, "lw", "linewidth"), + (Line2D, "c", "color"), + (Line2D, "ls", "linestyle"), + (Line2D, "ms", "markersize"), + (Patch, "ec", "edgecolor"), + (Patch, "fc", "facecolor"), + (Text, "ha", "horizontalalignment"), + (Text, "size", "fontsize"), + ], +) +def test_alias_replaces_the_default(artist, short, long_name): + options = mpl_styling(None, {long_name: "default"}, {short: "mine"}, artist=artist) + assert options == {long_name: "mine"} + + +def test_alias_in_defaults_is_converted_too(): + options = mpl_styling(None, {"lw": 2}, {"linewidth": 5}, artist=Line2D) + assert options == {"linewidth": 5} + + +def test_alias_beats_the_format_string(): + options = mpl_styling("r--", {}, {"c": "blue", "ls": ":"}, artist=Line2D) + assert options == {"color": "blue", "linestyle": ":"} + + +def test_merged_options_are_accepted_by_matplotlib(): + options = mpl_styling( + None, {"color": "red", "linewidth": 2}, {"lw": 4}, artist=Line2D + ) + fig, ax = plt.subplots() + try: + (line,) = ax.plot([0, 1], [0, 1], **options) + assert line.get_linewidth() == 4 + assert line.get_color() == "red" + finally: + plt.close(fig) + + +def test_both_names_given_by_the_caller_still_raises(): + with pytest.raises(TypeError, match="aliases of one another"): + mpl_styling(None, {}, {"lw": 1, "linewidth": 2}, artist=Line2D) + + +def test_without_artist_the_names_are_not_converted(): + assert mpl_styling(None, {"linewidth": 2}, {"lw": 4}) == {"linewidth": 2, "lw": 4} + + +def test_none_values_are_still_dropped(): + assert mpl_styling(None, {"color": "red"}, {"lw": None}, artist=Line2D) == { + "color": "red" + } + + +@pytest.mark.parametrize("name", ["plot_axes", "plot_ellipse", "plot_perimeter"]) +def test_blobs_plot_accepts_aliases(name): + from machinevisiontoolbox import Image + + blobs = Image.Read("sharks.png").blobs() + fig, ax = plt.subplots() + try: + getattr(blobs[0], name)(lw=4, c="blue") + assert all(line.get_linewidth() == 4 for line in ax.lines) + assert all(line.get_color() == "blue" for line in ax.lines) + finally: + plt.close(fig) + + +def test_blobs_plot_box_accepts_aliases(): + from machinevisiontoolbox import Image + + blobs = Image.Read("sharks.png").blobs() + fig, ax = plt.subplots() + try: + blobs[0].plot_box(lw=4, ec="blue") + assert ax.patches[0].get_linewidth() == 4 + finally: + plt.close(fig)