Graphics operations#

Draw graphical primitives into an image stored in an array. The functions draw_xxx perform a similar operation to the functions plot_xxx from the Spatial Math Toolbox. However the draw_xxx render the graphical primitive into the image pixel array, whereas the plot_xxx use Matplotlib to render the graphical primitive in a figure window.

Drawing primitives (boxes, circles, text) and color lookup onto OpenCV images.

draw_box(image: ndarray, l: int | None = None, r: int | None = None, t: int | None = None, b: int | None = None, w: int | None = None, h: int | None = None, lb: tuple[int, int] | list[int] | ndarray | None = None, lt: tuple[int, int] | list[int] | ndarray | None = None, rb: tuple[int, int] | list[int] | ndarray | None = None, rt: tuple[int, int] | list[int] | ndarray | None = None, wh: int | tuple[int, int] | list[int] | ndarray | None = None, centre: tuple[int, int] | list[int] | ndarray | None = None, center: tuple[int, int] | list[int] | ndarray | None = None, lbrt: tuple[int, int, int, int] | list[int] | ndarray | None = None, lrbt: tuple[int, int, int, int] | list[int] | ndarray | None = None, ltrb: tuple[int, int, int, int] | list[int] | ndarray | None = None, lbwh: tuple[int, int, int, int] | list[int] | ndarray | None = None, ax: Any = None, color: Any = None, thickness: int = 1, antialias: bool = False) → tuple[tuple[int, int], tuple[int, int]][source][source]#

Draw a box in an image

Parameters:
  • image (ndarray(H,W), ndarray(H,W,P)) – image to draw into, greyscale or color

  • l (int, optional) – left side coordinate

  • r (int, optional) – right side coordinate

  • t (int, optional) – top side coordinate

  • b (int, optional) – bottom side coordinate

  • w (int, optional) – box width

  • h (int, optional) – box height

  • lb (array_like(2), optional) – left-bottom corner [u,v]

  • lt (array_like(2), optional) – left-top corner [u,v]

  • rb (array_like(2), optional) – right-bottom corner (u,v)

  • rt (array_like(2), optional) – right-top corner (u,v)

  • wh (array_like(2), optional) – width and height

  • centre (array_like(2), optional) – box centre (u,v)

  • lbrt (array_like(4), optional) – left-bottom-right-top [xmin, ymin, xmax, ymax]

  • lrbt (array_like(4), optional) – left-right-bottom-top [xmin, ymin, xmax, ymax]

  • ltrb (array_like(4), optional) – bounding box [xmin, ymin, xmax, ymax]

  • lbwh (array_like(4), optional) – left-bottom-width-height [xmin, ymin, width, height]

  • color (scalar or array_like) – color of line

  • thickness (int, optional) – line thickness, -1 to fill, defaults to 1

  • antialias (bool, optional) – use antialiasing, defaults to False

  • ax – axes to draw into

Type:

Matplotlib axes

Returns:

bottom-left and top-right corners of the box

Return type:

(2-tuple, 2-tuple)

Draws a box into the specified image using OpenCV. The input image is modified.

The box can be specified in many ways, any combination of inputs is allowed so long as the box is fully specified:

  • bounding box [xmin, xmax; ymin, ymax]

  • left-top-right-bottom [xmin, ymin, xmax, ymax]

  • left side

  • right side

  • top side

  • bottom side

  • centre and width+height

  • left-bottom and right-top corners

  • left-bottom corner and width+height

  • right-top corner and width+height

  • left-top corner and width+height

where left-bottom is (xmin, ymin), left-top is (xmax, ymax)

Examples

from machinevisiontoolbox import draw_box, idisp
import numpy as np
img = np.zeros((1000, 1000), dtype='uint8')
draw_box(img, lbrt=[100, 300, 700, 500], thickness=2, color=200) # outline box
draw_box(img, lbwh=[300, 400, 500, 400], thickness=-1, color=250) # filled box
idisp(img)

(Source code, png, hires.png, pdf)

_images/graphics-1.png

Warning

For images y increases downwards so top of the box, has a larger v-coordinate, and is lower in the image.

