wbia.plottool package

Subpackages

Submodules

wbia.plottool.__MPL_INIT__ module

Notes

To use various backends certian packages are required

PyQt …

Tk pip install sudo apt-get install tk sudo apt-get install tk-dev

Wx pip install wxPython

GTK pip install PyGTK pip install pygobject pip install pygobject

Cairo pip install pycairo pip install py2cairo pip install cairocffi sudo apt-get install libcairo2-dev

CommandLine:

python -m wbia.plottool.draw_func2 –exec-imshow –show –mplbe=GTKAgg python -m wbia.plottool.draw_func2 –exec-imshow –show –mplbe=TkAgg python -m wbia.plottool.draw_func2 –exec-imshow –show –mplbe=WxAgg python -m wbia.plottool.draw_func2 –exec-imshow –show –mplbe=WebAgg python -m wbia.plottool.draw_func2 –exec-imshow –show –mplbe=gdk python -m wbia.plottool.draw_func2 –exec-imshow –show –mplbe=cairo

wbia.plottool.__MPL_INIT__.get_pyqt()[source]
wbia.plottool.__MPL_INIT__.get_target_backend()[source]
wbia.plottool.__MPL_INIT__.init_matplotlib(verbose=False)[source]
wbia.plottool.__MPL_INIT__.print_all_backends()[source]
wbia.plottool.__MPL_INIT__.profile(func)[source]

wbia.plottool.__main__ module

wbia.plottool.__main__.plottool_main()[source]

wbia.plottool._cv2_impaint module

wbia.plottool._cv2_impaint.cached_impaint(bgr_img, cached_mask_fpath=None, label_colors=None, init_mask=None, aug=False, refine=False)[source]
wbia.plottool._cv2_impaint.demo()[source]
CommandLine:

python -m wbia.plottool.interact_impaint –test-demo

References

http://docs.opencv.org/trunk/doc/py_tutorials/py_gui/py_mouse_handling/py_mouse_handling.html

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.interact_impaint import *  # NOQA
>>> # build test data
>>> # execute function
>>> result = demo()
>>> # verify results
>>> print(result)
wbia.plottool._cv2_impaint.impaint_mask(img, label_colors=None, init_mask=None, init_label=None)[source]
CommandLine:

python -m wbia.plottool.interact_impaint –test-impaint_mask

References

http://docs.opencv.org/trunk/doc/py_tutorials/py_gui/py_mouse_handling/py_mouse_handling.html

TODO: Slider for transparency TODO: Label selector

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.interact_impaint import *  # NOQA
>>> import utool as ut
>>> import vtool as vt
>>> img_fpath = ut.grab_test_imgpath('lena.png')
>>> img = vt.imread(img_fpath)
>>> label_colors = [255, 200, 100, 0]
>>> result = impaint_mask(img, label_colors)
>>> # verify results
>>> print(result)

wbia.plottool._oldimpaint module

wbia.plottool.abstract_interaction module

Known Interactions that use AbstractInteraction:

pt.MatchInteraction2 pt.MultiImageInteraction wbia.NameInteraction

class wbia.plottool.abstract_interaction.AbstractInteraction(**kwargs)[source]

Bases: object

An interaction is meant to take up an entire figure

overwrite either self.plot(fnum, pnum) or self.staic_plot(fnum, pnum) or show_page

LEFT_BUTTON = 1
MIDDLE_BUTTON = 2
MOUSE_BUTTONS = {1: 'left', 2: 'middle', 3: 'right'}
RIGHT_BUTTON = 3
append_button(text, divider=None, rect=None, callback=None, size='9%', location='bottom', ax=None, **kwargs)[source]

Adds a button to the current page

bring_to_front()[source]
clean_scope()[source]

Removes any widgets saved in the interaction scope

clear_parent_axes(ax)[source]

for clearing axes that we appended anything to

close()[source]
connect_callbacks()[source]
draw()[source]
enable_pan(ax)[source]
enable_pan_and_zoom(ax)[source]
enable_zoom(ax)[source]
on_click(event)[source]
on_click_inside(event, ax)[source]
on_click_outside(event)[source]
on_click_release(event)[source]
on_close(event=None)[source]
on_drag(event=None)[source]
on_drag_inside(event=None)[source]
on_drag_start(event=None)[source]
on_drag_stop(event=None)[source]
on_draw(event=None)[source]
on_key_press(event)[source]
on_motion(event)[source]
on_scroll(event)[source]
print_status()[source]
reset_mouse_state()[source]
show()[source]
show_page(*args)[source]

Hack: this function should probably not be defined, but it is for convinience of a developer. Override this or create static plot function (preferably override)

show_popup_menu(options, event)[source]

context menu

start()[source]
update()[source]
class wbia.plottool.abstract_interaction.AbstractPagedInteraction(nPages=None, draw_hud=True, **kwargs)[source]

Bases: wbia.plottool.abstract_interaction.AbstractInteraction

make_hud()[source]

Creates heads up display

next_page(event)[source]
on_key_press(event)[source]
prepare_page(fulldraw=True)[source]
prev_page(event)[source]
wbia.plottool.abstract_interaction.matches_hotkey(key, hotkeys)[source]
wbia.plottool.abstract_interaction.pretty_hotkey_map(hotkeys)[source]
wbia.plottool.abstract_interaction.register_interaction(self)[source]
wbia.plottool.abstract_interaction.unregister_interaction(self)[source]

wbia.plottool.color_funcs module

wbia.plottool.color_funcs.add_alpha(colors)[source]
wbia.plottool.color_funcs.adjust_hsv_of_rgb(rgb, hue_adjust=0.0, sat_adjust=0.0, val_adjust=0.0)[source]

works on a single rgb tuple

Parameters
Returns

new_rgb

Return type

?

CommandLine:

python -m wbia.plottool.color_funcs –test-adjust_hsv_of_rgb –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.color_funcs import *  # NOQA
>>> import wbia.plottool as pt
>>> # build test data
>>> rgb_list = [pt.DEEP_PINK[0:3], pt.DARK_YELLOW[0:3], pt.DARK_GREEN[0:3]]
>>> hue_adjust = -0.1
>>> sat_adjust = +0.5
>>> val_adjust = -0.1
>>> # execute function
>>> new_rgb_list = [adjust_hsv_of_rgb(rgb, hue_adjust, sat_adjust, val_adjust) for rgb in rgb_list]
>>> import wbia.plottool as pt
>>> if pt.show_was_requested():
>>>     color_list = rgb_list + new_rgb_list
>>>     testshow_colors(color_list)
>>> # verify results
>>> result = str(new_rgb)
>>> print(result)
Ignore:

print(np.array([-.1, 0.0, .1, .5, .9, 1.0, 1.1])) print(np.array([-.1, 0.0, .1, .5, .9, 1.0, 1.1]) % 1.0) print(divmod(np.array([-.1, 0.0, .1, .5, .9, 1.0, 1.1]), 1.0)) print(1 + np.array([-.1, 0.0, .1, .5, .9, 1.0, 1.1]) % 1.0)

wbia.plottool.color_funcs.adjust_hsv_of_rgb255(rgb255, *args, **kwargs)[source]
CommandLine:

python -m wbia.plottool.color_funcs –test-adjust_hsv_of_rgb255 –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.color_funcs import *  # NOQA
>>> import wbia.plottool as pt
>>> # build test data
>>> rgb = (220, 220, 255)
>>> hue_adjust =  0.0
>>> sat_adjust = -0.05
>>> val_adjust =  0.0
>>> # execute function
>>> new_rgb = adjust_hsv_of_rgb255(rgb, hue_adjust, sat_adjust, val_adjust)
>>> # verify results
>>> result = str(new_rgb)
>>> print(result)
>>> import wbia.plottool as pt
>>> if pt.show_was_requested():
>>>     color_list = [to_base01(rgb), to_base01(new_rgb)]
>>>     testshow_colors(color_list)
wbia.plottool.color_funcs.assert_base01(channels)[source]
wbia.plottool.color_funcs.assert_base255(channels)[source]
wbia.plottool.color_funcs.brighten(*args, **kwargs)[source]
wbia.plottool.color_funcs.brighten_rgb(rgb, amount)[source]
wbia.plottool.color_funcs.convert_255_to_hex(color255)[source]
>>> color255 = [255, 51, 0]

target_rgb01 = pt.FALSE_RED[0:3] target_rgb = np.array([[target_rgb01]]).astype(np.float32) / 25 target_lab = vt.convert_colorspace(target_rgb, ‘lab’, ‘rgb’)

# Find closest CSS color in LAB space dist_lab = {} dist_rgb = {} css_colors = ub.map_vals(convert_hex_to_255, mcolors.CSS4_COLORS) for k, c in css_colors.items():

rgb = np.array([[c]]).astype(np.float32) / 255 lab = vt.convert_colorspace(rgb, ‘lab’, ‘rgb’) dist_lab[k] = np.sqrt(((target_lab - lab) ** 2).sum()) dist_rgb[k] = np.sqrt(((target_rgb - rgb) ** 2).sum())

best_keys = ub.argsort(dist_lab) ub.odict(zip(best_keys, ub.take(dist_lab, best_keys)))

wbia.plottool.color_funcs.convert_hex_to_255(hex_color)[source]

hex_color = ‘#6A5AFFAF’

wbia.plottool.color_funcs.darken_rgb(rgb, amount)[source]
wbia.plottool.color_funcs.desaturate_rgb(rgb, amount)[source]
CommandLine:

python -m wbia.plottool.color_funcs –test-desaturate_rgb –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.color_funcs import *  # NOQA
>>> rgb = (255.0 / 255.0, 100 / 255.0, 0 / 255.0)
>>> amount = .5
>>> new_rgb = desaturate_rgb(rgb, amount)
>>> # xdoctest: +REQUIRES(--show)
>>> color_list = [rgb, new_rgb, desaturate_rgb(rgb, .7)]
>>> testshow_colors(color_list)
>>> # verify results
>>> result = ut.repr2(new_rgb)
>>> print(result)
(1.0, 0.696078431372549, 0.5)

(1.0, 0.41599384851980004, 0.039215686274509776)

wbia.plottool.color_funcs.distinct_colors(N, brightness=0.878, randomize=True, hue_range=(0.0, 1.0), cmap_seed=None)[source]
Parameters
Returns

RGB_tuples

Return type

list

CommandLine:

python -m wbia.plottool.color_funcs –test-distinct_colors –N 2 –show –hue-range=0.05,.95 python -m wbia.plottool.color_funcs –test-distinct_colors –N 3 –show –hue-range=0.05,.95 python -m wbia.plottool.color_funcs –test-distinct_colors –N 4 –show –hue-range=0.05,.95 python -m wbia.plottool.color_funcs –test-distinct_colors –N 3 –show –no-randomize python -m wbia.plottool.color_funcs –test-distinct_colors –N 4 –show –no-randomize python -m wbia.plottool.color_funcs –test-distinct_colors –N 6 –show –no-randomize python -m wbia.plottool.color_funcs –test-distinct_colors –N 20 –show

References

http://blog.jianhuashao.com/2011/09/generate-n-distinct-colors.html

CommandLine:

python -m wbia.plottool.color_funcs –exec-distinct_colors –show python -m wbia.plottool.color_funcs –exec-distinct_colors –show –no-randomize –N 50 python -m wbia.plottool.color_funcs –exec-distinct_colors –show –cmap_seed=foobar

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.color_funcs import *  # NOQA
>>> # build test data
>>> N = ut.get_argval('--N', int, 2)
>>> randomize = not ut.get_argflag('--no-randomize')
>>> brightness = 0.878
>>> # execute function
>>> cmap_seed = ut.get_argval('--cmap_seed', str, default=None)
>>> hue_range = ut.get_argval('--hue-range', list, default=(0.00, 1.0))
>>> RGB_tuples = distinct_colors(N, brightness, randomize, hue_range, cmap_seed=cmap_seed)
>>> # verify results
>>> assert len(RGB_tuples) == N
>>> result = str(RGB_tuples)
>>> print(result)
>>> ut.quit_if_noshow()
>>> color_list = RGB_tuples
>>> testshow_colors(color_list)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.color_funcs.ensure_base01(color)[source]

always returns a base 01 color

Note, some colors cannot be determined to be either 255 or 01 if they are in float format.

Parameters

color

Returns

color01

Return type

?

CommandLine:

python -m wbia.plottool.color_funcs ensure_base01

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.color_funcs import *  # NOQA
>>> ensure_base01('g')
>>> ensure_base01('orangered')
>>> ensure_base01('#AAAAAA')
>>> ensure_base01([0, 0, 0])
>>> ensure_base01([1, 1, 0, 0])
>>> ensure_base01([1., 1., 0., 0.])
>>> ensure_base01([.7, .2, 0., 0.])
wbia.plottool.color_funcs.ensure_base255(color)[source]

always returns a base 255 color

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.color_funcs import *  # NOQA
>>> ensure_base255('g')
>>> ensure_base255('orangered')
>>> ensure_base255('#AAAAAA')
>>> ensure_base255([0, 0, 0])
>>> ensure_base255([1, 1, 0, 0])
>>> ensure_base255([.9, 1., 0., 0.])
>>> ensure_base255([1., 1., 0., 0.])  # FIXME
>>> ensure_base255([.7, .2, 0., 0.])
wbia.plottool.color_funcs.is_base01(channels)[source]

check if a color is in base 01

wbia.plottool.color_funcs.is_base255(channels)[source]

check if a color is in base 01

wbia.plottool.color_funcs.lighten_rgb(rgb, amount)[source]
CommandLine:

python -m wbia.plottool.color_funcs –test-lighten_rgb –show python -m wbia.plottool.color_funcs –test-lighten_rgb

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.color_funcs import *  # NOQA
>>> # build test data
>>> rgb = np.array((255.0 / 255.0, 100 / 255.0, 0 / 255.0))
>>> amount = .1
>>> # execute function
>>> new_rgb = lighten_rgb(rgb, amount)
>>> import wbia.plottool as pt
>>> if pt.show_was_requested():
>>>     color_list = [rgb, new_rgb, lighten_rgb(rgb, .5)]
>>>     testshow_colors(color_list)
>>> # verify results
>>> result = ut.repr2(new_rgb, with_dtype=False)
>>> print(result)
wbia.plottool.color_funcs.show_all_colormaps()[source]

Displays at a 90 degree angle. Weird

FIXME: Remove call to pylab

References

http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps http://matplotlib.org/examples/color/colormaps_reference.html

Notes

cmaps = [(‘Perceptually Uniform Sequential’,

[‘viridis’, ‘inferno’, ‘plasma’, ‘magma’]),

(‘Sequential’, [‘Blues’, ‘BuGn’, ‘BuPu’,

‘GnBu’, ‘Greens’, ‘Greys’, ‘Oranges’, ‘OrRd’, ‘PuBu’, ‘PuBuGn’, ‘PuRd’, ‘Purples’, ‘RdPu’, ‘Reds’, ‘YlGn’, ‘YlGnBu’, ‘YlOrBr’, ‘YlOrRd’]),

(‘Sequential (2)’, [‘afmhot’, ‘autumn’, ‘bone’, ‘cool’,

‘copper’, ‘gist_heat’, ‘gray’, ‘hot’, ‘pink’, ‘spring’, ‘summer’, ‘winter’]),

(‘Diverging’, [‘BrBG’, ‘bwr’, ‘coolwarm’, ‘PiYG’, ‘PRGn’, ‘PuOr’,

‘RdBu’, ‘RdGy’, ‘RdYlBu’, ‘RdYlGn’, ‘Spectral’, ‘seismic’]),

(‘Qualitative’, [‘Accent’, ‘Dark2’, ‘Paired’, ‘Pastel1’,

‘Pastel2’, ‘Set1’, ‘Set2’, ‘Set3’]),

(‘Miscellaneous’, [‘gist_earth’, ‘terrain’, ‘ocean’, ‘gist_stern’,

‘brg’, ‘CMRmap’, ‘cubehelix’, ‘gnuplot’, ‘gnuplot2’, ‘gist_ncar’, ‘nipy_spectral’, ‘jet’, ‘rainbow’, ‘gist_rainbow’, ‘hsv’, ‘flag’, ‘prism’]) ]

CommandLine:

python -m wbia.plottool.color_funcs –test-show_all_colormaps –show python -m wbia.plottool.color_funcs –test-show_all_colormaps –show –type=Miscellaneous python -m wbia.plottool.color_funcs –test-show_all_colormaps –show –cmap=RdYlBu

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.color_funcs import *  # NOQA
>>> import wbia.plottool as pt
>>> show_all_colormaps()
>>> pt.show_if_requested()
wbia.plottool.color_funcs.testshow_colors(rgb_list, gray=False)[source]

colors = [‘r’, ‘b’, ‘purple’, ‘orange’, ‘deeppink’, ‘g’]

colors = list(mcolors.CSS4_COLORS.keys())

CommandLine:

python -m wbia.plottool.color_funcs testshow_colors –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.color_funcs import *  # NOQA
>>> colors = ut.get_argval('--colors', type_=list, default=['k', 'r'])
>>> ut.quit_if_noshow()
>>> rgb_list = ut.emap(ensure_base01, colors)
>>> testshow_colors(rgb_list)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.color_funcs.to_base01(color255)[source]

converts base 255 color to base 01 color

wbia.plottool.color_funcs.to_base255(color01, assume01=False)[source]

converts base 01 color to base 255 color

wbia.plottool.custom_constants module

wbia.plottool.custom_constants.FontProp(*args, **kwargs)[source]

overwrite fontproperties with custom settings

Kwargs:

fname=u’’, name=u’’, style=u’normal’, variant=u’normal’, weight=u’normal’, stretch=u’normal’, size=u’medium’

wbia.plottool.custom_constants.golden_wh(x)[source]

returns a width / height with a golden aspect ratio

wbia.plottool.custom_constants.golden_wh2(sz)[source]

wbia.plottool.custom_figure module

wbia.plottool.custom_figure.cla()[source]
wbia.plottool.custom_figure.clf()[source]
wbia.plottool.custom_figure.customize_figure(fig, docla)[source]
wbia.plottool.custom_figure.customize_fontprop(font_prop, **fontkw)[source]
wbia.plottool.custom_figure.ensure_fig(fnum=None)[source]
wbia.plottool.custom_figure.figure(fnum=None, pnum=(1, 1, 1), docla=False, title=None, figtitle=None, doclf=False, projection=None, **kwargs)[source]

http://matplotlib.org/users/gridspec.html

Parameters
  • fnum (int) – fignum = figure number

  • pnum (int, str, or tuple(int, int, int)) – plotnum = plot tuple

  • docla (bool) – (default = False)

  • title (str) – (default = None)

  • figtitle (None) – (default = None)

  • doclf (bool) – (default = False)

  • projection (None) – (default = None)

Returns

fig

Return type

?

CommandLine:

python -m wbia.plottool.custom_figure –exec-figure:0 –show python -m wbia.plottool.custom_figure –exec-figure:1 –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.custom_figure import *  # NOQA
>>> fnum = 1
>>> fig = figure(fnum, (2, 2, 1))
>>> gca().text(0.5, 0.5, "ax1", va="center", ha="center")
>>> fig = figure(fnum, (2, 2, 2))
>>> gca().text(0.5, 0.5, "ax2", va="center", ha="center")
>>> import wbia.plottool as pt
>>> pt.show_if_requested()

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.custom_figure import *  # NOQA
>>> fnum = 1
>>> fig = figure(fnum, (2, 2, 1))
>>> gca().text(0.5, 0.5, "ax1", va="center", ha="center")
>>> fig = figure(fnum, (2, 2, 2))
>>> gca().text(0.5, 0.5, "ax2", va="center", ha="center")
>>> fig = figure(fnum, (2, 4, (1, slice(1, None))))
>>> gca().text(0.5, 0.5, "ax3", va="center", ha="center")
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.custom_figure.gca()[source]
wbia.plottool.custom_figure.gcf()[source]
wbia.plottool.custom_figure.get_ax(fnum=None, pnum=None)[source]
wbia.plottool.custom_figure.get_fig(fnum=None)[source]

