kwplot.mpl_draw module

Note, this module should be refactored into MPL figure drawings and cv2 on-image drawings.

kwplot.mpl_draw.draw_boxes(boxes, alpha=None, color='blue', labels=None, centers=False, fill=False, ax=None, lw=2)[source]
Parameters
  • boxes (kwimage.Boxes)

  • labels (List[str]) – of labels

  • alpha (List[float]) – alpha for each box

  • centers (bool) – draw centers or not

  • lw (float) – linewidth

Example

>>> import kwimage
>>> bboxes = kwimage.Boxes([[.1, .1, .6, .3], [.3, .5, .5, .6]], 'xywh')
>>> draw_boxes(bboxes)
>>> #kwplot.autompl()
kwplot.mpl_draw.draw_line_segments(pts1, pts2, ax=None, **kwargs)[source]

draws N line segments between N pairs of points

Parameters
  • pts1 (ndarray) – Nx2

  • pts2 (ndarray) – Nx2

  • ax (None) – (default = None)

  • **kwargs – lw, alpha, colors

Example

>>> import numpy as np
>>> import kwplot
>>> pts1 = np.array([(.1, .8), (.6, .8)])
>>> pts2 = np.array([(.6, .7), (.4, .1)])
>>> kwplot.figure(fnum=None)
>>> draw_line_segments(pts1, pts2)
>>> # xdoc: +REQUIRES(--show)
>>> import matplotlib.pyplot as plt
>>> ax = plt.gca()
>>> ax.set_xlim(0, 1)
>>> ax.set_ylim(0, 1)
>>> kwplot.show_if_requested()
kwplot.mpl_draw.plot_matrix(matrix, index=None, columns=None, rot=90, ax=None, grid=True, label=None, zerodiag=False, cmap='viridis', showvals=False, showzero=True, logscale=False, xlabel=None, ylabel=None, fnum=None, pnum=None)[source]

Helper for plotting confusion matrices

Parameters

matrix (ndarray | pd.DataFrame) – if a data frame then index, columns, xlabel, and ylabel will be defaulted to sensible values.

Todo

  • [ ] Finish args docs

  • [ ] Replace internals with seaborn

Example

>>> # xdoctest: +REQUIRES(module:pandas)
>>> from kwplot.mpl_draw import *  # NOQA
>>> import pandas as pd
>>> classes = ['cls1', 'cls2', 'cls3']
>>> matrix = np.array([[2, 2, 1], [3, 1, 0], [1, 0, 0]])
>>> matrix = pd.DataFrame(matrix, index=classes, columns=classes)
>>> matrix.index.name = 'real'
>>> matrix.columns.name = 'pred'
>>> plot_matrix(matrix, showvals=True)
>>> # xdoc: +REQUIRES(--show)
>>> import matplotlib.pyplot as plt
>>> import kwplot
>>> kwplot.autompl()
>>> plot_matrix(matrix, showvals=True)

Example

>>> # xdoctest: +REQUIRES(module:pandas)
>>> from kwplot.mpl_draw import *  # NOQA
>>> matrix = np.array([[2, 2, 1], [3, 1, 0], [1, 0, 0]])
>>> plot_matrix(matrix)
>>> # xdoc: +REQUIRES(--show)
>>> import matplotlib.pyplot as plt
>>> import kwplot
>>> kwplot.autompl()
>>> plot_matrix(matrix)

Example

>>> # xdoctest: +REQUIRES(module:pandas)
>>> from kwplot.mpl_draw import *  # NOQA
>>> matrix = np.array([[2, 2, 1], [3, 1, 0], [1, 0, 0]])
>>> classes = ['cls1', 'cls2', 'cls3']
>>> plot_matrix(matrix, index=classes, columns=classes)
kwplot.mpl_draw.draw_points(xy, color='blue', class_idxs=None, classes=None, ax=None, alpha=None, radius=1, **kwargs)[source]
Parameters

xy (ndarray) – of points.

Example

>>> from kwplot.mpl_draw import *  # NOQA
>>> import kwimage
>>> xy = kwimage.Points.random(10).xy
>>> draw_points(xy, radius=0.01)
>>> draw_points(xy, class_idxs=np.random.randint(0, 3, 10),
>>>         radius=0.01, classes=['a', 'b', 'c'], color='classes')
kwplot.mpl_draw.draw_text_on_image(img, text, org=None, return_info=False, **kwargs)[source]