Note

If image has multiple planes then color should have the same number of elements as the image has planes. If it is a scalar that value is used for each color plane. For a color image color can be a string color name.

Warning

The image is drawn into in place, and image must be C-contiguous which OpenCV requires, otherwise a ValueError is raised.

See also

plot_box opencv.rectangle

draw_circle(image: ndarray, centre: tuple[float, float] | list[float] | ndarray, radius: int, color: Any, thickness: int = 1, antialias: bool = False, center: tuple[float, float] | list[float] | ndarray | None = None) → ndarray[source][source]#

Draw line in image

Parameters:
  • image (ndarray(H,W), ndarray(H,W,P)) – image to draw into, greyscale or color

  • centre – centre coordinate

  • radius – radius in pixels

  • color (scalar, array_like(3)) – color of circle

  • thickness (int, optional) – width of line in pixels, -1 to fill, defaults to 1

  • antialias (bool, optional) – use antialiasing, defaults to False

Raises:

TypeError – can’t draw color into a greyscale image

Returns:

passed image as modified

Return type:

ndarray(H,W), ndarray(H,W,P)

The centre coordinate can be a tuple, list or NumPy array. The values are rounded to the nearest integer. The radius is also rounded to the nearest integer.

Examples

from machinevisiontoolbox import draw_circle, idisp
import numpy as np
img = np.zeros((1000, 1000), dtype='uint8')
draw_circle(img, (300,400), 150, thickness=2, color=200)
draw_circle(img, (500,700), 250, thickness=-1, color=50)  # filled
draw_circle(img, (900,900), 200, thickness=-1, color=100)  # filled
idisp(img)

(Source code, png, hires.png, pdf)

_images/graphics-2.png

Note

If image has multiple planes then color should have the same number of elements as the image has planes. If it is a scalar that value is used for each color plane. For a color image color can be a string color name.

Warning

The image is drawn into in place, and image must be C-contiguous which OpenCV requires, otherwise a ValueError is raised.

draw_labelbox(image: ndarray, text: str, textcolor: Any = None, labelcolor: Any = None, font: str = 'simplex', fontsize: float = 0.9, fontheight: int | None = None, fontthickness: int = 2, position: str = 'topleft', **boxargs: Any) → ndarray[source][source]#

Draw a labelled box in an image

Parameters:
  • image (ndarray(H,W), ndarray(H,W,P)) – image to draw into

  • text (str) – text label

  • textcolor (str, array_like(3), optional) – text color, defaults to black

  • labelcolor (str, array_like(3), optional) – label background color

  • position – place to draw the label: ‘topleft’ (default), ‘topright, ‘bottomleft’ or ‘bottomright’

  • font (str, optional) – OpenCV font, defaults to cv2.FONT_HERSHEY_SIMPLEX

  • fontsize (float, optional) – OpenCV font scale, defaults to 0.3

  • fontheight (int, optional) – OpenCV font height in pixels, overrides fontsize if given

  • fontthickness (int, optional) – font thickness in pixels, defaults to 2

  • boxargs – arguments passed to draw_box

Raises:

TypeError – can’t draw color into a greyscale image

Returns:

passed image as modified

Return type:

ndarray(H,W), ndarray(H,W,P)

The position of the box is specified using the same arguments as for draw_box. The label font is specified using the same arguments as for draw_text. If labelcolor is specified it is used as the background color for the text label, otherwise the box color is used.

Examples

from machinevisiontoolbox import draw_labelbox, idisp
import numpy as np
img = np.zeros((500, 500))
draw_labelbox(img, "labelled box", lbwh=[100, 200, 400, 500], textcolor=0, labelcolor=100, color=200, thickness=2, fontsize=1)
draw_labelbox(img, "another labelled box", position="bottomright", lbwh=[300, 450, 500, 400], textcolor=0, labelcolor=100, color=200, thickness=2, fontsize=1)
idisp(img)

(Source code, png, hires.png, pdf)

_images/graphics-3.png

Note

If image has multiple planes then color, labelcolor and textcolor should have the same number of elements as the image has planes. If they are a scalar that value is used for each color plane. For a color image color can be a string color name.