DEPRICATE use ensure_fig

wbia.plottool.custom_figure.get_image_from_figure(fig)[source]

saves figure data to an ndarray

References

http://stackoverflow.com/questions/7821518/save-plot-to-numpy-array

wbia.plottool.custom_figure.prepare_figure_for_save(fnum, dpi=None, figsize=None, fig=None)[source]

so bad

wbia.plottool.custom_figure.prepare_figure_fpath(fig, fpath, fnum, usetitle, defaultext, verbose, dpath=None)[source]
wbia.plottool.custom_figure.sanitize_img_ext(ext, defaultext=None)[source]
wbia.plottool.custom_figure.sanitize_img_fname(fname)[source]

Removes bad characters from images fnames

wbia.plottool.custom_figure.save_figure(fnum=None, fpath=None, fpath_strict=None, usetitle=False, overwrite=True, defaultext=None, verbose=1, dpi=None, figsize=None, saveax=None, fig=None, dpath=None)[source]

Helper to save the figure image to disk. Tries to be smart about filename lengths, extensions, overwrites, etc…

DEPCIATE

Parameters
  • fnum (int) – figure number

  • fpath (str) – file path string

  • fpath_strict (str) – uses this exact path

  • usetitle (bool) – uses title as the fpath

  • overwrite (bool) – default=True

  • defaultext (str) – default extension

  • verbose (int) – verbosity flag

  • dpi (int) – dots per inch

  • figsize (tuple(int, int)) – figure size

  • saveax (bool or Axes) – specifies if the axes should be saved instead of the figure

References

for saving only a specific Axes http://stackoverflow.com/questions/4325733/save-a-subplot-in-matplotlib http://robotics.usc.edu/~ampereir/wordpress/?p=626 http://stackoverflow.com/questions/1271023/resize-a-figure-automatically-in-matplotlib

wbia.plottool.custom_figure.set_figtitle(figtitle, subtitle='', forcefignum=True, incanvas=True, size=None, fontfamily=None, fontweight=None, fig=None, font=None)[source]
Parameters
  • figtitle

  • subtitle (str) – (default = ‘’)

  • forcefignum (bool) – (default = True)

  • incanvas (bool) – (default = True)

  • fontfamily (None) – (default = None)

  • fontweight (None) – (default = None)

  • size (None) – (default = None)

  • fig (None) – (default = None)

CommandLine:

python -m wbia.plottool.custom_figure set_figtitle –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.custom_figure import *  # NOQA
>>> import wbia.plottool as pt
>>> fig = pt.figure(fnum=1, doclf=True)
>>> result = pt.set_figtitle(figtitle='figtitle', fig=fig)
>>> ut.quit_if_noshow()
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.custom_figure.set_ticks(xticks, yticks)[source]
wbia.plottool.custom_figure.set_title(title='', ax=None, **fontkw)[source]
wbia.plottool.custom_figure.set_xlabel(lbl, ax=None, **kwargs)[source]
Parameters
  • lbl

  • ax (None) – (default = None)

  • **kwargs

CommandLine:

python -m wbia.plottool.custom_figure set_xlabel

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.custom_figure import *  # NOQA
>>> import wbia.plottool as pt
>>> fig = pt.figure()
>>> pt.adjust_subplots(fig=fig, bottom=.5)
>>> ax = pt.gca()
>>> lbl = 'a\nab\nabc'
>>> result = set_xlabel(lbl, ax)
>>> xaxis = ax.get_xaxis()
>>> xlabel = xaxis.get_label()
>>> xlabel.set_horizontalalignment('left')
>>> xlabel.set_x(0)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.custom_figure.set_xticks(tick_set)[source]
wbia.plottool.custom_figure.set_ylabel(lbl, ax=None, **kwargs)[source]
wbia.plottool.custom_figure.set_yticks(tick_set)[source]

wbia.plottool.draw_func2 module

Lots of functions for drawing and plotting visiony things

class wbia.plottool.draw_func2.OffsetImage2(arr, zoom=1, cmap=None, norm=None, interpolation=None, origin=None, filternorm=1, filterrad=4.0, resample=False, dpi_cor=True, **kwargs)[source]

Bases: matplotlib.offsetbox.OffsetBox

TODO: If this works reapply to mpl

draw(renderer)[source]

Draw the children

get_children()[source]

Return a list of the child .Artists.

get_data()[source]
get_extent(renderer)[source]

Return a tuple width, height, xdescent, ydescent of the box.

get_offset()[source]

return offset of the container.

get_window_extent(renderer)[source]

get the bounding box in display space.

get_zoom()[source]
set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, data=<UNSET>, gid=<UNSET>, height=<UNSET>, in_layout=<UNSET>, label=<UNSET>, offset=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, width=<UNSET>, zoom=<UNSET>, zorder=<UNSET>)

Set multiple properties at once.

Supported properties are

Properties:

agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha: scalar or None animated: bool clip_box: .Bbox clip_on: bool clip_path: Patch or (Path, Transform) or None data: unknown figure: ~matplotlib.figure.Figure gid: str height: float in_layout: bool label: object offset: (float, float) or callable path_effects: .AbstractPathEffect picker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: .Transform url: str visible: bool width: float zoom: unknown zorder: float

set_data(arr)[source]
set_zoom(zoom)[source]
class wbia.plottool.draw_func2.RenderingContext(**savekw)[source]

Bases: object

wbia.plottool.draw_func2.absolute_lbl(x_, y_, txt, roffset=(- 0.02, - 0.02), alpha=0.6, **kwargs)[source]

alternative to relative text

wbia.plottool.draw_func2.absolute_text(pos, text, ax=None, **kwargs)[source]
wbia.plottool.draw_func2.add_alpha(colors)[source]
wbia.plottool.draw_func2.adjust_subplots(left=None, right=None, bottom=None, top=None, wspace=None, hspace=None, use_argv=False, fig=None)[source]
Kwargs:

left (float): left side of the subplots of the figure right (float): right side of the subplots of the figure bottom (float): bottom of the subplots of the figure top (float): top of the subplots of the figure wspace (float): width reserved for blank space between subplots hspace (float): height reserved for blank space between subplots

wbia.plottool.draw_func2.append_phantom_legend_label(label, color, type_='circle', alpha=1.0, ax=None)[source]

adds a legend label without displaying an actor

Parameters
  • label

  • color

  • loc (str) –

CommandLine:

python -m wbia.plottool.draw_func2 –test-append_phantom_legend_label –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import wbia.plottool as pt
>>> label = 'some label'
>>> color = 'b'
>>> loc = 'upper right'
>>> fig = pt.figure()
>>> ax = pt.gca()
>>> result = append_phantom_legend_label(label, color, loc, ax=ax)
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.quit_if_noshow()
>>> pt.show_phantom_legend_labels(ax=ax)
>>> pt.show_if_requested()
wbia.plottool.draw_func2.ax_absolute_text(x_, y_, txt, ax=None, roffset=None, **kwargs)[source]

Base function for text

Kwargs:

horizontalalignment in [‘right’, ‘center’, ‘left’], verticalalignment in [‘top’] color

wbia.plottool.draw_func2.axes_bottom_button_bar(ax, text_list=[])[source]
wbia.plottool.draw_func2.axes_extent(axs, pad=0.0)[source]

Get the full extent of a group of axes, including axes labels, tick labels, and titles.

wbia.plottool.draw_func2.cartoon_stacked_rects(xy, width, height, num=4, shift=None, **kwargs)[source]

pt.figure() xy = (.5, .5) width = .2 height = .2 ax = pt.gca() ax.add_collection(col)

wbia.plottool.draw_func2.color_orimag(gori, gmag=None, gmag_is_01=None, encoding='rgb', p=0.5)[source]
Parameters
  • gori (ndarray) – orientation values at pixels between 0 and tau

  • gmag (ndarray) – orientation magnitude

  • gmag_is_01 (bool) – True if gmag is in the 0 and 1 range. if None we try to guess

  • p (float) – power to raise normalized weights to for visualization purposes

Returns

rgb_ori or bgr_ori

Return type

ndarray

CommandLine:

python -m wbia.plottool.draw_func2 –test-color_orimag –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import wbia.plottool as pt
>>> import vtool as vt
>>> # build test data
>>> gori = np.array([[ 0.        ,  0.        ,  3.14159265,  3.14159265,  0.        ],
...                  [ 1.57079633,  3.92250052,  1.81294053,  3.29001537,  1.57079633],
...                  [ 4.71238898,  6.15139659,  0.76764078,  1.75632531,  1.57079633],
...                  [ 4.71238898,  4.51993581,  6.12565345,  3.87978382,  1.57079633],
...                  [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ]])
>>> gmag = np.array([[ 0.        ,  0.02160321,  0.00336692,  0.06290751,  0.        ],
...                      [ 0.02363726,  0.04195344,  0.29969492,  0.53007415,  0.0426679 ],
...                      [ 0.00459386,  0.32086307,  0.02844123,  0.24623816,  0.27344167],
...                      [ 0.04204251,  0.52165989,  0.25800464,  0.14568752,  0.023614  ],
...                      [ 0.        ,  0.05143869,  0.2744546 ,  0.01582246,  0.        ]])
>>> # execute function
>>> p = 1
>>> bgr_ori1 = color_orimag(gori, gmag, encoding='bgr', p=p)
>>> bgr_ori2 = color_orimag(gori, None, encoding='bgr')
>>> legendimg = pt.make_ori_legend_img().astype(np.float32) / 255.0
>>> gweights_color = np.dstack([gmag] * 3).astype(np.float32)
>>> img, _, _ = vt.stack_images(bgr_ori2, gweights_color, vert=False)
>>> img, _, _ = vt.stack_images(img, bgr_ori1, vert=False)
>>> img, _, _ = vt.stack_images(img, legendimg, vert=True, modifysize=True)
>>> # verify results
>>> pt.imshow(img, pnum=(1, 2, 1))
>>> # Hack orientation offset so 0 is downward
>>> gradx, grady = np.cos(gori + TAU / 4.0), np.sin(gori + TAU / 4.0)
>>> pt.imshow(bgr_ori2, pnum=(1, 2, 2))
>>> pt.draw_vector_field(gradx, grady, pnum=(1, 2, 2), invert=False)
>>> color_orimag_colorbar(gori)
>>> pt.set_figtitle('weighted and unweighted orientaiton colors')
>>> pt.update()
>>> pt.show_if_requested()
wbia.plottool.draw_func2.color_orimag_colorbar(gori)[source]
wbia.plottool.draw_func2.colorbar(scalars, colors, custom=False, lbl=None, ticklabels=None, float_format='%.2f', **kwargs)[source]

adds a color bar next to the axes based on specific scalars

Parameters
  • scalars (ndarray) –

  • colors (ndarray) –

  • custom (bool) – use custom ticks

Kwargs:

See plt.colorbar

Returns

matplotlib colorbar object

Return type

cb

CommandLine:

python -m wbia.plottool.draw_func2 –exec-colorbar –show python -m wbia.plottool.draw_func2 –exec-colorbar:1 –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> from wbia.plottool import draw_func2 as df2
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> scalars = np.array([-1, -2, 1, 1, 2, 7, 10])
>>> cmap_ = 'plasma'
>>> logscale = False
>>> custom = True
>>> reverse_cmap = True
>>> val2_customcolor  = {
...        -1: UNKNOWN_PURP,
...        -2: LIGHT_BLUE,
...    }
>>> colors = scores_to_color(scalars, cmap_=cmap_, logscale=logscale, reverse_cmap=reverse_cmap, val2_customcolor=val2_customcolor)
>>> colorbar(scalars, colors, custom=custom)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> from wbia.plottool import draw_func2 as df2
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import wbia.plottool as pt
>>> scalars = np.linspace(0, 1, 100)
>>> cmap_ = 'plasma'
>>> logscale = False
>>> custom = False
>>> reverse_cmap = False
>>> colors = scores_to_color(scalars, cmap_=cmap_, logscale=logscale,
>>>                          reverse_cmap=reverse_cmap)
>>> colors = [pt.lighten_rgb(c, .3) for c in colors]
>>> colorbar(scalars, colors, custom=custom)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.customize_colormap(data, base_colormap)[source]
wbia.plottool.draw_func2.dark_background(ax=None, doubleit=False, force=False)[source]
Parameters
  • ax (None) – (default = None)

  • doubleit (bool) – (default = False)

CommandLine:

python -m wbia.plottool.draw_func2 –exec-dark_background –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import wbia.plottool as pt
>>> fig = pt.figure()
>>> pt.dark_background()
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.distinct_markers(num, style='astrisk', total=None, offset=0)[source]
Parameters

num

CommandLine:

python -m wbia.plottool.draw_func2 –exec-distinct_markers –show python -m wbia.plottool.draw_func2 –exec-distinct_markers –mstyle=star –show python -m wbia.plottool.draw_func2 –exec-distinct_markers –mstyle=polygon –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import wbia.plottool as pt
>>> style = ut.get_argval('--mstyle', type_=str, default='astrisk')
>>> marker_list = distinct_markers(10, style)
>>> x_data = np.arange(0, 3)
>>> for count, (marker) in enumerate(marker_list):
>>>     pt.plot(x_data, [count] * len(x_data), marker=marker, markersize=10, linestyle='', label=str(marker))
>>> pt.legend()
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.draw_bbox(bbox, lbl=None, bbox_color=(1, 0, 0), lbl_bgcolor=(0, 0, 0), lbl_txtcolor=(1, 1, 1), draw_arrow=True, theta=0, ax=None, lw=2)[source]
wbia.plottool.draw_func2.draw_border(ax, color=array([0., 1., 0., 1.]), lw=2, offset=None, adjust=True)[source]

draws rectangle border around a subplot

wbia.plottool.draw_func2.draw_boxedX(xywh=None, color=array([1., 0., 0., 1.]), lw=2, alpha=0.5, theta=0, ax=None)[source]

draws a big red x

wbia.plottool.draw_func2.draw_keypoint_gradient_orientations(rchip, kpt, sift=None, mode='vec', kptkw={}, siftkw={}, **kwargs)[source]

Extracts a keypoint patch from a chip, extract the gradient, and visualizes it with respect to the current mode.

wbia.plottool.draw_func2.draw_keypoint_patch(rchip, kp, sift=None, warped=False, patch_dict={}, **kwargs)[source]
Parameters
  • rchip (ndarray[uint8_t, ndim=2]) – rotated annotation image data

  • kp (ndarray[float32_t, ndim=1]) – a single keypoint

  • sift (None) – (default = None)

  • warped (bool) – (default = False)

  • patch_dict (dict) – (default = {})

Returns

ax

Return type

?

CommandLine:

python -m wbia.plottool.draw_func2 –test-draw_keypoint_patch –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import vtool as vt
>>> rchip = vt.imread(ut.grab_test_imgpath('lena.png'))
>>> kp = [100, 100, 20, 0, 20, 0]
>>> sift = None
>>> warped = True
>>> patch_dict = {}
>>> ax = draw_keypoint_patch(rchip, kp, sift, warped, patch_dict)
>>> result = ('ax = %s' % (str(ax),))
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.draw_kpts2(kpts, offset=(0, 0), scale_factor=1, ell=True, pts=False, rect=False, eig=False, ori=False, pts_size=2, ell_alpha=0.6, ell_linewidth=1.5, ell_color=None, pts_color=array([1., 0.49803922, 0., 1.]), color_list=None, pts_alpha=1.0, siftkw={}, H=None, weights=None, cmap_='hot', ax=None, **kwargs)[source]

thin wrapper around mpl_keypoint.draw_keypoints

FIXME: seems to be off by (.5, .5) translation

Parameters
  • kpts

  • offset (tuple) –

  • scale_factor (int) –

  • ell (bool) –

  • pts (bool) –

  • rect (bool) –

  • eig (bool) –

  • ori (bool) –

  • pts_size (int) –

  • ell_alpha (float) –

  • ell_linewidth (float) –

  • ell_color (None) –

  • pts_color (ndarray) –

  • color_list (list) –

Example

>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> from wbia.plottool import draw_func2 as df2
>>> offset = (0, 0)
>>> scale_factor = 1
>>> ell = True
>>> ell=True
>>> pts=False
>>> rect=False
>>> eig=False
>>> ell=True
>>> pts=False
>>> rect=False
>>> eig=False
>>> ori=False
>>> pts_size=2
>>> ell_alpha=.6
>>> ell_linewidth=1.5
>>> ell_color=None
>>> pts_color=df2.ORANGE
>>> color_list=None
wbia.plottool.draw_func2.draw_line_segments(segments_list, **kwargs)[source]

segments_list - list of [xs,ys,…] defining the segments

wbia.plottool.draw_func2.draw_line_segments2(pts1, pts2, ax=None, **kwargs)[source]

draws N line segments

Parameters
  • pts1 (ndarray) – Nx2

  • pts2 (ndarray) – Nx2

  • ax (None) – (default = None)

CommandLine:

python -m wbia.plottool.draw_func2 draw_line_segments2 –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import wbia.plottool as pt
>>> pts1 = np.array([(1, 1), (0, 0)])
>>> pts2 = np.array([(2, 2), (1, 0)])
>>> pt.figure(fnum=None)
>>> #segments = [np.array((xy1, xy2)) for xy1, xy2 in zip(pts1, pts2)]
>>> #draw_line_segments(segments)
>>> draw_line_segments2(pts1, pts2)
>>> import wbia.plottool as pt
>>> pt.quit_if_noshow()
>>> ax = pt.gca()
>>> pt.set_axis_limit(-1, 3, -1, 3, ax)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.draw_lines2(kpts1, kpts2, fm=None, fs=None, kpts2_offset=(0, 0), color_list=None, scale_factor=1, lw=1.4, line_alpha=0.35, H1=None, H2=None, scale_factor1=None, scale_factor2=None, ax=None, **kwargs)[source]
wbia.plottool.draw_func2.draw_patches_and_sifts(patch_list, sift_list, fnum=None, pnum=(1, 1, 1))[source]
wbia.plottool.draw_func2.draw_stems(x_data=None, y_data=None, setlims=True, color=None, markersize=None, bottom=None, marker=None, linestyle='-')[source]

Draws stem plot

Parameters

References

http://exnumerus.blogspot.com/2011/02/how-to-quickly-plot-multiple-line.html

CommandLine:

python -m wbia.plottool.draw_func2 –test-draw_stems –show python -m wbia.plottool.draw_func2 –test-draw_stems

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> x_data = np.append(np.arange(1, 10), np.arange(1, 10))
>>> rng = np.random.RandomState(0)
>>> y_data = sorted(rng.rand(len(x_data)) * 10)
>>> # y_data = np.array([ut.get_nth_prime(n) for n in x_data])
>>> setlims = False
>>> color = [1.0, 0.0, 0.0, 1.0]
>>> markersize = 2
>>> marker = 'o'
>>> bottom = None
>>> result = draw_stems(x_data, y_data, setlims, color, markersize, bottom, marker)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.draw_text(text_str, rgb_textFG=(0, 0, 0), rgb_textBG=(1, 1, 1))[source]
wbia.plottool.draw_func2.draw_text_annotations(text_list, pos_list, bbox_offset_list=[0, 0], pos_offset_list=[0, 0], bbox_align_list=[0, 0], color_list=None, textprops={})[source]