Draws multiline text on an image using opencv

Parameters
  • img (ndarray | None | dict) – Generally a numpy image to draw on (inplace). Otherwise a canvas will be constructed such that the text will fit. The user may specify a dictionary with keys width and height to have more control over the constructed canvas.

  • text (str) – text to draw

  • org (Tuple[int, int]) – The x, y location of the text string “anchor” in the image as specified by halign and valign. For instance, If valign=’bottom’, halign=’left’, this is the bottom left corner.

  • return_info (bool, default=False) – if True, also returns information about the positions the text was drawn on.

  • **kwargs – color (tuple): default blue thickness (int): defaults to 2 fontFace (int): defaults to cv2.FONT_HERSHEY_SIMPLEX fontScale (float): defaults to 1.0 valign (str, default=’bottom’):

    either top, center, or bottom. NOTE: this default may change to “top” in the future.

    halign (str, default=’left’):

    either left, center, or right

    border (dict | int):

    If specified as an integer, draws a black border with that given thickness. If specified as a dictionary, draws a border with color specified parameters.

    “color”: border color, defaults to “black”. “thickness”: border thickness, defaults to 1.

Returns

the image that was drawn on

Return type

ndarray

Note

The image is modified inplace. If the image is non-contiguous then this returns a UMat instead of a ndarray, so be carefull with that.

References

https://stackoverflow.com/questions/27647424/ https://stackoverflow.com/questions/51285616/opencvs-gettextsize-and-puttext-return-wrong-size-and-chop-letters-with-low

Example

>>> import kwimage
>>> img = kwimage.grab_test_image(space='rgb')
>>> img2 = kwimage.draw_text_on_image(img.copy(), 'FOOBAR', org=(0, 0), valign='top')
>>> assert img2.shape == img.shape
>>> assert np.any(img2 != img)
>>> # xdoc: +REQUIRES(--show)
>>> import kwplot
>>> kwplot.autompl()
>>> kwplot.imshow(img2)
>>> kwplot.show_if_requested()

Example

>>> import kwimage
>>> # Test valign
>>> img = kwimage.grab_test_image(space='rgb', dsize=(500, 500))
>>> img2 = kwimage.draw_text_on_image(img, 'FOOBAR\nbazbiz\nspam', org=(0, 0), valign='top', border=2)
>>> img2 = kwimage.draw_text_on_image(img, 'FOOBAR\nbazbiz\nspam', org=(150, 0), valign='center', border=2)
>>> img2 = kwimage.draw_text_on_image(img, 'FOOBAR\nbazbiz\nspam', org=(300, 0), valign='bottom', border=2)
>>> # Test halign
>>> img2 = kwimage.draw_text_on_image(img, 'FOOBAR\nbazbiz\nspam', org=(250, 100), halign='right', border=2)
>>> img2 = kwimage.draw_text_on_image(img, 'FOOBAR\nbazbiz\nspam', org=(250, 250), halign='center', border=2)
>>> img2 = kwimage.draw_text_on_image(img, 'FOOBAR\nbazbiz\nspam', org=(250, 400), halign='left', border=2)
>>> # xdoc: +REQUIRES(--show)
>>> import kwplot
>>> kwplot.autompl()
>>> kwplot.imshow(img2)
>>> kwplot.show_if_requested()

Example

>>> # Ensure the function works with float01 or uint255 images
>>> import kwimage
>>> img = kwimage.grab_test_image(space='rgb')
>>> img = kwimage.ensure_float01(img)
>>> img2 = kwimage.draw_text_on_image(img, 'FOOBAR\nbazbiz\nspam', org=(0, 0), valign='top', border=2)

Example

>>> # Test dictionary border
>>> import kwimage
>>> img = kwimage.draw_text_on_image(None, 'hello\neveryone', org=(100, 100), valign='top', halign='center', border={'color': 'green', 'thickness': 9})
>>> #img = kwimage.draw_text_on_image(None, 'hello\neveryone', org=(0, 0), valign='top')
>>> #img = kwimage.draw_text_on_image(None, 'hello', org=(0, 60), valign='top', halign='center', border=0)
>>> # xdoc: +REQUIRES(--show)
>>> import kwplot
>>> kwplot.autompl()
>>> kwplot.imshow(img)
>>> kwplot.show_if_requested()