Warning

The image is drawn into in place, and image must be C-contiguous which OpenCV requires, otherwise a ValueError is raised.

See also

draw_box, draw_text

draw_line(image: ndarray, start: tuple[float, float] | list[float] | ndarray, end: tuple[float, float] | list[float] | ndarray, color: Any, thickness: int = 1, antialias: bool = False) → ndarray[source][source]#

Draw line in image

Parameters:
  • image (ndarray(H,W), ndarray(H,W,P)) – image to draw into, greyscale or color

  • start (array_like(2) int) – start coordinate (u,v)

  • end (array_like(2) int) – end coordinate (u,v)

  • color (scalar, array_like(3)) – color of line

  • thickness (int, optional) – width of line in pixels, defaults to 1

  • antialias (bool, optional) – use antialiasing, defaults to False

Raises:

TypeError – can’t draw color into a greyscale image

Returns:

passed image as modified

Return type:

ndarray(H,W), ndarray(H,W,P)

The coordinates can be tuples, lists or NumPy arrays. The values are rounded to the nearest integer.

Examples

from machinevisiontoolbox import draw_line, idisp
import numpy as np
img = np.zeros((1000, 1000), dtype='uint8')
draw_line(img, (100, 300), (700, 900), color=200, thickness=10)
idisp(img)

(Source code, png, hires.png, pdf)

_images/graphics-4.png

Note

If image has multiple planes then color should have the same number of elements as the image has planes. If it is a scalar that value is used for each color plane. For a color image color can be a string color name.

Warning

The image is drawn into in place, and image must be C-contiguous which OpenCV requires, otherwise a ValueError is raised.

See also

plot_line opencv.line

draw_point(image: ndarray, pos: tuple[float, float] | list[float] | list[tuple[float, float]] | ndarray, marker: str = '+', text: Iterable[str] | str | None = None, color: Any = None, font: str = 'simplex', fontheight: int | None = None, fontsize: float = 0.3, fontthickness: int = 2) → ndarray[source][source]#

Draw a marker in image

Parameters:
  • image (ndarray(H,W), ndarray(H,W,P)) – image to draw into, greyscale or color

  • pos (array_like(2), ndarray(2,n), list of 2-tuples) – position of marker

  • marker (str, optional) – marker character, defaults to ‘+’

  • text (str, optional) – text label, defaults to None

  • color (str or array_like(3), optional) – text color, defaults to None

  • font (str, optional) – OpenCV font, defaults to cv2.FONT_HERSHEY_SIMPLEX

  • fontheight (int, optional) – height of font in pixels, defaults to None

  • fontsize (float, optional) – OpenCV font scale, defaults to 0.3

  • fontthickness (int, optional) – font thickness in pixels, defaults to 2

Raises:
  • TypeError – can’t draw color into a greyscale image

  • ValueError – if the marker string has more than one color letter, has no marker character, or no color is given by color or by a letter

Returns:

passed image as modified

Return type:

ndarray(H,W), ndarray(H,W,P)

Changed in version 2.5.0: These cases raise ValueError with a message; they raised TypeError or ValueError from deeper in the code.

The text label is placed to the right of the marker, and vertically centred. The color of the marker can be different to the color of the text, the marker color is specified by a single letter in the marker string, eg. ‘b+’.

Multiple points can be marked if pos is a \(2 \times n\) array or a list of coordinate pairs. In this case:

  • if text is a string it is processed with text.format(i) where i is the point index (starting at zero). “{0}” within text will be substituted by the point index.

  • if text is a list, its elements are used to label the points

The font is specified by a string which selects a Hershey vector (stroke) font.

Font name

OpenCV font name

"simplex"

Hershey Roman simplex

"plain"

Hershey Roman plain

"duplex"

Hershey Roman duplex (double stroke)

"complex"

Hershey Roman complex

"triplex"

Hershey Romantriplex

"complex-small"

Hershey Roman complex (small)

"script-simplex"

Hershey script

"script-complex"

Hershey script complex

"italic"

Hershey italic

Note