Hack fixes to issues in text annotations

wbia.plottool.draw_func2.draw_vector_field(gx, gy, fnum=None, pnum=None, title=None, invert=True, stride=1)[source]
CommandLine:

python -m wbia.plottool.draw_func2 draw_vector_field –show python -m wbia.plottool.draw_func2 draw_vector_field –show –fname=zebra.png –fx=121 –stride=3

Example

>>> # DISABLE_DOCTEST
>>> import wbia.plottool as pt
>>> import utool as ut
>>> import vtool as vt
>>> patch = vt.testdata_patch()
>>> gx, gy = vt.patch_gradient(patch, gaussian_weighted=False)
>>> stride = ut.get_argval('--stride', default=1)
>>> pt.draw_vector_field(gx, gy, stride=stride)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.ensure_divider(ax)[source]

Returns previously constructed divider or creates one

wbia.plottool.draw_func2.ensure_fnum(fnum)[source]
wbia.plottool.draw_func2.execstr_global()[source]
wbia.plottool.draw_func2.extract_axes_extents(fig, combine=False, pad=0.0)[source]
CommandLine:

python -m wbia.plottool.draw_func2 extract_axes_extents python -m wbia.plottool.draw_func2 extract_axes_extents –save foo.jpg

Notes:

contour does something weird to axes with contour:

axes_extents = Bbox([[-0.839827203337, -0.00555555555556], [7.77743055556, 6.97227277762]])

without contour

axes_extents = Bbox([[0.0290607810781, -0.00555555555556], [7.77743055556, 5.88]])

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import wbia.plottool as pt
>>> import matplotlib.gridspec as gridspec
>>> import matplotlib.pyplot as plt
>>> pt.qtensure()
>>> fig = plt.figure()
>>> gs = gridspec.GridSpec(17, 17)
>>> specs = [
>>>     gs[0:8,  0:8], gs[0:8,  8:16],
>>>     gs[9:17, 0:8], gs[9:17, 8:16],
>>> ]
>>> rng = np.random.RandomState(0)
>>> X = (rng.rand(100, 2) * [[8, 8]]) + [[6, -14]]
>>> x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
>>> y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
>>> xx, yy = np.meshgrid(np.arange(x_min, x_max), np.arange(y_min, y_max))
>>> yynan = np.full(yy.shape, fill_value=np.nan)
>>> xxnan = np.full(yy.shape, fill_value=np.nan)
>>> cmap = plt.cm.RdYlBu
>>> norm = plt.Normalize(vmin=0, vmax=1)
>>> for count, spec in enumerate(specs):
>>>     fig.add_subplot(spec)
>>>     plt.plot(X.T[0], X.T[1], 'o', color='r', markeredgecolor='w')
>>>     Z = rng.rand(*xx.shape)
>>>     plt.contourf(xx, yy, Z, cmap=cmap, norm=norm, alpha=1.0)
>>>     plt.title('full-nan decision point')
>>>     plt.gca().set_aspect('equal')
>>> gs = gridspec.GridSpec(1, 16)
>>> subspec = gs[:, -1:]
>>> cax = plt.subplot(subspec)
>>> sm = plt.cm.ScalarMappable(cmap=cmap)
>>> sm.set_array(np.linspace(0, 1))
>>> plt.colorbar(sm, cax)
>>> cax.set_ylabel('ColorBar')
>>> fig.suptitle('SupTitle')
>>> subkw = dict(left=.001, right=.9, top=.9, bottom=.05, hspace=.2, wspace=.1)
>>> plt.subplots_adjust(**subkw)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.fig_relative_text(x, y, txt, **kwargs)[source]
wbia.plottool.draw_func2.fnum_generator(base=1)[source]
wbia.plottool.draw_func2.get_all_markers()[source]
CommandLine:

python -m wbia.plottool.draw_func2 –exec-get_all_markers –show

References

http://matplotlib.org/1.3.1/examples/pylab_examples/line_styles.html http://matplotlib.org/api/markers_api.html#matplotlib.markers.MarkerStyle.markers

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import wbia.plottool as pt
>>> marker_dict = get_all_markers()
>>> x_data = np.arange(0, 3)
>>> for count, (marker, name) in enumerate(marker_dict.items()):
>>>     pt.plot(x_data, [count] * len(x_data), marker=marker, linestyle='', label=name)
>>> pt.legend()
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.get_axis_bbox(ax=None, **kwargs)[source]

# returns in figure coordinates?

wbia.plottool.draw_func2.get_axis_xy_width_height(ax=None, xaug=0, yaug=0, waug=0, haug=0)[source]

gets geometry of a subplot

wbia.plottool.draw_func2.get_binary_svm_cmap()[source]
wbia.plottool.draw_func2.get_num_rc(nSubplots=None, nRows=None, nCols=None)[source]

Gets a constrained row column plot grid

Parameters
  • nSubplots (None) – (default = None)

  • nRows (None) – (default = None)

  • nCols (None) – (default = None)

Returns

(nRows, nCols)

Return type

tuple

CommandLine:

python -m wbia.plottool.draw_func2 get_num_rc

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> cases = [
>>>     dict(nRows=None, nCols=None, nSubplots=None),
>>>     dict(nRows=2, nCols=None, nSubplots=5),
>>>     dict(nRows=None, nCols=2, nSubplots=5),
>>>     dict(nRows=None, nCols=None, nSubplots=5),
>>> ]
>>> for kw in cases:
>>>     print('----')
>>>     size = get_num_rc(**kw)
>>>     if kw['nSubplots'] is not None:
>>>         assert size[0] * size[1] >= kw['nSubplots']
>>>     print('**kw = %s' % (ut.repr2(kw),))
>>>     print('size = %r' % (size,))
wbia.plottool.draw_func2.get_orientation_color(radians_list)[source]
Parameters

radians_list (list) –

CommandLine:

python -m wbia.plottool.draw_func2 –test-get_orientation_color

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> # build test data
>>> radians_list = np.linspace(-1, 10, 10)
>>> # execute function
>>> result = get_orientation_color(radians_list)
>>> # verify results
>>> print(result)
wbia.plottool.draw_func2.get_pnum_func(nRows=1, nCols=1, base=0)[source]
wbia.plottool.draw_func2.imshow(img, fnum=None, title=None, figtitle=None, pnum=None, interpolation='nearest', cmap=None, heatmap=False, data_colorbar=False, darken=None, update=False, xlabel=None, redraw_image=True, ax=None, alpha=None, norm=None, **kwargs)[source]
Parameters
  • img (ndarray) – image data

  • fnum (int) – figure number

  • title (str) –

  • figtitle (None) –

  • pnum (tuple) – plot number

  • interpolation (str) – other interpolations = nearest, bicubic, bilinear

  • cmap (None) –

  • heatmap (bool) –

  • data_colorbar (bool) –

  • darken (None) –

  • update (bool) – (default = False)

  • redraw_image (bool) – used when calling imshow over and over. if false doesnt do the image part.

Returns

(fig, ax)

Return type

tuple

Kwargs:

docla, doclf, projection

Returns

(fig, ax)

Return type

tuple

CommandLine:

python -m wbia.plottool.draw_func2 –exec-imshow –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import vtool as vt
>>> img_fpath = ut.grab_test_imgpath('carl.jpg')
>>> img = vt.imread(img_fpath)
>>> (fig, ax) = imshow(img)
>>> result = ('(fig, ax) = %s' % (str((fig, ax)),))
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.imshow_null(msg=None, ax=None, **kwargs)[source]
Parameters
  • msg (None) – (default = None)

  • ax (None) – (default = None)

  • **kwargs – fnum, title, figtitle, pnum, interpolation, cmap, heatmap, data_colorbar, darken, update, xlabel, redraw_image, alpha, docla, doclf, projection, use_gridspec

CommandLine:

python -m wbia.plottool.draw_func2 imshow_null –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> msg = None
>>> ax = None
>>> result = imshow_null(msg, ax)
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.interpolated_colormap(color_frac_list, resolution=64, space='lch-ab')[source]

http://stackoverflow.com/questions/12073306/customize-colorbar-in-matplotlib

CommandLine:

python -m wbia.plottool.draw_func2 interpolated_colormap –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import wbia.plottool as pt
>>> color_frac_list = [
>>>     (pt.TRUE_BLUE, 0),
>>>     #(pt.WHITE, .5),
>>>     (pt.YELLOW, .5),
>>>     (pt.FALSE_RED, 1.0),
>>> ]
>>> color_frac_list = [
>>>     (pt.RED, 0),
>>>     (pt.PINK, .1),
>>>     (pt.ORANGE, .2),
>>>     (pt.GREEN, .5),
>>>     (pt.TRUE_BLUE, .7),
>>>     (pt.PURPLE, 1.0),
>>> ]
>>> color_frac_list = [
>>>     (pt.RED,      0/6),
>>>     (pt.YELLOW,   1/6),
>>>     (pt.GREEN,    2/6),
>>>     (pt.CYAN,     3/6),
>>>     (pt.BLUE,     4/6),  # FIXME doesn't go in correct direction
>>>     (pt.MAGENTA,  5/6),
>>>     (pt.RED,      6/6),
>>> ]
>>> color_frac_list = [
>>>     ((1, 0, 0, 0),  0/6),
>>>     ((1, 0, .001/255, 0),  6/6), # hack
>>> ]
>>> space = 'hsv'
>>> color_frac_list = [
>>>     (pt.BLUE,   0.0),
>>>     (pt.GRAY,   0.5),
>>>     (pt.YELLOW, 1.0),
>>> ]
>>> color_frac_list = [
>>>     (pt.GREEN,  0.0),
>>>     (pt.GRAY,   0.5),
>>>     (pt.RED,    1.0),
>>> ]
>>> space = 'lab'
>>> #resolution = 16 + 1
>>> resolution = 256 + 1
>>> cmap = interpolated_colormap(color_frac_list, resolution, space)
>>> import wbia.plottool as pt
>>> pt.quit_if_noshow()
>>> a = np.linspace(0, 1, resolution).reshape(1, -1)
>>> pylab.imshow(a, aspect='auto', cmap=cmap, interpolation='nearest')  # , origin="lower")
>>> plt.grid(False)
>>> pt.show_if_requested()
wbia.plottool.draw_func2.is_texmode()[source]
wbia.plottool.draw_func2.label_to_colors(labels_)[source]

returns a unique and distinct color corresponding to each label

wbia.plottool.draw_func2.legend(loc='best', fontproperties=None, size=None, fc='w', alpha=1, ax=None, handles=None)[source]
Parameters
  • loc (str) – (default = ‘best’)

  • fontproperties (None) – (default = None)

  • size (None) – (default = None)

CommandLine:

python -m wbia.plottool.draw_func2 –exec-legend –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> loc = 'best'
>>> import wbia.plottool as pt
>>> xdata = np.linspace(-6, 6)
>>> ydata = np.sin(xdata)
>>> pt.plot(xdata, ydata, label='sin')
>>> fontproperties = None
>>> size = None
>>> result = legend(loc, fontproperties, size)
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.lowerright_text(txt)[source]
wbia.plottool.draw_func2.make_bbox(bbox, theta=0, bbox_color=None, ax=None, lw=2, alpha=1.0, align='center', fill=None, **kwargs)[source]
wbia.plottool.draw_func2.make_bbox_positioners(y=0.02, w=0.08, h=0.02, xpad=0.05, startx=0, stopx=1)[source]
wbia.plottool.draw_func2.make_fnum_nextgen(base=1)[source]
wbia.plottool.draw_func2.make_ori_legend_img()[source]

creates a figure that shows which colors are associated with which keypoint rotations.