Example

>>> # Test dictionary image
>>> import kwimage
>>> img = kwimage.draw_text_on_image({'width': 300}, 'good\nPropogate', org=(150, 0), valign='top', halign='center', border={'color': 'green', 'thickness': 0})
>>> print('img.shape = {!r}'.format(img.shape))
>>> # xdoc: +REQUIRES(--show)
>>> import kwplot
>>> kwplot.autompl()
>>> kwplot.imshow(img)
>>> kwplot.show_if_requested()

Example

>>> import ubelt as ub
>>> import kwimage
>>> grid = list(ub.named_product({
>>>     'halign': ['left', 'center', 'right', None],
>>>     'valign': ['top', 'center', 'bottom', None],
>>>     'border': [0, 3]
>>> }))
>>> canvases = []
>>> text = 'small-line\na-much-much-much-bigger-line\nanother-small\n.'
>>> for kw in grid:
>>>     header = kwimage.draw_text_on_image({}, ub.repr2(kw, compact=1), color='blue')
>>>     canvas = kwimage.draw_text_on_image({'color': 'white'}, text, org=None, **kw)
>>>     canvases.append(kwimage.stack_images([header, canvas], axis=0, bg_value=(255, 255, 255), pad=5))
>>> # xdoc: +REQUIRES(--show)
>>> canvas = kwimage.stack_images_grid(canvases, pad=10, bg_value=(255, 255, 255))
>>> import kwplot
>>> kwplot.autompl()
>>> kwplot.imshow(canvas)
>>> kwplot.show_if_requested()
kwplot.mpl_draw.draw_boxes_on_image(img, boxes, color='blue', thickness=1, box_format=None, colorspace='rgb')[source]

Draws boxes on an image.

Parameters
  • img (ndarray) – image to copy and draw on

  • boxes (nh.util.Boxes) – boxes to draw

  • colorspace (str) – string code of the input image colorspace

Example

>>> import kwimage
>>> import numpy as np
>>> img = np.zeros((10, 10, 3), dtype=np.uint8)
>>> color = 'dodgerblue'
>>> thickness = 1
>>> boxes = kwimage.Boxes([[1, 1, 8, 8]], 'ltrb')
>>> img2 = draw_boxes_on_image(img, boxes, color, thickness)
>>> assert tuple(img2[1, 1]) == (30, 144, 255)
>>> # xdoc: +REQUIRES(--show)
>>> import kwplot
>>> kwplot.autompl()  # xdoc: +SKIP
>>> kwplot.figure(doclf=True, fnum=1)
>>> kwplot.imshow(img2)
kwplot.mpl_draw.draw_clf_on_image(im, classes, tcx=None, probs=None, pcx=None, border=1)[source]

Draws classification label on an image.

Works best with image chips sized between 200x200 and 500x500

Parameters
  • im (ndarray) – the image

  • classes (Sequence | CategoryTree) – list of class names

  • tcx (int, default=None) – true class index if known

  • probs (ndarray) – predicted class probs for each class

  • pcx (int, default=None) – predicted class index. (if None but probs is specified uses argmax of probs)

Example

>>> # xdoctest: +REQUIRES(module:torch)
>>> import torch
>>> import kwarray
>>> import kwimage
>>> rng = kwarray.ensure_rng(0)
>>> im = (rng.rand(300, 300) * 255).astype(np.uint8)
>>> classes = ['cls_a', 'cls_b', 'cls_c']
>>> tcx = 1
>>> probs = rng.rand(len(classes))
>>> probs[tcx] = 0
>>> probs = torch.FloatTensor(probs).softmax(dim=0).numpy()
>>> im1_ = kwimage.draw_clf_on_image(im, classes, tcx, probs)
>>> probs[tcx] = .9
>>> probs = torch.FloatTensor(probs).softmax(dim=0).numpy()
>>> im2_ = kwimage.draw_clf_on_image(im, classes, tcx, probs)
>>> # xdoctest: +REQUIRES(--show)
>>> import kwplot
>>> kwplot.autompl()
>>> kwplot.imshow(im1_, colorspace='rgb', pnum=(1, 2, 1), fnum=1, doclf=True)
>>> kwplot.imshow(im2_, colorspace='rgb', pnum=(1, 2, 2), fnum=1)
>>> kwplot.show_if_requested()