Font size can be specified in two ways:

  • fontsize is the OpenCV font size scale factor as used by opencv.putText

  • fontheight is the height of the font in pixels, this overrides fontsize. The font scale is computed from fontheight using opencv.getFontScaleFromHeight

Note

The centroid of the marker character is very accurately positioned at the specified coordinate. The text label is placed to the right of the marker.

Note

If image has multiple planes then color should have the same number of elements as the image has planes. If it is a scalar that value is used for each color plane. For a color image color can be a string color name.

Examples

from machinevisiontoolbox import draw_point, idisp
import numpy as np
img = np.zeros((1000, 1000), dtype='uint8')
draw_point(img, (100, 300), '*', fontsize=1, color=200)
draw_point(img, (500, 300), '*', 'labelled point', fontsize=1, color=200)
draw_point(img, np.random.randint(1000, size=(2,10)), '+', 'point {0}', color=100, fontsize=0.8)
idisp(img)

(Source code, png, hires.png, pdf)

_images/graphics-5.png

Warning

The image is drawn into in place, and image must be C-contiguous which OpenCV requires, otherwise a ValueError is raised.

draw_text(image: ndarray, pos: tuple[int, int] | list[int] | ndarray, text: str | None = None, color: Any = None, font: str = 'simplex', fontheight: int | None = None, fontsize: float = 0.3, fontthickness: int = 2, antialias: bool = False) → ndarray[source][source]#

Draw text in image

Parameters:
  • image (ndarray(H,W), ndarray(H,W,P)) – image to draw into, greyscale or color

  • pos (array_like(2)) – position of text (u,v)

  • text (str) – text

  • color (scalar, array_like(3), str) – color of text

  • font (str, optional) – font name, defaults to “simplex”

  • fontheight (int, optional) – height of font in pixels, defaults to None

  • fontsize (float, optional) – OpenCV font scale, defaults to 0.3

  • fontthickness (int, optional) – font thickness in pixels, defaults to 2

  • antialias (bool, optional) – use antialiasing, defaults to False

Returns:

passed image as modified

Return type:

ndarray(H,W), ndarray(H,W,P)

The position corresponds to the bottom-left corner of the text box as seen in the image. The font is specified by a string which selects a Hershey vector (stroke) font.

Font name

OpenCV font name

'simplex'

Hershey Roman simplex

'plain'

Hershey Roman plain

'duplex'

Hershey Roman duplex (double stroke)

'complex'

Hershey Roman complex

'triplex'

Hershey Romantriplex

'complex-small'

Hershey Roman complex (small)

'script-simplex'

Hershey script

'script-complex'

Hershey script complex

'italic'

Hershey italic

Examples

from machinevisiontoolbox import draw_text, idisp
import numpy as np
img = np.zeros((1000, 1000), dtype='uint8')
draw_text(img, (100, 150), 'Hello world!', color=200, fontheight=60)
idisp(img)

(Source code, png, hires.png, pdf)

_images/graphics-6.png

Note

Font size can be specified in two ways:

  • fontsize is the OpenCV font size scale factor as used by opencv.putText

  • fontheight is the height of the font in pixels, this overrides fontsize. The font scale is computed from fontheight using opencv.getFontScaleFromHeight

Note

If image has multiple planes then color should have the same number of elements as the image has planes. If it is a scalar that value is used for each color plane. For a color image color can be a string color name.

Warning

The image is drawn into in place, and image must be C-contiguous which OpenCV requires, otherwise a ValueError is raised.

mpl_styling(fmt: str | tuple[str] | None = None, defaults: dict | None = None, kwargs: dict | None = None, artist: type[Artist] | None = None) → dict[str, Any][source][source]#

Merge Matplotlib style options

Parameters:
  • fmt (str or tuple[str], optional) – a format string, defaults to None

  • defaults (dict, optional) – a dictionary of default keyword arguments , defaults to None

  • kwargs (dict, optional) – a dictionary of keyword arguments , defaults to None

  • artist (type[Artist], optional) – the Matplotlib class that the options will be passed to, such as Line2D, Patch or Text, defaults to None