a rotation of 0 should point downward (becuase it is relative the the (0, 1) keypoint eigenvector. and its color should be red due to the hsv mapping

CommandLine:

python -m wbia.plottool.draw_func2 –test-make_ori_legend_img –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import wbia.plottool as pt
>>> # build test data
>>> # execute function
>>> img_BGR = make_ori_legend_img()
>>> # verify results
>>> pt.imshow(img_BGR)
>>> pt.iup()
>>> pt.show_if_requested()
wbia.plottool.draw_func2.make_pnum_nextgen(nRows=None, nCols=None, base=0, nSubplots=None, start=0)[source]
Parameters
  • nRows (None) – (default = None)

  • nCols (None) – (default = None)

  • base (int) – (default = 0)

  • nSubplots (None) – (default = None)

  • start (int) – (default = 0)

Returns

pnum_next

Return type

iterator

CommandLine:

python -m wbia.plottool.draw_func2 –exec-make_pnum_nextgen –show

GridParams:
>>> param_grid = dict(
>>>     nRows=[None, 3],
>>>     nCols=[None, 3],
>>>     nSubplots=[None, 9],
>>> )
>>> combos = ut.all_dict_combinations(param_grid)
GridExample:
>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> base, start = 0, 0
>>> pnum_next = make_pnum_nextgen(nRows, nCols, base, nSubplots, start)
>>> pnum_list = list( (pnum_next() for _ in it.count()) )
>>> print((nRows, nCols, nSubplots))
>>> result = ('pnum_list = %s' % (ut.repr2(pnum_list),))
>>> print(result)
wbia.plottool.draw_func2.next_fnum(new_base=None)[source]
wbia.plottool.draw_func2.overlay_icon(icon, coords=(0, 0), coord_type='axes', bbox_alignment=(0, 0), max_asize=None, max_dsize=None, as_artist=True)[source]

Overlay a species icon

References

http://matplotlib.org/examples/pylab_examples/demo_annotation_box.html http://matplotlib.org/users/annotations_guide.html /usr/local/lib/python2.7/dist-packages/matplotlib/offsetbox.py

Parameters
  • icon (ndarray or str) – image icon data or path

  • coords (tuple) – (default = (0, 0))

  • coord_type (str) – (default = ‘axes’)

  • bbox_alignment (tuple) – (default = (0, 0))

  • max_dsize (None) – (default = None)

CommandLine:

python -m wbia.plottool.draw_func2 –exec-overlay_icon –show –icon zebra.png python -m wbia.plottool.draw_func2 –exec-overlay_icon –show –icon lena.png python -m wbia.plottool.draw_func2 –exec-overlay_icon –show –icon lena.png –artist

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import wbia.plottool as pt
>>> pt.plot2(np.arange(100), np.arange(100))
>>> icon = ut.get_argval('--icon', type_=str, default='lena.png')
>>> coords = (0, 0)
>>> coord_type = 'axes'
>>> bbox_alignment = (0, 0)
>>> max_dsize = None  # (128, None)
>>> max_asize = (60, 40)
>>> as_artist = not ut.get_argflag('--noartist')
>>> result = overlay_icon(icon, coords, coord_type, bbox_alignment,
>>>                       max_asize, max_dsize, as_artist)
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.pad_axes(pad, xlim=None, ylim=None)[source]
wbia.plottool.draw_func2.param_plot_iterator(param_list, fnum=None, projection=None)[source]
wbia.plottool.draw_func2.parse_fontkw(**kwargs)[source]
Kwargs:

fontsize, fontfamilty, fontproperties

wbia.plottool.draw_func2.plot(*args, **kwargs)[source]
wbia.plottool.draw_func2.plot2(x_data, y_data, marker='o', title_pref='', x_label='x', y_label='y', unitbox=False, flipx=False, flipy=False, title=None, dark=None, equal_aspect=True, pad=0, label='', fnum=None, pnum=None, *args, **kwargs)[source]

don’t forget to call pt.legend

Kwargs:

linewidth (float):

wbia.plottool.draw_func2.plot_bars(y_data, nColorSplits=1)[source]
wbia.plottool.draw_func2.plot_descriptor_signature(vec, title='', fnum=None, pnum=None)[source]

signature general for for any descriptor vector.

Parameters
  • vec (ndarray) –

  • title (str) – (default = ‘’)

  • fnum (int) – figure number(default = None)

  • pnum (tuple) – plot number(default = None)

Returns

ax

Return type

AxesSubplot

CommandLine:

python -m wbia.plottool.draw_func2 –test-plot_descriptor_signature –show

SeeAlso:

plot_sift_signature

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import vtool as vt
>>> vec = ((np.random.RandomState(0).rand(258) - .2) * 4)
>>> title = 'test sift histogram'
>>> fnum = None
>>> pnum = None
>>> ax = plot_descriptor_signature(vec, title, fnum, pnum)
>>> result = ('ax = %s' % (str(ax),))
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.plot_fmatch(xywh1, xywh2, kpts1, kpts2, fm, fs=None, fm_norm=None, lbl1=None, lbl2=None, fnum=None, pnum=None, rect=False, colorbar_=True, draw_border=False, cmap=None, H1=None, H2=None, scale_factor1=None, scale_factor2=None, ax=None, **kwargs)[source]

Overlays the matching features over chips that were previously plotted.

Parameters
  • xywh1 (tuple) – location of rchip1 in the axes

  • xywh2 (tuple) – location or rchip2 in the axes

  • kpts1 (ndarray) – keypoints in rchip1

  • kpts2 (ndarray) – keypoints in rchip1

  • fm (list) – feature matches

  • fs (list) – features scores

  • fm_norm (None) – (default = None)

  • lbl1 (None) – rchip1 label

  • lbl2 (None) – rchip2 label

  • fnum (None) – figure number

  • pnum (None) – plot number

  • rect (bool) –

  • colorbar (bool) –

  • draw_border (bool) –

  • cmap (None) – (default = None)

  • H1 (None) – (default = None)

  • H2 (None) – (default = None)

  • scale_factor1 (None) – (default = None)

  • scale_factor2 (None) – (default = None)

Kwargs:

draw_pts, draw_ell, draw_lines, show_nMatches, all_kpts

Returns

None

Return type

?

CommandLine:

python -m wbia.plottool.draw_func2 –exec-plot_fmatch

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> xywh1 = '?'
>>> xywh2 = '?'
>>> kpts1 = '?'
>>> kpts2 = '?'
>>> fm = '?'
>>> fs = None
>>> fm_norm = None
>>> lbl1 = None
>>> lbl2 = None
>>> fnum = None
>>> pnum = None
>>> rect = False
>>> colorbar_ = True
>>> draw_border = False
>>> cmap = None
>>> H1 = None
>>> H2 = None
>>> scale_factor1 = None
>>> scale_factor2 = None
>>> plot_fmatch(xywh1, xywh2, kpts1, kpts2, fm, fs, fm_norm, lbl1, lbl2,
>>>             fnum, pnum, rect, colorbar_, draw_border, cmap, h1, h2,
>>>             scale_factor1, scale_factor2)
>>> result = ('None = %s' % (str(None),))
>>> print(result)
wbia.plottool.draw_func2.plot_func(funcs, start=0, stop=1, num=100, setup=None, fnum=None, pnum=None)[source]

plots a numerical function in a given range

Parameters
  • funcs (list of function) – live python function

  • start (int) – (default = 0)

  • stop (int) – (default = 1)

  • num (int) – (default = 100)

CommandLine:

python -m wbia.plottool.draw_func2 –exec-plot_func –show –range=-1,1 –func=np.exp python -m wbia.plottool.draw_func2 –exec-plot_func –show –range=-1,1 –func=scipy.special.logit python -m wbia.plottool.draw_func2 –exec-plot_func –show –range=0,1 –func=”lambda x: scipy.special.expit(((x * 2) - 1.0) * 6)” python -m wbia.plottool.draw_func2 –exec-plot_func –show –range=0,1 –func=”lambda x: scipy.special.expit(-6 + 12 * x)” python -m wbia.plottool.draw_func2 –exec-plot_func –show –range=0,4 –func=”lambda x: vt.logistic_01((-1 + x) * 2)” python -m wbia.plottool.draw_func2 –exec-plot_func –show –range=0,1 –func=”lambda x: np.tan((x - .5) * np.pi)” –ylim=-10,10 python -m wbia.plottool.draw_func2 –exec-plot_func –show –range=0,3 –func=np.tan python -m wbia.plottool.draw_func2 –exec-plot_func –show –range=0,50 –func=”lambda x: np.exp(-x / 50)” python -m wbia.plottool.draw_func2 –exec-plot_func –show –range=-8,8 –func=vt.beaton_tukey_loss python -m wbia.plottool.draw_func2 –exec-plot_func –show –range=-8,8 –func=vt.beaton_tukey_weight,vt.beaton_tukey_loss

python -m wbia.plottool plot_func –show –range=-1,1

–setup=”from wbia.algo.smk.smk_pipeline import SMK” –func=lambda u: SMK.selectivity(u, 3.0, 0)

python -m wbia.plottool plot_func –show –range=-1,1

–func “lambda u: sign(u) * abs(u)**3.0 * greater_equal(u, 0)” “lambda u: (sign((u+1)/2) * abs((u+1)/2)**3.0 * greater_equal(u, 0+.5))”

alpha=3 thresh=-1

python -m wbia.plottool plot_func –show –range=-1,1

–func “lambda u: sign(u) * abs(u)**$alpha * greater_equal(u, $thresh)” “lambda u: (sign(u) * abs(u)**$alpha * greater_equal(u, $thresh) + 1) / 2” “lambda u: sign((u+1)/2) * abs((u+1)/2)**$alpha * greater_equal(u, $thresh)”

python -m wbia.plottool plot_func –show –range=4,100

–func “lambda n: log2(n)”“lambda n: log2(log2(n))”“lambda n: log2(n)/log2(log2(n))”“lambda n: log2(n) ** 2”“lambda n: n”

python -m wbia.plottool plot_func –show –range=4,1000000

–func “lambda n: log2(n)”“lambda n: n ** (1/3)”

python -m wbia.plottool plot_func –show –range=0,10

–func “lambda x: (3 * (x ** 2) - 18 * (x) - 81) / ((x ** 2) - 54) “

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import scipy
>>> import scipy.special  # NOQA
>>> func_list = ut.get_argval('--func', type_=list, default=['np.exp'])
>>> setup = ut.get_argval('--setup', type_=str, default=None)
>>> #funcs = [eval(f) for f in func_list]
>>> funcs = func_list
>>> start, stop = ut.get_argval('--range', type_=list, default=[-1, 1])
>>> start, stop = eval(str(start)), eval(str(stop))
>>> num = 1000
>>> result = plot_func(funcs, start, stop, num, setup=setup)
>>> print(result)
>>> import plottool as pt
>>> pt.quit_if_noshow()
>>> ylim = ut.get_argval('--ylim', type_=list, default=None)
>>> import wbia.plottool as pt
>>> None if ylim is None else plt.gca().set_ylim(*ylim)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.plot_hist(data, bins=None, nbins=10, weights=None)[source]
wbia.plottool.draw_func2.plot_histpdf(data, label=None, draw_support=False, nbins=10)[source]
wbia.plottool.draw_func2.plot_sift_signature(sift, title='', fnum=None, pnum=None)[source]

Plots a SIFT descriptor as a histogram and distinguishes different bins into different colors

Parameters
  • sift (ndarray[dtype=np.uint8]) –

  • title (str) – (default = ‘’)

  • fnum (int) – figure number(default = None)

  • pnum (tuple) – plot number(default = None)

Returns

ax

Return type

AxesSubplot

CommandLine:

python -m wbia.plottool.draw_func2 –test-plot_sift_signature –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import vtool as vt
>>> sift = vt.demodata.testdata_dummy_sift(1, np.random.RandomState(0))[0]
>>> title = 'test sift histogram'
>>> fnum = None
>>> pnum = None
>>> ax = plot_sift_signature(sift, title, fnum, pnum)
>>> result = ('ax = %s' % (str(ax),))
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.plot_surface3d(xgrid, ygrid, zdata, xlabel=None, ylabel=None, zlabel=None, wire=False, mode=None, contour=False, dark=False, rstride=1, cstride=1, pnum=None, labelkw=None, xlabelkw=None, ylabelkw=None, zlabelkw=None, titlekw=None, *args, **kwargs)[source]

References

http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html

CommandLine:

python -m wbia.plottool.draw_func2 –exec-plot_surface3d –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import wbia.plottool as pt
>>> import vtool as vt
>>> shape=(19, 19)
>>> sigma1, sigma2 = 2.0, 1.0
>>> ybasis = np.arange(shape[0])
>>> xbasis = np.arange(shape[1])
>>> xgrid, ygrid = np.meshgrid(xbasis, ybasis)
>>> sigma = [sigma1, sigma2]
>>> gausspatch = vt.gaussian_patch(shape, sigma=sigma)
>>> title = 'ksize=%r, sigma=%r' % (shape, (sigma1, sigma2),)
>>> pt.plot_surface3d(xgrid, ygrid, gausspatch, rstride=1, cstride=1,
>>>                   cmap=mpl.cm.coolwarm, title=title)
>>> pt.show_if_requested()
wbia.plottool.draw_func2.pnum_generator(nRows=1, nCols=1, base=0, nSubplots=None, start=0)[source]
Parameters
  • nRows (int) – (default = 1)

  • nCols (int) – (default = 1)

  • base (int) – (default = 0)

  • nSubplots (None) – (default = None)

Yields

tuple – pnum

CommandLine:

python -m wbia.plottool.draw_func2 –exec-pnum_generator –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> nRows = 3
>>> nCols = 2
>>> base = 0
>>> pnum_ = pnum_generator(nRows, nCols, base)
>>> result = ut.repr2(list(pnum_), nl=1, nobr=True)
>>> print(result)
(3, 2, 1),
(3, 2, 2),
(3, 2, 3),
(3, 2, 4),
(3, 2, 5),
(3, 2, 6),

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> nRows = 3
>>> nCols = 2
>>> pnum_ = pnum_generator(nRows, nCols, start=3)
>>> result = ut.repr2(list(pnum_), nl=1, nobr=True)
>>> print(result)
(3, 2, 4),
(3, 2, 5),
(3, 2, 6),
wbia.plottool.draw_func2.postsetup_axes(use_legend=True, bg=None)[source]
wbia.plottool.draw_func2.presetup_axes(x_label='x', y_label='y', title_pref='', title=None, equal_aspect=False, ax=None, **kwargs)[source]
wbia.plottool.draw_func2.print_valid_cmaps()[source]
wbia.plottool.draw_func2.quit_if_noshow()[source]
wbia.plottool.draw_func2.relative_text(pos, text, ax=None, offset=None, **kwargs)[source]

Places text on axes in a relative position

Parameters
  • pos (tuple) – relative xy position

  • text (str) – text

  • ax (None) – (default = None)

  • offset (None) – (default = None)

  • **kwargs – horizontalalignment, verticalalignment, roffset, ha, va, fontsize, fontproperties, fontproperties, clip_on

CommandLine:

python -m wbia.plottool.draw_func2 relative_text –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import wbia.plottool as pt
>>> x = .5
>>> y = .5
>>> txt = 'Hello World'
>>> pt.figure()
>>> ax = pt.gca()
>>> family = 'monospace'
>>> family = 'CMU Typewriter Text'
>>> fontproperties = mpl.font_manager.FontProperties(family=family,
>>>                                                  size=42)
>>> result = relative_text((x, y), txt, ax, halign='center',
>>>                           fontproperties=fontproperties)
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.remove_patches(ax=None)[source]

deletes patches from axes

wbia.plottool.draw_func2.render_figure_to_image(fig, **savekw)[source]
wbia.plottool.draw_func2.reverse_colormap(cmap)[source]

References

http://nbviewer.ipython.org/github/kwinkunks/notebooks/blob/master/Matteo_colourmaps.ipynb

wbia.plottool.draw_func2.rotate_plot(theta=0.7853981633974483, ax=None)[source]
Parameters
  • theta

  • ax (None) –

CommandLine:

python -m wbia.plottool.draw_func2 –test-rotate_plot

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> # build test data
>>> ax = gca()
>>> theta = TAU / 8
>>> plt.plot([1, 2, 3, 4, 5], [1, 2, 3, 2, 2])
>>> # execute function
>>> result = rotate_plot(theta, ax)
>>> # verify results
>>> print(result)
>>> show_if_requested()
wbia.plottool.draw_func2.save_parts(fig, fpath, grouped_axes=None, dpi=None)[source]

FIXME: this works in mpl 2.0.0, but not 2.0.2

Parameters
  • fig

  • fpath (str) – file path string

  • dpi (None) – (default = None)

Returns

subpaths

Return type

list

CommandLine:

python -m wbia.plottool.draw_func2 save_parts

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import wbia.plottool as pt
>>> import matplotlib as mpl
>>> import matplotlib.pyplot as plt
>>> def testimg(fname):
>>>     return plt.imread(mpl.cbook.get_sample_data(fname))
>>> fnames = ['grace_hopper.png', 'ada.png'] * 4
>>> fig = plt.figure(1)
>>> for c, fname in enumerate(fnames, start=1):
>>>     ax = fig.add_subplot(3, 4, c)
>>>     ax.imshow(testimg(fname))
>>>     ax.set_title(fname[0:3] + str(c))
>>>     ax.set_xticks([])
>>>     ax.set_yticks([])
>>> ax = fig.add_subplot(3, 1, 3)
>>> ax.plot(np.sin(np.linspace(0, np.pi * 2)))
>>> ax.set_xlabel('xlabel')
>>> ax.set_ylabel('ylabel')
>>> ax.set_title('title')
>>> fpath = 'test_save_parts.png'
>>> adjust_subplots(fig=fig, wspace=.3, hspace=.3, top=.9)
>>> subpaths = save_parts(fig, fpath, dpi=300)
>>> fig.savefig(fpath)
>>> ut.startfile(subpaths[0])
>>> ut.startfile(fpath)
wbia.plottool.draw_func2.scores_to_cmap(scores, colors=None, cmap_='hot')[source]
wbia.plottool.draw_func2.scores_to_color(score_list, cmap_='hot', logscale=False, reverse_cmap=False, custom=False, val2_customcolor=None, score_range=None, cmap_range=(0.1, 0.9))[source]

Other good colormaps are ‘spectral’, ‘gist_rainbow’, ‘gist_ncar’, ‘Set1’, ‘Set2’, ‘Accent’ # TODO: plasma

Parameters
  • score_list (list) –

  • cmap (str) – defaults to hot

  • logscale (bool) –

  • cmap_range (tuple) – restricts to only a portion of the cmap to avoid extremes

Returns

<class ‘_ast.ListComp’>

SeeAlso:

python -m wbia.plottool.color_funcs –test-show_all_colormaps –show –type “Perceptually Uniform Sequential”

CommandLine:

python -m wbia.plottool.draw_func2 scores_to_color –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import wbia.plottool as pt
>>> ut.exec_funckw(pt.scores_to_color, globals())
>>> score_list = np.array([-1, -2, 1, 1, 2, 10])
>>> # score_list = np.array([0, .1, .11, .12, .13, .8])
>>> # score_list = np.linspace(0, 1, 100)
>>> cmap_ = 'plasma'
>>> colors = pt.scores_to_color(score_list, cmap_)
>>> import vtool as vt
>>> imgRGB = vt.atleast_nd(np.array(colors)[:, 0:3], 3, tofront=True)
>>> imgRGB = imgRGB.astype(np.float32)
>>> imgBGR = vt.convert_colorspace(imgRGB, 'BGR', 'RGB')
>>> pt.imshow(imgBGR)
>>> pt.show_if_requested()

Example

>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> score_list = np.array([-1, -2, 1, 1, 2, 10])
>>> cmap_ = 'hot'
>>> logscale = False
>>> reverse_cmap = True
>>> custom = True
>>> val2_customcolor  = {
...        -1: UNKNOWN_PURP,
...        -2: LIGHT_BLUE,
...    }
wbia.plottool.draw_func2.set_axis_extent(extents, ax=None)[source]
Parameters

extents – xmin, xmax, ymin, ymax

wbia.plottool.draw_func2.set_axis_limit(xmin, xmax, ymin, ymax, ax=None)[source]
wbia.plottool.draw_func2.set_figsize(w, h, dpi)[source]
wbia.plottool.draw_func2.show_chipmatch2(rchip1, rchip2, kpts1=None, kpts2=None, fm=None, fs=None, fm_norm=None, title=None, vert=None, fnum=None, pnum=None, heatmap=False, modifysize=False, new_return=False, draw_fmatch=True, darken=None, H1=None, H2=None, sel_fm=[], ax=None, heatmask=False, white_background=False, **kwargs)[source]

Draws two chips and the feature matches between them. feature matches kpts1 and kpts2 use the (x,y,a,c,d)

Parameters
  • rchip1 (ndarray) – rotated annotation 1 image data

  • rchip2 (ndarray) – rotated annotation 2 image data

  • kpts1 (ndarray) – keypoints for annotation 1 [x, y, a=1, c=0, d=1, theta=0]

  • kpts2 (ndarray) – keypoints for annotation 2 [x, y, a=1, c=0, d=1, theta=0]

  • fm (list) – list of feature matches as tuples (qfx, dfx)

  • fs (list) – list of feature scores

  • fm_norm (None) – (default = None)

  • title (str) – (default = None)

  • vert (None) – (default = None)

  • fnum (int) – figure number(default = None)

  • pnum (tuple) – plot number(default = None)

  • heatmap (bool) – (default = False)

  • modifysize (bool) – (default = False)

  • new_return (bool) – (default = False)

  • draw_fmatch (bool) – (default = True)

  • darken (None) – (default = None)

  • H1 (None) – (default = None)

  • H2 (None) – (default = None)

  • sel_fm (list) – (default = [])

  • ax (None) – (default = None)

  • heatmask (bool) – (default = False)

  • **kwargs – all_kpts, lbl1, lbl2, rect, colorbar_, draw_border, cmap, scale_factor1, scale_factor2, draw_pts, draw_ell, draw_lines, ell_alpha, colors

Returns

(xywh1, xywh2, sf_tup)

Return type

tuple

CommandLine:

python -m wbia.plottool.draw_func2 show_chipmatch2 –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import wbia.plottool as pt
>>> import vtool as vt
>>> rchip1 = vt.imread(ut.grab_test_imgpath('easy1.png'))
>>> rchip2 = vt.imread(ut.grab_test_imgpath('easy2.png'))
>>> kpts1 = np.array([
>>>     [10,  10,   30,   0,    30,    0.  ],
>>>     [ 355.89,  142.95,   10.46,   -0.63,    8.59,    0.  ],
>>>     [ 356.35,  147.  ,    8.38,    1.08,   11.68,    0.  ],
>>>     [ 361.4 ,  150.64,    7.44,    3.45,   13.63,    0.  ]
>>> ], dtype=np.float64)
>>> kpts2 = np.array([
>>>     [ 10,   10,   30,   0,    30,    0.  ],
>>>     [ 376.98,   50.61,   11.91,   -2.9 ,    9.77,    0.  ],
>>>     [ 377.59,   54.89,    9.7 ,   -1.4 ,   13.72,    0.  ],
>>>     [ 382.8 ,   58.2 ,    7.87,   -0.31,   15.23,    0.  ]
>>> ], dtype=np.float64)
>>> fm = None
>>> fs = None
>>> H1 = np.array([
>>>     [ -4.68815126e-01,   7.80306795e-02,  -2.23674587e+01],
>>>     [  4.54394231e-02,  -7.67438835e-01,   5.92158624e+01],
>>>     [  2.12918867e-04,  -8.64851418e-05,  -6.21472492e-01]])
>>> H1 = None
>>> H2 = None
>>> #H_half = np.array([[.2, 0, 0], [0, .2, 0], [0, 0, 1]])
>>> #H1 = H_half
>>> #H2 = H_half
>>> kwargs = dict(H1=H1, H2=H2, fm=fm, draw_lines=True, draw_ell=True)
>>> kwargs.update(ell_linewidth=5, lw=10, line_alpha=[1, .3, .3, .3])
>>> result = show_chipmatch2(rchip1, rchip2, kpts1, kpts2, **kwargs)
>>> pt.show_if_requested()
wbia.plottool.draw_func2.show_histogram(data, bins=None, **kwargs)[source]
CommandLine:

python -m wbia.plottool.draw_func2 –test-show_histogram –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> # build test data
>>> data = np.array([1, 24, 0, 0, 3, 4, 5, 9, 3, 0, 0, 0, 0, 2, 2, 2, 0, 0, 1, 1, 0, 0, 0, 3,])
>>> bins = None
>>> # execute function
>>> result = show_histogram(data, bins)
>>> # verify results
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.show_if_requested(N=1)[source]

Used at the end of tests. Handles command line arguments for saving figures

Referencse:

http://stackoverflow.com/questions/4325733/save-a-subplot-in-matplotlib

wbia.plottool.draw_func2.show_kpts(kpts, fnum=None, pnum=None, **kwargs)[source]

Show keypoints in a new figure. Note: use draw_kpts2 to overlay keypoints on a existing figure.

Parameters

kpts (ndarray[float32_t, ndim=2]) – keypoints

CommandLine:

xdoctest -m ~/code/plottool/plottool/draw_func2.py show_kpts

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.draw_func2 import *  # NOQA
>>> import vtool as vt
>>> kpts = vt.demodata.get_dummy_kpts()
>>> result = show_kpts(kpts)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.draw_func2.show_phantom_legend_labels(ax=None, **kwargs)[source]
wbia.plottool.draw_func2.show_signature(sig, **kwargs)[source]
wbia.plottool.draw_func2.show_was_requested()[source]

returns True if –show is specified on the commandline or you are in IPython (and presumably want some sort of interaction

wbia.plottool.draw_func2.small_xticks(ax=None)[source]
wbia.plottool.draw_func2.small_yticks(ax=None)[source]
wbia.plottool.draw_func2.space_xticks(nTicks=9, spacing=16, ax=None)[source]
wbia.plottool.draw_func2.space_yticks(nTicks=9, spacing=32, ax=None)[source]
wbia.plottool.draw_func2.test_save()[source]
CommandLine:

python -m wbia.plottool.draw_func2 test_save –show python -m wbia.plottool.draw_func2 test_save

wbia.plottool.draw_func2.udpate_adjust_subplots()[source]

DEPRICATE

updates adjust_subplots based on command line

wbia.plottool.draw_func2.unique_rows(arr)[source]

References

http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array

wbia.plottool.draw_func2.update_figsize()[source]

updates figsize based on command line

wbia.plottool.draw_func2.upperleft_text(txt, alpha=0.6, color=None)[source]
wbia.plottool.draw_func2.upperright_text(txt, offset=None, alpha=0.6)[source]
wbia.plottool.draw_func2.variation_trunctate(data)[source]
wbia.plottool.draw_func2.width_from(num, pad=0.05, start=0, stop=1)[source]

wbia.plottool.draw_sv module

wbia.plottool.draw_sv.get_blended_chip(chip1, chip2, M)[source]

warps chip1 into chip2 space

wbia.plottool.draw_sv.show_sv(chip1, chip2, kpts1, kpts2, fm, homog_tup=None, aff_tup=None, mx=None, show_assign=True, show_lines=True, show_kpts=True, show_aff=None, fnum=1, refine_method=None, **kwargs)[source]

Visualizes spatial verification

CommandLine:

python -m vtool.spatial_verification –test-spatially_verify_kpts –show

wbia.plottool.draw_sv.show_sv_simple(chip1, chip2, kpts1, kpts2, fm, inliers, mx=None, fnum=1, vert=None, **kwargs)[source]
CommandLine:

python -m wbia.plottool.draw_sv –test-show_sv_simple –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.draw_sv import *  # NOQA
>>> import vtool as vt
>>> kpts1, kpts2, fm, aff_inliers, chip1, chip2, xy_thresh_sqrd = vt.testdata_matching_affine_inliers()
>>> inliers = aff_inliers
>>> mx = None
>>> fnum = 1
>>> vert = None  # ut.get_argval('--vert', type_=bool, default=None)
>>> result = show_sv_simple(chip1, chip2, kpts1, kpts2, fm, inliers, mx, fnum, vert=vert)
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()

wbia.plottool.fig_presenter module

wbia.plottool.fig_presenter.all_figures_bring_to_front()[source]
wbia.plottool.fig_presenter.all_figures_show()[source]
wbia.plottool.fig_presenter.all_figures_tight_layout()[source]
wbia.plottool.fig_presenter.all_figures_tile(max_rows=None, row_first=True, no_tile=False, monitor_num=None, percent_w=None, percent_h=None, hide_toolbar=True)[source]

Lays out all figures in a grid. if wh is a scalar, a golden ratio is used

wbia.plottool.fig_presenter.bring_to_front(fig)[source]
wbia.plottool.fig_presenter.close_all_figures()[source]
wbia.plottool.fig_presenter.close_figure(fig)[source]
wbia.plottool.fig_presenter.draw()[source]
wbia.plottool.fig_presenter.get_all_figures()[source]
wbia.plottool.fig_presenter.get_all_qt4_wins()[source]
wbia.plottool.fig_presenter.get_all_windows()[source]

Returns all mpl figures and registered qt windows

wbia.plottool.fig_presenter.get_figure_window(fig)[source]
wbia.plottool.fig_presenter.get_geometry(fnum)[source]
wbia.plottool.fig_presenter.get_main_win_base()[source]
wbia.plottool.fig_presenter.iup()
wbia.plottool.fig_presenter.iupdate()[source]
wbia.plottool.fig_presenter.present(*args, **kwargs)[source]

basically calls show if not embeded.

Kwargs:

max_rows, row_first, no_tile, monitor_num, percent_w, percent_h, hide_toolbar

CommandLine:

python -m wbia.plottool.fig_presenter present

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.fig_presenter import *  # NOQA
>>> result = present()
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.fig_presenter.register_qt4_win(win)[source]
wbia.plottool.fig_presenter.reset()[source]
wbia.plottool.fig_presenter.set_geometry(fnum, x, y, w, h)[source]
wbia.plottool.fig_presenter.show()[source]
wbia.plottool.fig_presenter.show_figure(fig)[source]
wbia.plottool.fig_presenter.unregister_qt4_win(win)[source]
wbia.plottool.fig_presenter.update()[source]

wbia.plottool.interact_annotations module

Interactive tool to draw mask on an image or image-like array.

Todo

  • need concept of subannotation

  • need to take options on a right click of an annotation

  • add support for arbitrary polygons back in .

  • rename species_list to label_list or category_list

  • Just use metadata instead of species / category / label

# Need to incorporate parts into metadata

Notes

3. Change bounding box and update continuously to the original image the new ANNOTATIONs

2. Make new window and frames inside, double click to pull up normal window with editing start with just taking in 6 images and ANNOTATIONs

  1. ANNOTATION ID number, then list of 4 tuples

python -m utool.util_inspect check_module_usage –pat=”interact_annotations.py”

References

Adapted from matplotlib/examples/event_handling/poly_editor.py Jan 9 2014: taken from: https://gist.github.com/tonysyu/3090704

CommandLine:

python -m wbia.plottool.interact_annotations –test-test_interact_annots –show

class wbia.plottool.interact_annotations.AnnotPoly(ax, num, verts, theta, species, fc=(0, 0, 0), line_color=(1, 1, 1), line_width=4, is_orig=False, metadata=None, valid_species=None, manager=None)[source]

Bases: matplotlib.patches.Polygon, utool.util_dev.NiceRepr

Helper to represent an annotation polygon wbia –aidcmd=’Interact image’ –aid=1

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.interact_annotations import *  # NOQA
>>> verts = vt.verts_from_bbox([0, 0, 10, 10])
>>> poly = AnnotPoly(None, 0, verts, 0, '____')
add_to_axis(ax)[source]
axes_init(ax)[source]
calc_handle_display_coords()[source]
calc_tag_position()[source]
CommandLine:

python -m wbia.plottool.interact_annotations –test-calc_tag_position –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.interact_annotations import *  # NOQA
>>> poly = ut.DynStruct()
>>> poly.basecoords = vt.verts_from_bbox([0, 0, 400, 400], True)
>>> poly.theta = 0
>>> poly.xy = vt.verts_from_bbox([0, 0, 400, 400], True)
>>> tagpos = poly.calc_tag_position()
>>> print('tagpos = %r' % (tagpos,))
draw_self(ax, show_species_tags=False, editable=True)[source]
get_poly_mask(shape)[source]
increment_species(amount=1)[source]
is_near_handle(xy_pt, max_dist)[source]
move_poly(dx, dy, ax)[source]
move_to_back()[source]
print_info()[source]
remove_from_axis(ax)[source]
resize_poly(x, y, idx, ax)[source]

Resize a rectangle using idx as the given anchor point. Respects current rotation.

CommandLine:

python -m wbia.plottool.interact_annotations –exec-resize_poly –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.interact_annotations import *  # NOQA
>>> (h, w) = img.shape[0:2]
>>> x1, y1 = 10, 10
>>> x2, y2 = w - 10,  h - 10
>>> coords = ((x1, y1), (x1, y2), (x2, y2), (x2, y1))
>>> x = 3 * w / 4
>>> y = 3 * h / 4
>>> idx = 3
>>> resize_poly(poly, x, y, idx)
>>> update_UI()
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
rotate_poly(dtheta, ax)[source]
set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, antialiased=<UNSET>, capstyle=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, closed=<UNSET>, color=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, fill=<UNSET>, gid=<UNSET>, hatch=<UNSET>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, species=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, xy=<UNSET>, zorder=<UNSET>)

Set multiple properties at once.

Supported properties are

Properties:

agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alpha: scalar or None animated: bool antialiased or aa: bool or None capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clip_box: .Bbox clip_on: bool clip_path: Patch or (Path, Transform) or None closed: bool color: color edgecolor or ec: color or None facecolor or fc: color or None figure: .Figure fill: bool gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float or None path_effects: .AbstractPathEffect picker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None species: unknown transform: .Transform url: str visible: bool xy: (N, 2) array-like zorder: float

set_species(text)[source]
property size
update_color(selected=False, editing_parts=False)[source]
update_display_coords()[source]
update_lines()[source]
class wbia.plottool.interact_annotations.AnnotationInteraction(img, img_ind=None, commit_callback=None, verts_list=None, bbox_list=None, theta_list=None, species_list=None, metadata_list=None, line_width=4, line_color=(1, 1, 1), face_color=(0, 0, 0), fnum=None, default_species='____', next_callback=None, prev_callback=None, do_mask=False, valid_species=[], **kwargs)[source]

Bases: wbia.plottool.abstract_interaction.AbstractInteraction

An interactive polygon editor.

SeeAlso:

wbia.viz.interact.interact_annotations2 (ensure that any updates here are propogated there)

Parameters

verts_list (list) – list of lists of (float, float) List of (x, y) coordinates used as vertices of the polygon.

add_action_buttons()[source]
add_new_poly(event=None, full=False)[source]

Adds a new annotation to the image

connect_mpl_callbacks(canvas)[source]

disconnects matplotlib callbacks specified in the self.mpl_callback_ids dict

delete_current_poly(event=None)[source]

Removes an annotation

disconnect_mpl_callbacks(canvas)[source]

disconnects all connected matplotlib callbacks

draw_artists()[source]
draw_callback(event)[source]
edit_poly_parts(poly)[source]
property editable_polys
get_most_recently_added_poly()[source]
get_poly_under_cursor(x, y)[source]

get the index of the vertex under cursor if within max_dist tolerance

handle_polygon_creation(bbox_list, theta_list, species_list, metadata_list)[source]

Maintain original input

property in_edit_parts_mode
is_poly_pickable(artist, event)[source]
new_polygon(verts, theta, species, fc=(0, 0, 0), line_color=(1, 1, 1), line_width=4, is_orig=False, metadata=None)[source]

verts - list of (x, y) tuples

next_image(event)[source]
on_click(event)[source]

python -m wbia.viz.interact.interact_annotations2 –test-ishow_image2 –show

on_click_release(event)[source]
on_figure_leave(event)[source]
on_key_press(event)[source]
on_motion(event)[source]
on_pick(event)[source]

Makes selected polygon translucent

prev_image(event)[source]
reinitialize_figure(fnum=None)[source]
rrr(verbose=True, reload_module=True)

special class reloading function This function is often injected as rrr of classes

save_and_exit(event, do_close=True)[source]

The Save and Exit Button

write a callback to redraw viz for bbox_list

show()[source]
start()[source]
toggle_species_label()[source]
property uneditable_polys
update_UI()[source]
update_callbacks(next_callback, prev_callback)[source]
update_image_and_callbacks(img, bbox_list, theta_list, species_list, metadata_list, next_callback, prev_callback)[source]
wbia.plottool.interact_annotations.apply_mask(img, mask)[source]
wbia.plottool.interact_annotations.apply_polarDelta(poldelt, cart)[source]
wbia.plottool.interact_annotations.calc_display_coords(oldcoords, theta)[source]
wbia.plottool.interact_annotations.check_dims(ax, xy_pt, margin=0.5)[source]

checks if bounding box dims are ok

Allow the bounding box to go off the image so orientations can be done correctly

wbia.plottool.interact_annotations.check_min_wh(coords)[source]

Depends on hardcoded indices, which is inelegant, but we’re already depending on those for the FUDGE_FACTORS array above 0—-1 | | 3—-2

wbia.plottool.interact_annotations.check_valid_coords(ax, coords_list)[source]
wbia.plottool.interact_annotations.default_vertices(img, polys=None, mouseX=None, mouseY=None)[source]

Default to rectangle that has a quarter-width/height border.

wbia.plottool.interact_annotations.enforce_dims(ax, xy_pt, margin=0.5)[source]

ONLY USE THIS ON UNROTATED RECTANGLES, as to do otherwise may yield arbitrary polygons

wbia.plottool.interact_annotations.is_within_distance_from_line(pt, line, max_dist)[source]
wbia.plottool.interact_annotations.points_center(pts)[source]
wbia.plottool.interact_annotations.polarDelta(p1, p2)[source]
wbia.plottool.interact_annotations.pretty_hotkey_map(hotkeys)[source]
wbia.plottool.interact_annotations.rotate_points_around(points, theta, ax, ay)[source]

References

http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/matrix2d/

wbia.plottool.interact_annotations.test_interact_annots()[source]
CommandLine:

python -m wbia.plottool.interact_annotations –test-test_interact_annots –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.interact_annotations import *  # NOQA
>>> import wbia.plottool as pt
>>> # build test data
>>> # execute function
>>> self = test_interact_annots()
>>> # verify results
>>> print(self)
>>> pt.show_if_requested()

wbia.plottool.interact_helpers module

wbia.plottool.interact_helpers.begin_interaction(type_, fnum)[source]
wbia.plottool.interact_helpers.clicked_inside_axis(event)[source]
wbia.plottool.interact_helpers.clicked_outside_axis(event)[source]
wbia.plottool.interact_helpers.connect_callback(fig, callback_type, callback_fn)[source]

wrapper around fig.canvas.mpl_connect

References

http://matplotlib.org/users/event_handling.html button_press_event button_release_event draw_event key_press_event key_release_event motion_notify_event pick_event resize_event scroll_event figure_enter_event figure_leave_event axes_enter_event axes_leave_event

wbia.plottool.interact_helpers.detect_keypress(fig)[source]
wbia.plottool.interact_helpers.disconnect_callback(fig, callback_type, **kwargs)[source]

wbia.plottool.interact_impaint module

helpers for painting on top of images for groundtruthing

References

http://stackoverflow.com/questions/22232812/drawing-on-image-with-matplotlib-and-opencv-update-image http://stackoverflow.com/questions/34933254/force-matplotlib-to-block-in-a-pyqt-thread-process http://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html http://stackoverflow.com/questions/22410663/block-qmainwindow-while-child-widget-is-alive-pyqt http://stackoverflow.com/questions/20289939/pause-execution-until-button-press

class wbia.plottool.interact_impaint.PaintInteraction(img, **kwargs)[source]

Bases: wbia.plottool.abstract_interaction.AbstractInteraction

References

http://stackoverflow.com/questions/22232812/drawing-on-image-with-mpl

CommandLine:

python -m wbia.plottool.interact_impaint –exec-draw_demo –show

apply_stroke(x, y, color)[source]
do_blit()[source]
on_click_inside(event, ax)[source]
on_close(event=None)[source]
on_drag_inside(event)[source]
on_drag_stop(event)[source]
on_draw(event)[source]
on_key_press(event)[source]
on_scroll(event)[source]
static_plot(fnum=None, pnum=(1, 1, 1))[source]
update_image()[source]
update_title()[source]
wbia.plottool.interact_impaint.draw_demo()[source]
CommandLine:

python -m wbia.plottool.interact_impaint –exec-draw_demo –show

Example

>>> # SCRIPT
>>> from wbia.plottool.interact_impaint import *  # NOQA
>>> result = draw_demo()
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.interact_impaint.impaint_mask2(img, init_mask=None)[source]

python -m wbia.plottool.interact_impaint –exec-draw_demo –show

wbia.plottool.interact_keypoints module

class wbia.plottool.interact_keypoints.KeypointInteraction(chip, kpts, vecs, fnum=0, figtitle=None, **kwargs)[source]

Bases: wbia.plottool.abstract_interaction.AbstractInteraction

CommandLine:

python -m wbia.plottool.interact_keypoints –exec-KeypointInteraction –show python -m wbia.plottool.interact_keypoints –exec-KeypointInteraction –show –fname=lena.png

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.interact_keypoints import *  # NOQA
>>> import numpy as np
>>> import wbia.plottool as pt
>>> import utool as ut
>>> import pyhesaff
>>> import vtool as vt
>>> kpts, vecs, imgBGR = pt.viz_keypoints.testdata_kpts()
>>> ut.quit_if_noshow()
>>> #pt.interact_keypoints.ishow_keypoints(imgBGR, kpts, vecs, ori=True, ell_alpha=.4, color='distinct')
>>> pt.interact_keypoints.KeypointInteraction(imgBGR, kpts, vecs, ori=True, ell_alpha=.4, autostart=True)
>>> pt.show_if_requested()
on_click_inside(event, ax)[source]
on_click_outside(event)[source]
plot(fnum=None, pnum=(1, 1, 1), **kwargs)[source]
wbia.plottool.interact_keypoints.ishow_keypoints(chip, kpts, desc, fnum=0, figtitle=None, nodraw=False, **kwargs)[source]

TODO: Depricate in favor of the class

CommandLine:

python -m wbia.plottool.interact_keypoints –test-ishow_keypoints –show python -m wbia.plottool.interact_keypoints –test-ishow_keypoints –show –fname zebra.png

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.interact_keypoints import *  # NOQA
>>> import numpy as np
>>> import wbia.plottool as pt
>>> import utool as ut
>>> import pyhesaff
>>> import vtool as vt
>>> kpts, vecs, imgBGR = pt.viz_keypoints.testdata_kpts()
>>> ut.quit_if_noshow()
>>> #pt.interact_keypoints.ishow_keypoints(imgBGR, kpts, vecs, ori=True, ell_alpha=.4, color='distinct')
>>> pt.interact_keypoints.ishow_keypoints(imgBGR, kpts, vecs, ori=True, ell_alpha=.4)
>>> pt.show_if_requested()

wbia.plottool.interact_matches module

Unfinished non-wbia dependent version of interact matches

class wbia.plottool.interact_matches.MatchInteraction2(rchip1, rchip2, kpts1, kpts2, fm, fs, fsv, vecs1, vecs2, H1=None, H2=None, fnum=None, **kwargs)[source]

Bases: wbia.plottool.abstract_interaction.AbstractInteraction

TODO: replace functional version with this class

Plots a chip result and sets up callbacks for interaction.

SeeAlso:

wbia.viz.interact.interact_matches.MatchInteraction

CommandLine:

python -m wbia.plottool.interact_matches –test-MatchInteraction2 –show

Example

>>> # xdoctest: +REQUIRES(module:wbia, --slow)
>>> from wbia.plottool.interact_matches import *  # NOQA
>>> import wbia
>>> # build test data
>>> ibs = wbia.opendb('testdb1')
>>> qreq_ = ibs.new_query_request([1], [2, 3, 4, 5], cfgdict=dict(query_rotation_heuristic=True))
>>> cm = qreq_.execute()[0]
>>> qaid = cm.qaid
>>> daid = cm.get_top_aids()[0]
>>> rchip1 = ibs.get_annot_chips([qaid], config2_=qreq_.extern_query_config2)[0]
>>> rchip2 = ibs.get_annot_chips([daid], config2_=qreq_.extern_data_config2)[0]
>>> kpts1 = ibs.get_annot_kpts([qaid], config2_=qreq_.extern_query_config2)[0]
>>> kpts2 = ibs.get_annot_kpts([daid], config2_=qreq_.extern_data_config2)[0]
>>> vecs1 = ibs.get_annot_vecs([qaid], config2_=qreq_.extern_query_config2)[0]
>>> vecs2 = ibs.get_annot_vecs([daid], config2_=qreq_.extern_data_config2)[0]
>>> fm = cm.aid2_fm[daid]
>>> fs = cm.aid2_fs[daid]
>>> fsv = cm.aid2_fsv[daid]
>>> H1 = cm.aid2_H[daid]
>>> self = MatchInteraction2(rchip1, rchip2, kpts1, kpts2, fm, fs, fsv,
>>>                          vecs1, vecs2, H1)
>>> self.show_page()
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
chipmatch_view(fnum=None, pnum=(1, 1, 1), verbose=None, **kwargs_)[source]

just visualizes the matches using some type of lines

get_popup_options()[source]
on_click_inside(event, ax)[source]
on_click_outside(event)[source]
plot(*args, **kwargs)[source]
rrr(verbose=True, reload_module=True)

special class reloading function This function is often injected as rrr of classes

select_ith_match(mx)[source]

Selects the ith match and visualizes and prints information concerning features weights, keypoint details, and sift descriptions

wbia.plottool.interact_matches.show_keypoint_gradient_orientations(ibs, rchip, kp, vec, fnum=None, pnum=None, config2_=None)[source]

wbia.plottool.interact_multi_image module

class wbia.plottool.interact_multi_image.MultiImageInteraction(gpath_list, nPerPage=4, bboxes_list=None, thetas_list=None, verts_list=None, gid_list=None, nImgs=None, fnum=None, context_option_funcs=None, xlabel_list=None, vizkw=None, **kwargs)[source]

Bases: wbia.plottool.abstract_interaction.AbstractInteraction

CommandLine:

python -m wbia.plottool.interact_multi_image –exec-MultiImageInteraction –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.interact_multi_image import *  # NOQA
>>> import utool as ut
>>> TEST_IMAGES_URL = 'https://wildbookiarepository.azureedge.net/data/testdata.zip'
>>> test_image_dir = ut.grab_zipped_url(TEST_IMAGES_URL, appname='utool')
>>> # test image paths
>>> imgpaths       = ut.list_images(test_image_dir, fullpath=True, recursive=False)
>>> bboxes_list = [[]] * len(imgpaths)
>>> #bboxes_list[0] = [(-200, -100, 400, 400)]
>>> bboxes_list[0] = [(20, 10, 400, 400)]
>>> iteract_obj = MultiImageInteraction(imgpaths, nPerPage=4,
>>>                                     bboxes_list=bboxes_list)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
dump_to_disk(dpath, num=None, prefix='temp_img')[source]
make_hud()[source]

Creates heads up display

next_page(event)[source]
on_click_inside(event, ax)[source]
on_key_press(event)[source]
plot_image(index)[source]
prepare_page(pagenum)[source]

Gets indexes for the pagenum ready to be displayed

prev_page(event)[source]
rrr(verbose=True, reload_module=True)

special class reloading function This function is often injected as rrr of classes

show_page(pagenum=None)[source]

Displays a page of matches

update_images(img_ind, updated_bbox_list, updated_theta_list, changed_annottups, new_annottups)[source]

Insert code for viz_image2 redrawing here

wbia.plottool.interactions module

class wbia.plottool.interactions.ExpandableInteraction(fnum=None, _pnumiter=None, interactive=None, **kwargs)[source]

Bases: wbia.plottool.abstract_interaction.AbstractInteraction

Append a list of functions that draw plots and this interaction will plot them in appropriate subplots and let you click on them to zoom in.

Parameters
  • fnum (int) – figure number(default = None)

  • _pnumiter (None) – (default = None)

  • interactive (None) – (default = None)

  • **kwargs – nRows, nCols

CommandLine:

python -m wbia.plottool.interactions –exec-ExpandableInteraction –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.interactions import *  # NOQA
>>> import numpy as np
>>> import wbia.plottool as pt
>>> inter = pt.interactions.ExpandableInteraction()
>>> inter.append_plot(ut.partial(pt.plot_func, np.sin, stop=np.pi * 2))
>>> inter.append_plot(ut.partial(pt.plot_func, np.cos, stop=np.pi * 2))
>>> inter.append_plot(ut.partial(pt.plot_func, np.tan, stop=np.pi * 2))
>>> inter.start()
>>> pt.show_if_requested()
append_partial(func, *args, **kwargs)[source]

Register a plotting function with default arguments

Parameters
  • func (callable) – plotting function (does NOT need fnum/pnum).

  • *args – args to be passed to func

  • **kwargs – kwargs to be passed to func

append_plot(func, pnum=None, ishow_func=None, px=None)[source]

Register a plotting function

Parameters
  • func (callable) – must take fnum and pnum as keyword arguments.

  • pnum (tuple) – plot num / gridspec. Defaults based on append order

  • ishow_func (callable) – an interactive version of func

  • px (int) – None or a plot index into (nRows, nCols)

on_click(event)[source]
show_page()[source]

Hack: this function should probably not be defined, but it is for convinience of a developer. Override this or create static plot function (preferably override)

class wbia.plottool.interactions.PanEvents(ax=None)[source]

Bases: object

pan_on_motion(event)[source]
pan_on_press(event)[source]
pan_on_release(event)[source]
wbia.plottool.interactions.check_if_subinteract(func)[source]
wbia.plottool.interactions.pan_factory(ax=None)[source]
wbia.plottool.interactions.zoom_factory(ax=None, zoomable_list=[], base_scale=1.1)[source]

References

https://gist.github.com/tacaswell/3144287 http://stackoverflow.com/questions/11551049/matplotlib-plot-zooming-with-scroll-wheel

wbia.plottool.mpl_keypoint module

class wbia.plottool.mpl_keypoint.HomographyTransform(H, axis=None, use_rmin=True)[source]

Bases: matplotlib.transforms.Transform

References

http://stackoverflow.com/questions/28401788/using-homogeneous-transforms-non-affine-with-matplotlib-patches?noredirect=1#comment45156353_28401788 http://matplotlib.org/users/transforms_tutorial.html

input_dims = 2

The number of input dimensions of this transform. Must be overridden (with integers) in the subclass.

is_separable = False

True if this transform is separable in the x- and y- dimensions.

output_dims = 2

The number of output dimensions of this transform. Must be overridden (with integers) in the subclass.

transform_non_affine(input_xy)[source]

The input and output are Nx2 numpy arrays.

transform_path_non_affine(path)[source]

Apply the non-affine part of this transform to .Path path, returning a new .Path.

transform_path(path) is equivalent to transform_path_affine(transform_path_non_affine(values)).

wbia.plottool.mpl_keypoint.draw_keypoints(ax, kpts_, scale_factor=1.0, offset=(0.0, 0.0), rotation=0.0, ell=True, pts=False, rect=False, eig=False, ori=False, sifts=None, siftkw={}, H=None, **kwargs)[source]

draws keypoints extracted by pyhesaff onto a matplotlib axis

FIXME: There is probably a matplotlib bug here. If you specify two different alphas in a collection, whatever the last alpha was gets applied to everything

Parameters
  • ax (mpl.Axes) –

  • kpts (ndarray) – keypoints [[x, y, a, c, d, theta], …]

  • scale_factor (float) –

  • offset (tuple) –

  • rotation (float) –

  • ell (bool) –

  • pts (bool) –

  • rect (bool) –

  • eig (bool) –

  • ori (bool) –

  • sifts (None) –

References

http://stackoverflow.com/questions/28401788/transforms-non-affine-patch

CommandLine:

python -m wbia.plottool.mpl_keypoint draw_keypoints –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.mpl_keypoint import *  # NOQA
>>> from wbia.plottool.mpl_keypoint import _draw_patches, _draw_pts  # NOQA
>>> import wbia.plottool as pt
>>> import vtool as vt
>>> imgBGR = vt.get_star_patch(jitter=True)
>>> H = np.array([[1, 0, 0], [.5, 2, 0], [0, 0, 1]])
>>> H = np.array([[.8, 0, 0], [0, .8, 0], [0, 0, 1]])
>>> H = None
>>> TAU = 2 * np.pi
>>> kpts_ = vt.make_test_image_keypoints(imgBGR, scale=.5, skew=2, theta=TAU / 8.0)
>>> scale_factor=1.0
>>> #offset=(0.0, -4.0)
>>> offset=(0.0, 0.0)
>>> rotation=0.0
>>> ell=True
>>> pts=True
>>> rect=True
>>> eig=True
>>> ori=True
>>> # make random sifts
>>> sifts = mpl_sift.testdata_sifts()
>>> siftkw = {}
>>> kwargs = dict(ori_color=[0, 1, 0], rect_color=[0, 0, 1],
>>>               eig_color=[1, 1, 0], pts_size=.1)
>>> w, h = imgBGR.shape[0:2][::-1]
>>> imgBGR_ = imgBGR if H is None else vt.warpAffine(
>>>     imgBGR, H, (int(w * .8), int(h * .8)))
>>> fig, ax = pt.imshow(imgBGR_ * 255)
>>> draw_keypoints(ax, kpts_, scale_factor, offset, rotation, ell, pts,
...                rect, eig, ori, sifts, siftkw, H=H, **kwargs)
>>> pt.iup()
>>> pt.show_if_requested()
wbia.plottool.mpl_keypoint.eigenvector_actors(invVR_aff2Ds)[source]
wbia.plottool.mpl_keypoint.ellipse_actors(invVR_aff2Ds)[source]
wbia.plottool.mpl_keypoint.get_invVR_aff2Ds(kpts, H=None)[source]

Returns matplotlib keypoint transformations (circle -> ellipse)

Example

>>> # Test CV2 ellipse vs mine using MSER
>>> import vtool as vt
>>> import cv2
>>> import wbia.plottool as pt
>>> img_fpath = ut.grab_test_imgpath(ut.get_argval('--fname', default='zebra.png'))
>>> imgBGR = vt.imread(img_fpath)
>>> imgGray = cv2.cvtColor(imgBGR, cv2.COLOR_BGR2GRAY)
>>> mser = cv2.MSER_create()
>>> regions, bboxs = mser.detectRegions(imgGray)
>>> region = regions[0]
>>> bbox = bboxs[0]
>>> vis = imgBGR.copy()
>>> vis[region.T[1], region.T[0], :] = 0
>>> hull = cv2.convexHull(region.reshape(-1, 1, 2))
>>> cv2.polylines(vis, [hull], 1, (0, 255, 0))
>>> ell = cv2.fitEllipse(region)
>>> cv2.ellipse(vis, ell, (255))
>>> ((cx, cy), (rx, ry), degrees) = ell
>>> # Convert diameter to radians
>>> rx /= 2
>>> ry /= 2
>>> # Make my version of ell
>>> theta = np.radians(degrees)  # opencv lives in radians
>>> S = vt.scale_mat3x3(rx, ry)
>>> T = vt.translation_mat3x3(cx, cy)
>>> R = vt.rotation_mat3x3(theta)
>>> #R = np.eye(3)
>>> invVR = T.dot(R).dot(S)
>>> kpts = vt.flatten_invV_mats_to_kpts(np.array([invVR]))
>>> pt.imshow(vis)
>>> # MINE IS MUCH LARGER (by factor of 2)) WHY?
>>> # we start out with a unit circle not a half circle
>>> pt.draw_keypoints(pt.gca(), kpts, pts=True, ori=True, eig=True, rect=True)
wbia.plottool.mpl_keypoint.orientation_actors(kpts, H=None)[source]

creates orientation actors w.r.t. the gravity vector

wbia.plottool.mpl_keypoint.pass_props(dict1, dict2, *args)[source]
wbia.plottool.mpl_keypoint.rectangle_actors(invVR_aff2Ds)[source]

wbia.plottool.mpl_sift module

wbia.plottool.mpl_sift.draw_sift_on_patch(patch, sift, **kwargs)[source]
wbia.plottool.mpl_sift.draw_sifts(ax, sifts, invVR_aff2Ds=None, **kwargs)[source]

Gets sift patch collections, transforms them and then draws them.

CommandLine:

python -m wbia.plottool.mpl_sift –test-draw_sifts –show

Example

>>> # ENABLE_DOCTEST
>>> from wbia.plottool.mpl_sift import *  # NOQA
>>> # build test data
>>> import wbia.plottool as pt
>>> pt.figure(1)
>>> ax = pt.gca()
>>> ax.set_xlim(-1.1, 1.1)
>>> ax.set_ylim(-1.1, 1.1)
>>> sifts = testdata_sifts()
>>> sifts[:, 0:8] = 0
>>> invVR_aff2Ds = None
>>> kwargs = dict(multicolored_arms=False)
>>> kwargs['arm1_lw'] = 3
>>> kwargs['stroke'] = 5
>>> result = draw_sifts(ax, sifts, invVR_aff2Ds, **kwargs)
>>> ax.set_aspect('equal')
>>> print(result)
>>> pt.show_if_requested()
wbia.plottool.mpl_sift.get_sift_collection(sift, aff=None, bin_color=array([0., 0., 0., 1.]), arm1_color=array([1., 0., 0., 1.]), arm2_color=array([0., 0., 0., 1.]), arm_alpha=1.0, arm1_lw=1.0, arm2_lw=2.0, stroke=1.0, circ_alpha=0.5, fidelity=256, scaling=True, **kwargs)[source]

Creates a collection of SIFT matplotlib patches

get_sift_collection

Parameters
  • sift

  • aff (None) –

  • bin_color (ndarray) –

  • arm1_color (ndarray) –

  • arm2_color (ndarray) –

  • arm_alpha (float) –

  • arm1_lw (float) –

  • arm2_lw (float) –

  • circ_alpha (float) –

  • fidelity (int) – quantization factor

Returns

coll_tup

Return type

?

CommandLine:

python -m wbia.plottool.mpl_sift –test-get_sift_collection

Example

>>> from wbia.plottool.mpl_sift import *  # NOQA
>>> sift = testdata_sifts()[0]
>>> aff = None
>>> bin_color = np.array([ 0.,  0.,  0.,  1.])
>>> arm1_color = np.array([ 1.,  0.,  0.,  1.])
>>> arm2_color = np.array([ 0.,  0.,  0.,  1.])
>>> arm_alpha = 1.0
>>> arm1_lw = 0.5
>>> arm2_lw = 1.0
>>> circ_alpha = 0.5
>>> coll_tup = get_sift_collection(sift, aff, bin_color, arm1_color,
>>>                                arm2_color, arm_alpha, arm1_lw,
>>>                                arm2_lw, circ_alpha)
>>> print(coll_tup)
wbia.plottool.mpl_sift.render_sift_on_patch(patch, sift)[source]
wbia.plottool.mpl_sift.testdata_sifts()[source]

wbia.plottool.nx_helpers module

Helpers for graph plotting

References

http://www.graphviz.org/content/attrs http://www.graphviz.org/doc/info/attrs.html

Ignore:

http://www.graphviz.org/pub/graphviz/stable/windows/graphviz-2.38.msi pip uninstall pydot pip uninstall pyparsing pip install -Iv https://pypi.python.org/packages/source/p/pyparsing/pyparsing-1.5.7.tar.gz#md5=9be0fcdcc595199c646ab317c1d9a709 pip install pydot sudo apt-get install libgraphviz4 libgraphviz-dev -y sudo apt-get install libgraphviz-dev pip install pygraphviz sudo pip3 install pygraphviz

–install-option=”–include-path=/usr/include/graphviz” –install-option=”–library-path=/usr/lib/graphviz/”

python -c “import pygraphviz; print(pygraphviz.__file__)” python3 -c “import pygraphviz; print(pygraphviz.__file__)”

class wbia.plottool.nx_helpers.GRAPHVIZ_KEYS[source]

Bases: object

E = {'URL', 'arrowhead', 'arrowsize', 'arrowtail', 'color', 'colorscheme', 'comment', 'constraint', 'decorate', 'dir', 'edgeURL', 'edgehref', 'edgetarget', 'edgetooltip', 'fillcolor', 'fontcolor', 'fontname', 'fontsize', 'headURL', 'head_lp', 'headclip', 'headhref', 'headlabel', 'headport', 'headtarget', 'headtooltip', 'href', 'id', 'label', 'labelURL', 'labelangle', 'labeldistance', 'labelfloat', 'labelfontcolor', 'labelfontname', 'labelfontsize', 'labelhref', 'labeltarget', 'labeltooltip', 'layer', 'len', 'lhead', 'lp', 'ltail', 'minlen', 'nojustify', 'penwidth', 'pos', 'samehead', 'sametail', 'showboxes', 'style', 'tailURL', 'tail_lp', 'tailclip', 'tailhref', 'taillabel', 'tailport', 'tailtarget', 'tailtooltip', 'target', 'tooltip', 'weight', 'xlabel', 'xlp'}
G = {'Damping', 'K', 'URL', '_background', 'bb', 'bgcolor', 'center', 'charset', 'clusterrank', 'colorscheme', 'comment', 'compound', 'concentrate', 'defaultdist', 'dim', 'dimen', 'diredgeconstraints', 'dpi', 'epsilon', 'esep', 'fontcolor', 'fontname', 'fontnames', 'fontpath', 'fontsize', 'forcelabels', 'gradientangle', 'href', 'id', 'imagepath', 'inputscale', 'label', 'label_scheme', 'labeljust', 'labelloc', 'landscape', 'layerlistsep', 'layers', 'layerselect', 'layersep', 'layout', 'levels', 'levelsgap', 'lheight', 'lp', 'lwidth', 'margin', 'maxiter', 'mclimit', 'mindist', 'mode', 'model', 'mosek', 'newrank', 'nodesep', 'nojustify', 'normalize', 'notranslate', 'nslimit\nnslimit1', 'ordering', 'orientation', 'outputorder', 'overlap', 'overlap_scaling', 'overlap_shrink', 'pack', 'packmode', 'pad', 'page', 'pagedir', 'quadtree', 'quantum', 'rankdir', 'ranksep', 'ratio', 'remincross', 'repulsiveforce', 'resolution', 'root', 'rotate', 'rotation', 'scale', 'searchsize', 'sep', 'showboxes', 'size', 'smoothing', 'sortv', 'splines', 'start', 'style', 'stylesheet', 'target', 'truecolor', 'viewport', 'voro_margin', 'xdotversion'}
N = {'URL', 'area', 'color', 'colorscheme', 'comment', 'distortion', 'fillcolor', 'fixedsize', 'fontcolor', 'fontname', 'fontsize', 'gradientangle', 'group', 'height', 'href', 'id', 'image', 'imagepos', 'imagescale', 'label', 'labelloc', 'layer', 'margin', 'nojustify', 'ordering', 'orientation', 'penwidth', 'peripheries', 'pin', 'pos', 'rects', 'regular', 'root', 'samplepoints', 'shape', 'shapefile', 'showboxes', 'sides', 'skew', 'sortv', 'style', 'target', 'tooltip', 'vertices', 'width', 'xlabel', 'xlp', 'z'}
class wbia.plottool.nx_helpers.GraphVizLayoutConfig(**kwargs)[source]

Bases: wbia.dtool.base.Config

Ignore:
Node Props:
colorscheme CEGN string NaN
fontcolor CEGN color NaN

fontname CEGN string NaN fontsize CEGN double NaN

label CEGN lblString NaN

nojustify CEGN bool NaN

style CEGN style NaN color CEN colorcolorList NaN

fillcolor CEN colorcolorList NaN

layer CEN layerRange NaN

penwidth CEN double NaN

radientangle CGN int NaN
labelloc CGN string NaN
margin CGN doublepoint NaN

sortv CGN int NaN

peripheries CN int NaN
showboxes EGN int dot only
comment EGN string NaN

pos EN pointsplineType NaN

xlabel EN lblString NaN

ordering GN string dot only
group N string dot only

pin N bool fdp | neato only

distortion N double NaN
fixedsize N boolstring NaN
height N double NaN

image N string NaN

imagescale N boolstring NaN

orientation N double NaN

regular N bool NaN

samplepoints N int NaN

shape N shape NaN

shapefile N string NaN
sides N int NaN

skew N double NaN

width N double NaN

z N double NaN

static get_param_info_list()[source]
wbia.plottool.nx_helpers.apply_graph_layout_attrs(graph, layout_info)[source]
wbia.plottool.nx_helpers.draw_network2(graph, layout_info, ax, as_directed=None, hacknoedge=False, hacknode=False, verbose=None, **kwargs)[source]
Kwargs:

use_image, arrow_width, fontsize, fontweight, fontname, fontfamilty, fontproperties

fancy way to draw networkx graphs without directly using networkx

# python -m wbia.annotmatch_funcs review_tagged_joins –dpath ~/latex/crall-candidacy-2015/ –save figures4/mergecase.png –figsize=15,15 –clipwhite –diskshow # python -m dtool –tf DependencyCache.make_graph –show

wbia.plottool.nx_helpers.dump_nx_ondisk(graph, fpath)[source]
wbia.plottool.nx_helpers.ensure_nonhex_color(orig_color)[source]
wbia.plottool.nx_helpers.format_anode_pos(xy, pin=True)[source]
wbia.plottool.nx_helpers.get_explicit_graph(graph)[source]
Parameters

graph (nx.Graph) –

wbia.plottool.nx_helpers.get_nx_layout(graph, layout, layoutkw=None, verbose=None)[source]
wbia.plottool.nx_helpers.make_agraph(graph_)[source]
wbia.plottool.nx_helpers.netx_draw_images_at_positions(img_list, pos_list, size_list, color_list, framewidth_list)[source]

Overlays images on a networkx graph

References

https://gist.github.com/shobhit/3236373 http://matplotlib.org/examples/pylab_examples/demo_annotation_box.html http://stackoverflow.com/questions/11487797/mpl-overlay-small-image http://matplotlib.org/api/text_api.html http://matplotlib.org/api/offsetbox_api.html

wbia.plottool.nx_helpers.nx_agraph_layout(orig_graph, inplace=False, verbose=None, return_agraph=False, groupby=None, **layoutkw)[source]

Uses graphviz and custom code to determine position attributes of nodes and edges.

Parameters

groupby (str) – if not None then nodes will be grouped by this attributes and groups will be layed out separately and then stacked together in a grid

Ignore:

orig_graph = graph graph = layout_graph

References

http://www.graphviz.org/content/attrs http://www.graphviz.org/doc/info/attrs.html

CommandLine:

python -m wbia.plottool.nx_helpers nx_agraph_layout –show

Doctest:
>>> # FIXME failing-test (22-Jul-2020) This test is failing and it's not clear how to fix it
>>> # xdoctest: +SKIP
>>> # xdoctest: +REQUIRES(module:pygraphviz)
>>> from wbia.plottool.nx_helpers import *  # NOQA
>>> import wbia.plottool as pt
>>> import networkx as nx
>>> import utool as ut
>>> n, s = 9, 4
>>> offsets = list(range(0, (1 + n) * s, s))
>>> node_groups = [ut.lmap(str, range(*o)) for o in ut.itertwo(offsets)]
>>> edge_groups = [ut.combinations(nodes, 2) for nodes in node_groups]
>>> graph = nx.Graph()
>>> [graph.add_nodes_from(nodes) for nodes in node_groups]
>>> [graph.add_edges_from(edges) for edges in edge_groups]
>>> for count, nodes in enumerate(node_groups):
...     nx.set_node_attributes(graph, name='id', values=ut.dzip(nodes, [count]))
>>> layoutkw = dict(prog='neato')
>>> graph1, info1 = nx_agraph_layout(graph.copy(), inplace=True, groupby='id', **layoutkw)
>>> graph2, info2 = nx_agraph_layout(graph.copy(), inplace=True, **layoutkw)
>>> graph3, _ = nx_agraph_layout(graph1.copy(), inplace=True, **layoutkw)
>>> nx.set_node_attributes(graph1, name='pin', values='true')
>>> graph4, _ = nx_agraph_layout(graph1.copy(), inplace=True, **layoutkw)
>>> if pt.show_was_requested():
>>>     pt.show_nx(graph1, layout='custom', pnum=(2, 2, 1), fnum=1)
>>>     pt.show_nx(graph2, layout='custom', pnum=(2, 2, 2), fnum=1)
>>>     pt.show_nx(graph3, layout='custom', pnum=(2, 2, 3), fnum=1)
>>>     pt.show_nx(graph4, layout='custom', pnum=(2, 2, 4), fnum=1)
>>>     pt.show_if_requested()
>>> g1pos = nx.get_node_attributes(graph1, 'pos')['1']
>>> g4pos = nx.get_node_attributes(graph4, 'pos')['1']
>>> g2pos = nx.get_node_attributes(graph2, 'pos')['1']
>>> g3pos = nx.get_node_attributes(graph3, 'pos')['1']
>>> print('g1pos = {!r}'.format(g1pos))
>>> print('g4pos = {!r}'.format(g4pos))
>>> print('g2pos = {!r}'.format(g2pos))
>>> print('g3pos = {!r}'.format(g3pos))
>>> assert np.all(g1pos == g4pos), 'points between 1 and 4 were pinned so they should be equal'
>>> #assert np.all(g2pos != g3pos), 'points between 2 and 3 were not pinned, so they should be different'

assert np.all(nx.get_node_attributes(graph1, ‘pos’)[‘1’] == nx.get_node_attributes(graph4, ‘pos’)[‘1’]) assert np.all(nx.get_node_attributes(graph2, ‘pos’)[‘1’] == nx.get_node_attributes(graph3, ‘pos’)[‘1’])

wbia.plottool.nx_helpers.parse_aedge_layout_attrs(aedge, translation=None)[source]

parse grpahviz splineType

wbia.plottool.nx_helpers.parse_anode_layout_attrs(anode)[source]
wbia.plottool.nx_helpers.parse_html_graphviz_attrs()[source]
wbia.plottool.nx_helpers.parse_point(ptstr)[source]
wbia.plottool.nx_helpers.patch_pygraphviz()[source]

Hacks around a python3 problem in 1.3.1 of pygraphviz

wbia.plottool.nx_helpers.show_nx(graph, with_labels=True, fnum=None, pnum=None, layout='agraph', ax=None, pos=None, img_dict=None, title=None, layoutkw=None, verbose=None, **kwargs)[source]
Parameters
  • graph (networkx.Graph) –

  • with_labels (bool) – (default = True)

  • fnum (int) – figure number(default = None)

  • pnum (tuple) – plot number(default = None)

  • layout (str) – (default = ‘agraph’)

  • ax (None) – (default = None)

  • pos (None) – (default = None)

  • img_dict (dict) – (default = None)

  • title (str) – (default = None)

  • layoutkw (None) – (default = None)

  • verbose (bool) – verbosity flag(default = None)

Kwargs:

use_image, framewidth, modify_ax, as_directed, hacknoedge, hacknode, arrow_width, fontsize, fontweight, fontname, fontfamilty, fontproperties

CommandLine:

python -m wbia.plottool.nx_helpers show_nx –show python -m dtool –tf DependencyCache.make_graph –show python -m wbia.scripts.specialdraw double_depcache_graph –show –testmode python -m vtool.clustering2 unsupervised_multicut_labeling –show

Example

>>> # ENABLE_DOCTEST
>>> # xdoctest: +REQUIRES(module:pygraphviz)
>>> from wbia.plottool.nx_helpers import *  # NOQA
>>> import networkx as nx
>>> graph = nx.DiGraph()
>>> graph.add_nodes_from(['a', 'b', 'c', 'd'])
>>> graph.add_edges_from({'a': 'b', 'b': 'c', 'b': 'd', 'c': 'd'}.items())
>>> nx.set_node_attributes(graph, name='shape', values='rect')
>>> nx.set_node_attributes(graph, name='image', values={'a': ut.grab_test_imgpath('carl.jpg')})
>>> nx.set_node_attributes(graph, name='image', values={'d': ut.grab_test_imgpath('lena.png')})
>>> #nx.set_node_attributes(graph, name='height', values=100)
>>> with_labels = True
>>> fnum = None
>>> pnum = None
>>> e = show_nx(graph, with_labels, fnum, pnum, layout='agraph')
>>> import wbia.plottool as pt
>>> pt.show_if_requested()

wbia.plottool.other module

wbia.plottool.other.color_orimag(gori, gmag)[source]
wbia.plottool.other.draw_hist_subbin_maxima(hist, centers=None)[source]

wbia.plottool.plot_helpers module

wbia.plottool.plot_helpers.del_plotdat(ax, key)[source]

sets internal property to a matplotlib axis

wbia.plottool.plot_helpers.draw()[source]
wbia.plottool.plot_helpers.ensureqt()
wbia.plottool.plot_helpers.get_bbox_centers(bbox_list)[source]
wbia.plottool.plot_helpers.get_plotdat(ax, key, default=None)[source]

returns internal property from a matplotlib axis

wbia.plottool.plot_helpers.get_plotdat_dict(ax)[source]

sets internal property to a matplotlib axis

wbia.plottool.plot_helpers.get_square_row_cols(nSubplots, max_cols=None, fix=False, inclusive=True)[source]
Parameters
  • nSubplots

  • max_cols (None) –

Returns

(None, None)

Return type

tuple

CommandLine:

python -m wbia.plottool.plot_helpers –test-get_square_row_cols

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plot_helpers import *  # NOQA
>>> # build test data
>>> nSubplots = 9
>>> nSubplots_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> max_cols = None
>>> # execute function
>>> rc_list = [get_square_row_cols(nSubplots, fix=True) for nSubplots in nSubplots_list]
>>> # verify results
>>> result = repr(np.array(rc_list).T)
>>> print(result)
array([[1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3],
       [1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4]])
wbia.plottool.plot_helpers.kp_info(kp)[source]
wbia.plottool.plot_helpers.qt4ensure()[source]
wbia.plottool.plot_helpers.qtensure()[source]
wbia.plottool.plot_helpers.set_plotdat(ax, key, val)[source]

sets internal property to a matplotlib axis

wbia.plottool.plots module

wbia.plottool.plots.colorline(x, y, z=None, cmap=<matplotlib.colors.LinearSegmentedColormap object>, norm=<matplotlib.colors.Normalize object>, linewidth=1, alpha=1.0)[source]

Plot a colored line with coordinates x and y Optionally specify colors in the array z Optionally specify a colormap, a norm function and a line width

References

nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb

CommandLine:

python -m wbia.plottool.plots –test-colorline –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> import wbia.plottool as pt
>>> # build test data
>>> x = np.array([1, 3, 3, 2, 5]) / 5.0
>>> y = np.array([1, 2, 1, 3, 5]) / 5.0
>>> z = None
>>> cmap = df2.plt.get_cmap('hsv')
>>> norm = plt.Normalize(0.0, 1.0)
>>> linewidth = 1
>>> alpha = 1.0
>>> # execute function
>>> pt.figure()
>>> result = colorline(x, y, z, cmap)
>>> # verify results
>>> print(result)
>>> pt.dark_background()
>>> pt.show_if_requested()
wbia.plottool.plots.demo_fonts()[source]
CommandLine:

python -m wbia.plottool.plots demo_fonts –show

References

http://stackoverflow.com/questions/8753835/list-of-fonts-avail-mpl

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> demo_fonts()
>>> ut.quit_if_noshow()
>>> import wbia.plottool as pt
>>> pt.present()
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.plots.draw_hist_subbin_maxima(hist, centers=None, bin_colors=None, maxima_thresh=None, remove_endpoints=True, **kwargs)[source]
Parameters
  • hist (ndarray) –

  • centers (None) –

CommandLine:

python -m wbia.plottool.plots –test-draw_hist_subbin_maxima –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> import wbia.plottool as pt
>>> hist = np.array([    6.73, 8.69, 0.00, 0.00, 34.62, 29.16, 0.00, 0.00, 6.73, 8.69])
>>> centers = np.array([-0.39, 0.39, 1.18, 1.96,  2.75,  3.53, 4.32, 5.11, 5.89, 6.68])
>>> bin_colors = pt.df2.plt.get_cmap('hsv')(centers / vt.TAU)
>>> use_darkbackground = True
>>> maxima_thresh = .8
>>> result = draw_hist_subbin_maxima(hist, centers, bin_colors,
>>>                                  maxima_thresh,
>>>                                  use_darkbackground=use_darkbackground)
>>> print(result)
>>> pt.show_if_requested()
wbia.plottool.plots.draw_histogram(bin_labels, bin_values, xlabel='', ylabel='Freq', xtick_rotation=0, transpose=False, **kwargs)[source]
Parameters
  • bin_labels

  • bin_values

  • xlabel (unicode) – (default = u’’)

  • ylabel (unicode) – (default = u’Freq’)

  • xtick_rotation (int) – (default = 0)

  • transpose (bool) – (default = False)

Kwargs:

fnum, pnum, kind, spread_list, title, titlesize, labelsize, legendsize, ticksize, num_xticks, num_yticks, yticklabels, xticklabels, ytick_rotation, xpad, ypad, xpad_factor, ypad_factor, ypad_high, ypad_low, xpad_high, xpad_low, xscale, yscale, legend_loc, legend_alpha, use_darkbackground, lightbg

CommandLine:

python -m wbia.plottool.plots –exec-draw_histogram –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> bin_labels = ['label1', 'label2']
>>> bin_values = [.4, .6]
>>> xlabel = ''
>>> ylabel = 'Freq'
>>> xtick_rotation = 0
>>> transpose = False  # True
>>> kwargs = dict(use_darkbackground=False)
>>> result = draw_histogram(bin_labels, bin_values, xlabel, ylabel, xtick_rotation, transpose, **kwargs)
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.plots.draw_subextrema(ydata, xdata=None, op='max', bin_colors=None, thresh_factor=None, normalize_x=True, flat=True)[source]
Parameters
  • ydata (ndarray) –

  • xdata (None) –

CommandLine:

python -m wbia.plottool.plots –test-draw_subextrema –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> import vtool as vt
>>> import wbia.plottool as pt
>>> ydata = np.array([    6.73, 8.69, 0.00, 0.00, 34.62, 29.16, 0.01, 0.00, 6.73, 8.69])
>>> xdata = np.array([-0.39, 0.39, 1.18, 1.96,  2.75,  3.53, 4.32, 5.11, 5.89, 6.68])
>>> bin_colors = pt.df2.plt.get_cmap('hsv')(xdata / vt.TAU)
>>> use_darkbackground = True
>>> thresh_factor = .01
>>> op = 'max'
>>> ut.exec_funckw(draw_subextrema, globals())
>>> result = draw_subextrema(ydata, xdata, bin_colors=bin_colors,
>>>                          thresh_factor=thresh_factor, op=op)
>>> print(result)
>>> pt.show_if_requested()
wbia.plottool.plots.draw_time_distribution(unixtime_list, bw=None)[source]
wbia.plottool.plots.draw_time_histogram(unixtime_list, **kwargs)[source]
wbia.plottool.plots.draw_timedelta_pie(timedeltas, bins=None, fnum=None, pnum=(1, 1, 1), label='')[source]
Parameters
  • timedeltas (list) –

  • bins (None) – (default = None)

CommandLine:

python -m wbia.plottool.plots –exec-draw_timedelta_pie –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> timedeltas = np.array([    1.,    14.,    17.,    34.,     4.,    36.,    34.,     2.,
...                         3268.,    34., np.nan,    33.,     5.,     2.,    16.,     5.,
...                           35.,    64.,   299.,    35.,     2.,     5.,    34.,    12.,
...                            1.,     8.,     6.,     7.,    11.,     5.,    46.,    47.,
...                           22.,     3.,  np.nan,    11.], dtype=np.float64) ** 2
>>> bins = None
>>> result = draw_timedelta_pie(timedeltas, bins)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.plots.estimate_pdf(data, bw_factor)[source]
wbia.plottool.plots.get_good_logyscale_kwargs(y_data, adaptive_knee_scaling=False)[source]
wbia.plottool.plots.interval_line_plot(xdata, ydata_mean, y_data_std, color=[1, 0, 0], label=None, marker='o', linestyle='-')[source]
Parameters
  • xdata (ndarray) –

  • ydata_mean (ndarray) –

  • y_data_std (ndarray) –

SeeAlso:

pt.multi_plot (using the spread_list kwarg)

CommandLine:

python -m wbia.plottool.plots –test-interval_line_plot –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> xdata = [1, 2, 3, 4, 5, 6, 7, 8]
>>> ydata_mean = [2, 3, 4, 3, 3, 2, 2, 2]
>>> y_data_std = [1, 2, 1, 1, 3, 2, 2, 1]
>>> result = interval_line_plot(xdata, ydata_mean, y_data_std)
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.plots.interval_stats_plot(param2_stat_dict, fnum=None, pnum=(1, 1, 1), x_label='', y_label='', title='')[source]

interval plot for displaying mean, range, and std

Parameters
  • fnum (int) – figure number

  • pnum (tuple) – plot number

CommandLine:

python -m wbia.plottool.plots –test-interval_stats_plot python -m wbia.plottool.plots –test-interval_stats_plot –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> import wbia.plottool as pt
>>> # build test data
>>> param2_stat_dict = {
...     0.5: dict([('max', 0.0584), ('min', 0.0543), ('mean', 0.0560), ('std', 0.00143),]),
...     0.6: dict([('max', 0.0593), ('min', 0.0538), ('mean', 0.0558), ('std', 0.00178),]),
...     0.7: dict([('max', 0.0597), ('min', 0.0532), ('mean', 0.0556), ('std', 0.00216),]),
...     0.8: dict([('max', 0.0601), ('min', 0.0525), ('mean', 0.0552), ('std', 0.00257),]),
...     0.9: dict([('max', 0.0604), ('min', 0.0517), ('mean', 0.0547), ('std', 0.00300),]),
...     1.0: dict([('max', 0.0607), ('min', 0.0507), ('mean', 0.0541), ('std', 0.00345),])
... }
>>> fnum = None
>>> pnum = (1, 1, 1)
>>> title = 'p vs score'
>>> x_label = 'p'
>>> y_label = 'score diff'
>>> result = interval_stats_plot(param2_stat_dict, fnum, pnum, x_label, y_label, title)
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.plots.is_default_dark_bg()[source]
wbia.plottool.plots.multi_plot(xdata=None, ydata_list=[], **kwargs)[source]

plots multiple lines, bars, etc…

This is the big function that implements almost all of the heavy lifting in this file. Any function not using this should probably find a way to use it. It is pretty general and relatively clean.

Parameters
  • xdata (ndarray) – can also be a list of arrays

  • ydata_list (list of ndarrays) – can also be a single array

Kwargs:
Misc:

fnum, pnum, use_legend, legend_loc

Labels:

xlabel, ylabel, title, figtitle ticksize, titlesize, legendsize, labelsize

Grid:

gridlinewidth, gridlinestyle

Ticks:

num_xticks, num_yticks, tickwidth, ticklength, ticksize

Data:

xmin, xmax, ymin, ymax, spread_list # can append _list to any of these plot_kw_keys = [‘label’, ‘color’, ‘marker’, ‘markersize’,

‘markeredgewidth’, ‘linewidth’, ‘linestyle’]

