diff --git a/src/machinevisiontoolbox/ImageBlobs.py b/src/machinevisiontoolbox/ImageBlobs.py index b1521c1f..615fde25 100644 --- a/src/machinevisiontoolbox/ImageBlobs.py +++ b/src/machinevisiontoolbox/ImageBlobs.py @@ -1872,15 +1872,37 @@ def plot_box(self, *args: Any, **kwargs: Any) -> None: smb.plot_box(lrbt=blob.bbox, **options) def plot_labelbox( - self, fmt: str | None = None, label: str = "{:d}", **kwargs: Any + self, + fmt: str | None = None, + label: str = "{:d}", + *, + position: str = "topleft", + textcolor: Any = None, + labelcolor: Any = None, + text_style: dict[str, Any] | None = None, + **kwargs: Any, ) -> None: """ Plot a labelled bounding box of blobs using Matplotlib - :param fmt: Matplotlib format string, passed to ``plot_labelbox`` + :param fmt: Matplotlib format string for the box, such as ``"r--"`` :param label: label to be displayed on the bounding box, defaults to blob id :type label: str or bool, optional - :param kwargs: arguments passed to ``plot_labelbox`` + :param position: place to draw the label: ``"topleft"`` (default), + ``"topright"``, ``"bottomleft"`` or ``"bottomright"`` + :param textcolor: color of the label text, defaults to black + :param labelcolor: label background color, defaults to the edge color of the box + :param text_style: Matplotlib text options for the label, such as + ``dict(fontsize=12, fontweight="bold")``, defaults to None + :param kwargs: Matplotlib patch options for the box, passed to ``plot_labelbox`` + + The label text color and background can be set by ``text_style``, + by ``textcolor`` and ``labelcolor``, or by default, and the most specific + wins: see :func:`~machinevisiontoolbox.base.graphics.plot_labelbox`. + + .. versionchanged:: 2.5.0 + Added ``text_style``, and the label background follows the edge color of the + box however that was set. Plot a labelled bounding box for every blob described by this object. @@ -1916,7 +1938,15 @@ def plot_labelbox( ) for blob in self: # the format string is already in options, so is not passed again - plot_labelbox(text=label.format(blob.id), lrbt=blob.bbox, **options) + plot_labelbox( + text=label.format(blob.id), + lrbt=blob.bbox, + position=position, + textcolor=textcolor, + labelcolor=labelcolor, + text_style=text_style, + **options, + ) def plot_centroid( self, diff --git a/src/machinevisiontoolbox/base/graphics.py b/src/machinevisiontoolbox/base/graphics.py index 901b179d..884993bb 100644 --- a/src/machinevisiontoolbox/base/graphics.py +++ b/src/machinevisiontoolbox/base/graphics.py @@ -15,6 +15,7 @@ from matplotlib import cbook, colors from matplotlib.artist import Artist from matplotlib.patches import Patch, Rectangle +from matplotlib.text import Text from machinevisiontoolbox.base import name2color @@ -316,6 +317,7 @@ def plot_labelbox( textcolor: Any = None, labelcolor: Any = None, position: str = "topleft", + text_style: dict[str, Any] | None = None, **boxargs: Any, ) -> Rectangle: """ @@ -325,19 +327,31 @@ def plot_labelbox( :type text: str :param fmt: format string for the simply specifying the box edge style, eg. ``"y--"`` for a dashed yellow box :type fmt: str, optional - :param textcolor: text color, defaults to None + :param textcolor: text color, defaults to the Matplotlib default, black :type textcolor: str, array_like(3), optional - :param labelcolor: label background color + :param labelcolor: label background color, defaults to the edge color of the box :type labelcolor: str, array_like(3), optional :param position: place to draw the label: 'topleft' (default), 'topright, 'bottomleft' or 'bottomright' - :type above: str, optional + :type position: str, optional + :param text_style: Matplotlib text options for the label, such as + ``dict(fontsize=12, fontweight="bold")``, defaults to None :param boxargs: arguments passed to :func:`plot_box` Plot a box with a label above it. The position of the box is specified using - the same arguments as for ``plot_box``. The label font is specified using - the same arguments as for ``plot_text``. If ``labelcolor`` is specified it - is used as the background color for the text label, otherwise the box color - is used. + the same arguments as for ``plot_box``. The label is drawn by ``plot_text``, and + ``text_style`` holds any of its Matplotlib text options. + + The label's text color and background each have three possible sources, and the + most specific one wins: ``text_style`` (``color``, ``backgroundcolor`` or the + ``facecolor`` of ``bbox``), then ``textcolor`` and ``labelcolor``, then the default. + The default background is the final edge color of the box, however that was set + (``color``, ``edgecolor`` or the format string). Other keys of ``bbox`` in + ``text_style``, such as a border or rounded corners, are merged over the default + borderless background. + + .. versionchanged:: 2.5.0 + Added ``text_style``, and the label background now follows the edge color + of the box, not only the ``color`` option. Example: @@ -373,9 +387,6 @@ def plot_labelbox( bbox = rect.get_bbox() - if labelcolor is None: - labelcolor = boxargs.get("color") - if position == "topleft": pos = (bbox.xmin, bbox.ymin) valign = "bottom" @@ -392,16 +403,32 @@ def plot_labelbox( pos = (bbox.xmax, bbox.ymax) valign = "top" halign = "right" + else: + raise ValueError( + "position must be 'topleft', 'topright', 'bottomleft' or 'bottomright', " + f"got {position!r}" + ) - smb.plot_text( - pos, - text, - color=textcolor, - verticalalignment=valign, - horizontalalignment=halign, - bbox=dict(facecolor=labelcolor, linewidth=0, edgecolor=None), + # the text options: the defaults, then the shorthands, then text_style, with + # short option names such as ``size`` and ``ha`` converted to the full names + style = mpl_styling( + None, + dict(verticalalignment=valign, horizontalalignment=halign, color=textcolor), + text_style, + artist=Text, + ) + + # the background: the box edge color, then labelcolor, then text_style + background = labelcolor + if background is None: + background = rect.get_edgecolor() + background = style.pop("backgroundcolor", background) + style["bbox"] = dict(facecolor=background, linewidth=0, edgecolor=None) | style.get( + "bbox", {} ) + smb.plot_text(pos, text, **style) + return rect diff --git a/tests/test_image_blobs.py b/tests/test_image_blobs.py index 1b0a08bd..4bb2bbf3 100644 --- a/tests/test_image_blobs.py +++ b/tests/test_image_blobs.py @@ -741,6 +741,106 @@ def test_box_with_a_marker_in_the_format_string_says_so(self): with self.assertRaisesRegex(ValueError, "cannot draw"): self._box_patch(method, fmt) + def _labelbox(self, *args, **kwargs): + """Draw one labelled box; return (box patch, label text).""" + fig, ax = self._fresh_ax() + self.blobs1.plot_labelbox(*args, **kwargs) + patch, text = ax.patches[0], ax.texts[0] + plt.close(fig) + return patch, text + + @staticmethod + def _hex(color): + return mcolors.to_hex(color) + + def test_labelbox_default_label_background_is_the_box_edge_color(self): + patch, text = self._labelbox() + self.assertEqual(self._hex(text.get_bbox_patch().get_facecolor()), "#ffff00") + self.assertEqual(self._hex(text.get_color()), "#000000") + + def test_labelbox_label_background_follows_however_the_edge_was_set(self): + # was: only the color option was followed, so ec= left a yellow label + for args, kwargs in [ + ((), dict(color="red")), + ((), dict(edgecolor="red")), + ((), dict(ec="red")), + (("r--",), {}), + ]: + with self.subTest(args=args, kwargs=kwargs): + patch, text = self._labelbox(*args, **kwargs) + self.assertEqual(self._hex(patch.get_edgecolor()), "#ff0000") + self.assertEqual( + self._hex(text.get_bbox_patch().get_facecolor()), "#ff0000" + ) + + def test_labelbox_shorthands(self): + patch, text = self._labelbox(textcolor="white", labelcolor="blue") + self.assertEqual(self._hex(text.get_color()), "#ffffff") + self.assertEqual(self._hex(text.get_bbox_patch().get_facecolor()), "#0000ff") + self.assertEqual(self._hex(patch.get_edgecolor()), "#ffff00") # box unchanged + + def test_labelbox_text_style(self): + patch, text = self._labelbox( + text_style=dict(color="white", fontsize=17, fontweight="bold") + ) + self.assertEqual(self._hex(text.get_color()), "#ffffff") + self.assertEqual(text.get_fontsize(), 17) + self.assertEqual(text.get_fontweight(), "bold") + self.assertEqual(self._hex(patch.get_edgecolor()), "#ffff00") # box unchanged + + def test_labelbox_text_style_accepts_short_names(self): + # size and c are aliases of fontsize and color + patch, text = self._labelbox(text_style=dict(size=15, c="red", weight="bold")) + self.assertEqual(text.get_fontsize(), 15) + self.assertEqual(self._hex(text.get_color()), "#ff0000") + self.assertEqual(text.get_fontweight(), "bold") + + def test_labelbox_text_style_wins_over_the_shorthands(self): + patch, text = self._labelbox( + textcolor="white", + labelcolor="blue", + text_style=dict(color="red", backgroundcolor="green"), + ) + self.assertEqual(self._hex(text.get_color()), "#ff0000") + self.assertEqual(self._hex(text.get_bbox_patch().get_facecolor()), "#008000") + + def test_labelbox_bbox_in_text_style_is_merged_over_the_default(self): + patch, text = self._labelbox( + labelcolor="blue", text_style=dict(bbox=dict(linewidth=2, edgecolor="k")) + ) + bbox = text.get_bbox_patch() + self.assertEqual(self._hex(bbox.get_facecolor()), "#0000ff") # kept + self.assertEqual(bbox.get_linewidth(), 2) + self.assertEqual(self._hex(bbox.get_edgecolor()), "#000000") + # and a facecolor in bbox is the most specific of all + patch, text = self._labelbox( + labelcolor="blue", text_style=dict(bbox=dict(facecolor="red")) + ) + self.assertEqual(self._hex(text.get_bbox_patch().get_facecolor()), "#ff0000") + + def test_labelbox_position(self): + positions = {} + for position in ("topleft", "topright", "bottomleft", "bottomright"): + patch, text = self._labelbox(position=position) + positions[position] = (text.get_ha(), text.get_va()) + self.assertEqual(positions["topleft"], ("left", "bottom")) + self.assertEqual(positions["topright"], ("right", "bottom")) + self.assertEqual(positions["bottomleft"], ("left", "top")) + self.assertEqual(positions["bottomright"], ("right", "top")) + + def test_labelbox_bad_position(self): + with self.assertRaisesRegex(ValueError, "position must be"): + self._labelbox(position="middle") + + def test_labelbox_text_style_is_not_changed_by_drawing(self): + style = dict(size=15, c="red") + self._labelbox(text_style=style) + self.assertEqual(style, dict(size=15, c="red")) + + def test_labelbox_label_text(self): + patch, text = self._labelbox(label="shark {:d}") + self.assertTrue(text.get_text().startswith("shark ")) + def test_plot_labelbox_ratio(self): self._test_plot_ratio("plot_labelbox", self._patches)