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
38 changes: 29 additions & 9 deletions src/machinevisiontoolbox/ImageBlobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down
20 changes: 19 additions & 1 deletion src/machinevisiontoolbox/base/graphics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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:

Expand All @@ -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
Expand Down Expand Up @@ -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}

Expand Down
85 changes: 85 additions & 0 deletions tests/base/test_mpl_styling.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
Loading