kind = [‘bar’, ‘plot’, …]

if kind=’plot’:

spread

if kind=’bar’:

stacked, width

References

matplotlib.org/examples/api/barchart_demo.html

CommandLine:

python -m wbia.plottool.plots multi_plot:0 –show python -m wbia.plottool.plots multi_plot:1 –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> xdata = [1, 2, 3, 4, 5]
>>> ydata_list = [[1, 2, 3, 4, 5], [3, 3, 3, 3, 3], [5, 4, np.nan, 2, 1], [4, 3, np.nan, 1, 0]]
>>> kwargs = {'label_list': ['spamΣ', 'eggs', 'jamµ', 'pram'],  'linestyle': '-'}
>>> #fig = multi_plot(xdata, ydata_list, title='$\phi_1(\\vec{x})$', xlabel='\nfds', **kwargs)
>>> fig = multi_plot(xdata, ydata_list, title='ΣΣΣµµµ', xlabel='\nfdsΣΣΣµµµ', **kwargs)
>>> result = ('fig = %s' % (str(fig),))
>>> fig2 = multi_plot([1, 2, 3], [4, 5, 6], fnum=4)
>>> result = ('fig = %s' % (str(fig),))
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> fig = multi_plot([1, 2, 3], [4, 5, 6])
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.plots.plot_densities(prob_list, prob_lbls=None, prob_colors=None, xdata=None, prob_thresh=None, score_thresh=None, figtitle='plot_probabilities', fnum=None, pnum=(1, 1, 1), fill=False, **kwargs)