Changed in version 2.5.0: Added artist.

Matplotlib has two distinct ways of specifying styling for plots:

  1. A format string, which is a compact way of specifying color, marker and linestyle, eg. ‘ro–’ for red circles with dashed lines.

  2. Keyword arguments, which can specify a wide range of styling options, eg. color=’red’, marker=’o’, linestyle=’–‘.

The format string strictly specifies only color, marker and linestyle, and is a convenient way to specify these three options in a compact form. The keyword arguments are more verbose and flexible, and can specify any styling option, including color, marker and linestyle, but also many others such as linewidth, markersize, etc.

These two styles reflects the shift from “quick-and-dirty” plotting (as in original MATLAB) to modern, robust software engineering.

This function returns a dict of keyword arguments that merges the format string fmt, the default keyword arguments defaults and the user-specified keyword 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 detailed styling through keyword arguments with decent defaults.

def function(*fmt, ..., **kwargs):
    options = mpl_styling(fmt, defaults={color='red', marker='o'}, kwargs=kwargs)
     .
     .
    plt.plot(x, y, **options)
parse_fmt(fmt: str | tuple[str, ...] | list[str] | None) → dict[str, str][source][source]#

Parse a MATLAB-style format string into Matplotlib options

Parameters:

fmt (str, tuple or list of str, or None) – a format string such as "r--", "ko" or "C2:", or a tuple or list whose first element is one, or None

Raises:

ValueError – if the string is not a valid format string

Returns:

the options the string sets, as color, marker and linestyle keys

Return type:

dict

The string is a color, a marker and a line style in any order, and each is optional:

  • color: one of b g r c m y k w, a cycle color such as C0, or the whole string can be any Matplotlib color, such as "red", "0.5" or "#ff8000"

  • marker: one of . , o v ^ < > 1 2 3 4 8 s p P * h H + x X D d | _

  • line style: one of -, --, -. or :

The result holds only what the string sets, so it can be merged over a dict of defaults without wiping them out:

>>> parse_fmt("r--")
{'color': 'r', 'linestyle': '--'}
>>> parse_fmt("--")
{'linestyle': '--'}
>>> parse_fmt("")
{}

As in Matplotlib, a marker with no line style means markers only, so linestyle is "None":

>>> parse_fmt("go")
{'color': 'g', 'marker': 'o', 'linestyle': 'None'}

This is the same parsing that plot applies to its fmt argument, except that a color, marker or line style that is not in the string is left out, and is not set to a default.

Note

The characters accepted are the same as those of plot, but not the unusual ones: a space, "None", or the numbers that Matplotlib accepts as markers.

plot_labelbox(text: str, fmt: str | None = None, textcolor: Any = None, labelcolor: Any = None, position: str = 'topleft', text_style: dict[str, Any] | None = None, **boxargs: Any) → Rectangle[source][source]#

Plot a labelled box using Matplotlib

Parameters:
  • text (str) – text label

  • fmt (str, optional) – format string for the simply specifying the box edge style, eg. "y--" for a dashed yellow box

  • textcolor (str, array_like(3), optional) – text color, defaults to the Matplotlib default, black

  • labelcolor (str, array_like(3), optional) – label background color, defaults to the edge color of the box

  • position (str, optional) – place to draw the label: ‘topleft’ (default), ‘topright, ‘bottomleft’ or ‘bottomright’

  • text_style – Matplotlib text options for the label, such as dict(fontsize=12, fontweight="bold"), defaults to None

  • boxargs – arguments passed to 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 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.

Changed in version 2.5.0: Added text_style, and the label background now follows the edge color of the box, not only the color option.

Examples

from machinevisiontoolbox import plot_labelbox
import numpy as np
img = np.zeros((1000, 1000), dtype='uint8')
idisp(img) # create a Matplotlib window
plot_labelbox("labelled box", lbwh=[100, 250, 300, 400], color="yellow")
plot_labelbox('another labelled box', position="bottomright", lbwh=[300, 450, 500, 400], color="red")

(Source code, png, hires.png, pdf)

_images/graphics-7.png

See also

plot_box, plot_text