Input: a list of scores (either chip or descriptor)

Concatenates and sorts the scores Sorts and plots with different types of scores labeled

Parameters
  • prob_list (list) –

  • prob_lbls (None) – (default = None)

  • prob_colors (None) – (default = None)

  • xdata (None) – (default = None)

  • prob_thresh (None) – (default = None)

  • figtitle (str) – (default = ‘plot_probabilities’)

  • fnum (int) – figure number(default = None)

  • pnum (tuple) – plot number(default = (1, 1, 1))

  • fill (bool) – (default = False)

CommandLine:

python -m wbia.plottool.plots –exec-plot_probabilities –show –lightbg

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> prob_list = [[.01, .02, .03, .04, .03, .06, .03, .04]]
>>> prob_lbls = ['prob']
>>> prob_colors = None
>>> xdata = None
>>> prob_thresh = None
>>> figtitle = 'plot_probabilities'
>>> fnum = None
>>> pnum = (1, 1, 1)
>>> fill = True
>>> score_thresh = None
>>> result = plot_probabilities(prob_list, prob_lbls, prob_colors, xdata, prob_thresh, score_thresh, figtitle, fnum, pnum, fill)
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.plots.plot_multiple_scores(known_nd_data, known_target_points, nd_labels, target_label, title=None, use_legend=True, color_list=None, marker_list=None, report_max=True, **kwargs)[source]

Plots nd-data in 2d using multiple contour lines

CommandLine:

python -m wbia.plottool.plots –test-plot_multiple_scores –show

python -m wbia.plottool.plots –exec-plot_rank_cumhist

–adjust=.15 –dpi=512 –figsize=11,4 –clipwhite –dpath ~/latex/crall-candidacy-2015/ –save “figures/tmp.jpg” –diskshow

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> known_nd_data = np.array([[  1,   2,   4,   7,   1,   2,   4,   7,   1,   2,   4,   7,   1,
...                              2,   4,   7,   1,   2,   4,   7],
...                           [ 50,  50,  50,  50, 100, 100, 100, 100, 200, 200, 200, 200, 300,
...                            300, 300, 300, 500, 500, 500, 500]], dtype=np.int64).T
>>> known_target_points = np.array([35, 32, 32, 30, 33, 32, 33, 30, 32, 31, 31, 32, 36, 33, 33, 32, 33,
...                                 33, 32, 31], dtype=np.int64)
>>> label_list = ['custom', 'custom:sv_on=False']
>>> nd_labels = [u'K', u'dsize']
>>> target_label = 'score'
>>> fnum = None
>>> pnum = None
>>> use_legend = True
>>> title = 'test'
>>> result = plot_multiple_scores(known_nd_data, known_target_points, nd_labels, target_label, title=title)
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.plots.plot_pdf(data, draw_support=True, scale_to=None, label=None, color=0, nYTicks=3)[source]
wbia.plottool.plots.plot_probabilities(prob_list, prob_lbls=None, prob_colors=None, xdata=None, prob_thresh=None, score_thresh=None, figtitle='plot_probabilities', fnum=None, pnum=(1, 1, 1), fill=False, **kwargs)[source]

Input: a list of scores (either chip or descriptor)

Concatenates and sorts the scores Sorts and plots with different types of scores labeled

Parameters
  • prob_list (list) –

  • prob_lbls (None) – (default = None)

  • prob_colors (None) – (default = None)

  • xdata (None) – (default = None)

  • prob_thresh (None) – (default = None)

  • figtitle (str) – (default = ‘plot_probabilities’)

  • fnum (int) – figure number(default = None)

  • pnum (tuple) – plot number(default = (1, 1, 1))

  • fill (bool) – (default = False)

CommandLine:

python -m wbia.plottool.plots –exec-plot_probabilities –show –lightbg

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> prob_list = [[.01, .02, .03, .04, .03, .06, .03, .04]]
>>> prob_lbls = ['prob']
>>> prob_colors = None
>>> xdata = None
>>> prob_thresh = None
>>> figtitle = 'plot_probabilities'
>>> fnum = None
>>> pnum = (1, 1, 1)
>>> fill = True
>>> score_thresh = None
>>> result = plot_probabilities(prob_list, prob_lbls, prob_colors, xdata, prob_thresh, score_thresh, figtitle, fnum, pnum, fill)
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.plots.plot_probs(prob_list, prob_lbls=None, prob_colors=None, xdata=None, prob_thresh=None, score_thresh=None, figtitle='plot_probabilities', fnum=None, pnum=(1, 1, 1), fill=False, **kwargs)

Input: a list of scores (either chip or descriptor)

Concatenates and sorts the scores Sorts and plots with different types of scores labeled

Parameters
  • prob_list (list) –

  • prob_lbls (None) – (default = None)

  • prob_colors (None) – (default = None)

  • xdata (None) – (default = None)

  • prob_thresh (None) – (default = None)

  • figtitle (str) – (default = ‘plot_probabilities’)

  • fnum (int) – figure number(default = None)

  • pnum (tuple) – plot number(default = (1, 1, 1))

  • fill (bool) – (default = False)

CommandLine:

python -m wbia.plottool.plots –exec-plot_probabilities –show –lightbg

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> prob_list = [[.01, .02, .03, .04, .03, .06, .03, .04]]
>>> prob_lbls = ['prob']
>>> prob_colors = None
>>> xdata = None
>>> prob_thresh = None
>>> figtitle = 'plot_probabilities'
>>> fnum = None
>>> pnum = (1, 1, 1)
>>> fill = True
>>> score_thresh = None
>>> result = plot_probabilities(prob_list, prob_lbls, prob_colors, xdata, prob_thresh, score_thresh, figtitle, fnum, pnum, fill)
>>> print(result)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.plots.plot_rank_cumhist(cdf_list, label_list, color_list=None, marker_list=None, edges=None, xlabel='', ylabel='cumfreq', use_legend=True, num_xticks=None, kind='bar', **kwargs)[source]

Plots CMC curves TODO rename to plot_cmc

CommandLine:

python -m wbia.plottool.plots –test-plot_rank_cumhist –show

python -m wbia.plottool.plots –exec-plot_rank_cumhist

–adjust=.15 –dpi=512 –figsize=11,4 –clipwhite –dpath ~/latex/crall-candidacy-2015/ –save “figures/tmp.jpg” –diskshow

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> cdf_list = np.array(
>>>     [[ 88,  92,  93,  96,  96,  96,  96,  98,  99,  99, 100, 100, 100],
>>>      [ 79,  82,  82,  85,  86,  87,  87,  87,  88,  89,  90,  90,  90]])
>>> edges = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
>>> label_list = ['custom', 'custom:sv_on=False']
>>> fnum = None
>>> pnum = None
>>> plot_rank_cumhist(cdf_list, label_list, edges=edges, fnum=fnum, pnum=pnum)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.plots.plot_score_histograms(scores_list, score_lbls=None, score_markers=None, score_colors=None, markersizes=None, fnum=None, pnum=(1, 1, 1), title=None, score_label='score', score_thresh=None, overlay_prob_given_list=None, overlay_score_domain=None, logscale=False, histnorm=False, **kwargs)[source]

Accumulates scores into histograms and plots them

CommandLine:

python -m wbia.plottool.plots –test-plot_score_histograms –show

Ignore:
>>> score_label = 'score'

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> rng = np.random.RandomState(seed=0)
>>> tp_support = rng.normal(loc=6.5, size=(256,))
>>> tn_support = rng.normal(loc=3.5, size=(256,))
>>> scores_list = [tp_support, tn_support]
>>> logscale = True
>>> title = 'plot_scores_histogram'
>>> result = plot_score_histograms(scores_list, title=title,
>>>                                logscale=logscale)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
>>> print(result)
wbia.plottool.plots.plot_search_surface(known_nd_data, known_target_points, nd_labels, target_label, fnum=None, pnum=None, title=None)[source]

3D Function

Parameters
  • known_nd_data – should be integral for now

  • known_target_points

  • nd_labels

  • target_label

  • fnum (int) – figure number(default = None)

Returns

ax

Return type

?

CommandLine:

python -m wbia.plottool.plots –exec-plot_search_surface –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> known_nd_data = np.array([x.flatten() for x in np.meshgrid(*[np.linspace(-20, 20, 10).astype(np.int32), np.linspace(-20, 20, 10).astype(np.int32)])]).T
>>> # complicated polynomial target
>>> known_target_points = -.001 * known_nd_data.T[0] ** 4 + .25 * known_nd_data.T[1] ** 2 - .0005 * known_nd_data.T[1] ** 4 + .001 * known_nd_data.T[1] ** 3
>>> nd_labels = ['big-dim', 'small-dim']
>>> target_label = ['score']
>>> fnum = 1
>>> ax = plot_search_surface(known_nd_data, known_target_points, nd_labels, target_label, fnum)
wbia.plottool.plots.plot_sorted_scores(scores_list, score_lbls=None, score_markers=None, score_colors=None, markersizes=None, fnum=None, pnum=(1, 1, 1), logscale=True, figtitle=None, score_label='score', thresh=None, use_stems=None, **kwargs)[source]

Concatenates and sorts the scores Sorts and plots with different types of scores labeled

Parameters
  • scores_list (list) – a list of scores

  • score_lbls (None) –

  • score_markers (None) –

  • score_colors (None) –

  • markersizes (None) –

  • fnum (int) – figure number

  • pnum (tuple) – plot number

  • logscale (bool) –

  • figtitle (str) –

CommandLine:

python -m wbia.plottool.plots –test-plot_sorted_scores –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> rng = np.random.RandomState(seed=0)
>>> tp_support = rng.normal(loc=6.5, size=(256,))
>>> tn_support = rng.normal(loc=3.5, size=(256,))
>>> scores_list = [tp_support, tn_support]
>>> score_lbls = None
>>> score_markers = None
>>> score_colors = None
>>> markersizes = None
>>> fnum = None
>>> pnum = (1, 1, 1)
>>> logscale = True
>>> figtitle = 'plot_sorted_scores'
>>> result = plot_sorted_scores(scores_list, score_lbls, score_markers,
>>>                             score_colors, markersizes, fnum, pnum,
>>>                             logscale, figtitle)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
>>> print(result)
wbia.plottool.plots.plot_stems(x_data, y_data, fnum=None, pnum=(1, 1, 1), **kwargs)[source]

Example

>>> import wbia.plottool as pt
>>> x_data = [1, 1, 2, 3, 3, 3, 4, 4, 5]
>>> y_data = [1, 2, 1, 2, 1, 4, 4, 5, 1]
>>> pt.plots.plot_stems(x_data, y_data)
>>> pt.show_if_requested()
wbia.plottool.plots.set_logyscale_from_data(y_data)[source]
wbia.plottool.plots.word_histogram2(text_list, weight_list=None, **kwargs)[source]
Parameters

text_list (list) –

References

stackoverflow.com/questions/17430105/autofmt-xdate-deletes-x-axis-labels-of-all-subplots

CommandLine:

python -m wbia.plottool.plots –exec-word_histogram2 –show –lightbg

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> text_list = []
>>> item_list = text_list = ['spam', 'eggs', 'ham', 'jam', 'spam', 'spam', 'spam', 'eggs', 'spam']
>>> weight_list = None
>>> #weight_list = [.1, .2, .3, .4, .5, .5, .4, .3, .1]
>>> #text_list = [x.strip() for x in ut.lorium_ipsum().split()]
>>> result = word_histogram2(text_list, weight_list)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
wbia.plottool.plots.wordcloud(text, size=None, fnum=None, pnum=None, ax=None)[source]

References

bioinfoexpert.com/?p=592 sudo pip install git+git://github.com/amueller/word_cloud.git

Parameters
  • text (str or dict) – raw text or dictionary of frequencies

  • fnum (int) – figure number(default = None)

  • pnum (tuple) – plot number(default = None)

CommandLine:

python -m wbia.plottool.plots –exec-wordcloud –show python -m wbia.plottool.plots –exec-wordcloud –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> text = '''
        Normally, Frost-Breath-type cards are only good in aggressive decks,
        but add an Eldrazi Scion into the mix and that all changes. I'm not
        adverse to playing a card that ramps my mana, can trade for an x/1, and
        does so while keeping me alive. I still would rather be beating down if
        I'm including this in my deck, but I think it does enough different
        things at a good rate that you are more likely to play it than not.
        Cards that swing a race this drastically are situationally awesome, and
        getting the Eldrazi Scion goes a long way toward mitigating the cost of
        drawing this when you aren't in a race (which is the reason
        non-aggressive decks tend to avoid this effect).
    '''
>>> fnum = None
>>> pnum = None
>>> result = wordcloud(text, fnum, pnum)
>>> import wbia.plottool as pt
>>> pt.show_if_requested()
>>> print(result)
wbia.plottool.plots.zoom_effect01(ax1, ax2, xmin, xmax, **kwargs)[source]

connect ax1 & ax2. The x-range of (xmin, xmax) in both axes will be marked. The keywords parameters will be used ti create patches.

Parameters
  • ax1 (mpl.axes) – the main axes

  • ax2 (mpl.axes) – the zoomed axes

  • (xmin – the limits of the colored area in both plot axes.

  • xmax) – the limits of the colored area in both plot axes.

Returns

(c1, c2, bbox_patch1, bbox_patch2, p)

Return type

tuple

References

matplotlib.org/users/annotations_guide.html

CommandLine:

python -m wbia.plottool.plots zoom_effect01 –show

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.plots import *  # NOQA
>>> import wbia.plottool as pt
>>> cdf_list = np.array(
>>>     [[10, 15, 40, 42, 50, 88,  92,  93,  96,  96,  96,  96,  98,  99,  99, 100, 100, 100],
>>>      [20, 30, 31, 66, 75, 79,  82,  82,  85,  86,  87,  87,  87,  88,  89,  90,  90,  90]])
>>> edges = list(range(0, len(cdf_list[0]) + 1))
>>> label_list = ['custom', 'custom:sv_on=False']
>>> fnum = 1
>>> numranks = len(cdf_list[0])
>>> top = 3
>>> plot_rank_cumhist(cdf_list, label_list, edges=edges, xmin=.9, num_xticks=numranks, fnum=fnum, pnum=(2, 1, 1), kind='plot', ymin=0, ymax=100)
>>> ax1 = pt.gca()
>>> plot_rank_cumhist(cdf_list.T[0:top].T, label_list, edges=edges[0:top + 1], xmin=.9, num_xticks=top, fnum=fnum, pnum=(2, 1, 2), kind='plot', ymin=0, ymax=100)
>>> ax2 = pt.gca()
>>> xmin = 1
>>> xmax = top
>>> (c1, c2, bbox_patch1, bbox_patch2, p) = zoom_effect01(ax1, ax2, xmin, xmax)
>>> result = ('(c1, c2, bbox_patch1, bbox_patch2, p) = %s' % (ut.repr2((c1, c2, bbox_patch1, bbox_patch2, p)),))
>>> print(result)
>>> ut.quit_if_noshow()
>>> import wbia.plottool as pt
>>> pt.show_if_requested()

wbia.plottool.screeninfo module

wbia.plottool.test_colorsys module

wbia.plottool.test_colorsys.TEST_COLORSYS()[source]

wbia.plottool.test_vtk_poly module

wbia.plottool.test_vtk_poly.rhombic_dodecahedron()[source]
wbia.plottool.test_vtk_poly.rhombicuboctahedron()[source]

wbia.plottool.viz_featrow module

wbia.plottool.viz_featrow.draw_feat_row(chip, fx, kp, sift, fnum, nRows, nCols=None, px=None, prevsift=None, origsift=None, aid=None, info='', type_=None, shape_labels=False, vecfield=False, multicolored_arms=False, draw_chip=False, draw_warped=True, draw_unwarped=True, draw_desc=True, rect=True, ori=True, pts=False, **kwargs)[source]
SeeAlso:

wbia.viz.viz_nearest_descriptors ~/code/wbia/wbia/viz/viz_nearest_descriptors.py

CommandLine:

# Use this to find the fx you want to visualize python -m wbia.plottool.interact_keypoints –test-ishow_keypoints –show –fname zebra.png

# Use this to visualize the featrow python -m wbia.plottool.viz_featrow –test-draw_feat_row –show python -m wbia.plottool.viz_featrow –test-draw_feat_row –show –fname zebra.png –fx=121 –feat-all –no-sift python -m wbia.plottool.viz_featrow –test-draw_feat_row –dpath figures –save ~/latex/crall-candidacy-2015/figures/viz_featrow.jpg

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.viz_featrow import *  # NOQA
>>> import wbia.plottool as pt
>>> # build test data
>>> kpts, vecs, imgBGR = pt.viz_keypoints.testdata_kpts()
>>> chip = imgBGR
>>> print('There are %d features' % (len(vecs)))
>>> fx = ut.get_argval('--fx', type_=int, default=0)
>>> kp = kpts[fx]
>>> sift = vecs[fx]
>>> fnum = 1
>>> nRows = 1
>>> nCols = 2
>>> px = 0
>>> if True:
>>>     from wbia.scripts.thesis import TMP_RC
>>>     import matplotlib as mpl
>>>     mpl.rcParams.update(TMP_RC)
>>> hack = ut.get_argflag('--feat-all')
>>> sift = sift if not ut.get_argflag('--no-sift') else None
>>> draw_desc = sift is not None
>>> kw = dict(
>>>     prevsift=None, origsift=None, aid=None, info='', type_=None,
>>>     shape_labels=False, vecfield=False, multicolored_arms=True,
>>>     draw_chip=hack, draw_unwarped=hack, draw_warped=True, draw_desc=draw_desc
>>> )
>>> # execute function
>>> result = draw_feat_row(chip, fx, kp, sift, fnum, nRows, nCols, px,
>>>                           rect=False, ori=False, pts=False, **kw)
>>> # verify results
>>> print(result)
>>> pt.show_if_requested()
wbia.plottool.viz_featrow.formatdist(val)[source]
wbia.plottool.viz_featrow.precisionstr(c='E', pr=2)[source]

wbia.plottool.viz_image2 module

wbia.plottool.viz_image2.draw_chip_overlay(ax, bbox, theta, text, is_sel)[source]

Draw an annotation around a chip in the image

wbia.plottool.viz_image2.draw_image_overlay(ax, bbox_list=[], theta_list=None, text_list=None, sel_list=None, draw_lbls=True)[source]
wbia.plottool.viz_image2.show_image(img, bbox_list=[], title='', theta_list=None, text_list=None, sel_list=None, draw_lbls=True, fnum=None, annote=True, **kwargs)[source]

Driver function to show images

wbia.plottool.viz_keypoints module

wbia.plottool.viz_keypoints.show_keypoints(chip, kpts, fnum=0, pnum=None, **kwargs)[source]
Parameters
  • chip (ndarray[uint8_t, ndim=2]) – annotation image data

  • kpts (ndarray[float32_t, ndim=2]) – keypoints

  • fnum (int) – figure number(default = 0)

  • pnum (tuple) – plot number(default = None)

Kwargs:

ddd, title, figtitle, interpolation, cmap, heatmap, data_colorbar, darken, update, redraw_image, docla, doclf, projection, sel_fx

CommandLine:

python -m wbia.plottool.viz_keypoints –exec-show_keypoints

Example

>>> # DISABLE_DOCTEST
>>> from wbia.plottool.viz_keypoints import *  # NOQA
>>> import vtool as vt
>>> kpts, vecs, chip = testdata_kpts()
>>> fnum = 0
>>> pnum = None
>>> result = show_keypoints(chip, kpts, fnum, pnum)
>>> print(result)
wbia.plottool.viz_keypoints.testdata_kpts()[source]

Module contents

Wrappers around matplotlib

wbia.plottool.reassign_submodule_attributes(verbose=1)[source]

Updates attributes in the __init__ modules with updated attributes in the submodules.

wbia.plottool.reload_subs(verbose=1)[source]

Reloads wbia.plottool and submodules

wbia.plottool.rrrr(verbose=1)

Reloads wbia.plottool and submodules