xiuminglib.vis package

Submodules

xiuminglib.vis.anim module

xiuminglib.vis.anim.make_anim(imgs, duration=1, outpath=None)[source]

Writes a list of images into an animation.

In most cases, we need to label each image, for which you can use vis.text.put_text().

Parameters:
  • imgs (list(numpy.ndarray or str)) – An image is either a path or an array (mixing ok, but arrays will need to be written to a temporary directory). If array, should be of type uint and of shape H-by-W (grayscale) or H-by-W-by-3 (RGB).
  • duration (float, optional) – Duration of each frame in seconds.
  • outpath (str, optional) – Where to write the output to (a .apng or .gif file). None means os.path.join(const.Dir.tmp, 'make_anim.gif').
Writes
  • An animation of the images.

xiuminglib.vis.general module

This module should be imported before skimage to avoid the matplotlib backend problem.

xiuminglib.vis.general.axes3d_wrapper(*args, func='scatter', labels=None, legend_fontsize=20, legend_loc=0, figsize=(14, 14), figtitle=None, figtitle_fontsize=20, xlabel=None, xlabel_fontsize=20, ylabel=None, ylabel_fontsize=20, zlabel=None, zlabel_fontsize=20, xticks=None, xticks_fontsize=10, xticks_rotation=0, yticks=None, yticks_fontsize=10, yticks_rotation=0, zticks=None, zticks_fontsize=10, zticks_rotation=0, grid=True, views=None, equal_axes=False, outpath=None, **kwargs)[source]

Convinience wrapper for mpl_toolkits.mplot3d.Axes3D functions.

It saves plots directly to the disk without displaying.

Parameters:
  • *args – Positional parameters that the wrapped function takes. See mpl_toolkits.mplot3d.Axes3D.
  • **kwargs – Keyword parameters.
  • func (str, optional) – Which pyplot function to invoke, e.g., 'scatter'.
  • labels (list(str), optional) – Labels for plot objects, to appear in the legend. Use None for no label for a certain object. None means no legend at all.
  • legend_loc (str, optional) – Legend location: 'best', 'upper right', 'lower left', 'right', 'center left', 'lower center', 'upper center', 'center', etc. Effective only when labels is not None.
  • figsize (tuple, optional) – Width and height of the figure in inches.
  • figtitle (str, optional) – Figure title.
  • xlabel (str, optional) – Label of x-axis.
  • ylabel
  • zlabel
  • xticks (array_like, optional) – Tick values of x-axis. None means auto.
  • yticks
  • zticks
  • *_fontsize (int, optional) – Font size.
  • *_rotation (float, optional) – Tick rotation in degrees.
  • grid (bool, optional) – Whether to draw grid.
  • views (list(tuple), optional) – List of elevation-azimuth angle pairs (in degrees). A good set of views is [(30, 0), (30, 45), (30, 90), (30, 135)].
  • equal_axes (bool, optional) – Whether to have the same scale for all axes.
  • outpath (str, optional) – Path to which the visualization is saved to. Should end with '.png' or '.pkl' (for offline interactive viewing). None means os.path.join(const.Dir.tmp, 'axes3d_wrapper.png').
Writes
  • One or multiple (if views is provided) views of the 3D plot.
xiuminglib.vis.general.make_colormap(low, high)[source]

Generates your own colormap for heatmap.

Parameters:
  • low (str or tuple) – Color for the lowest value, such as 'red' or (1, 0, 0).
  • high
Returns:

Generated colormap.

Return type:

matplotlib.colors.LinearSegmentedColormap

xiuminglib.vis.general.pyplot_wrapper(*args, ci=None, func='plot', labels=None, legend_fontsize=20, legend_loc=0, figsize=(14, 14), figtitle=None, figtitle_fontsize=20, xlabel=None, xlabel_fontsize=20, ylabel=None, ylabel_fontsize=20, xticks=None, xticks_locations=None, xticks_fontsize=10, xticks_rotation=0, yticks=None, yticks_locations=None, yticks_fontsize=10, yticks_rotation=0, xlim=None, ylim=None, grid=True, outpath=None, **kwargs)[source]

Convinience wrapper for matplotlib.pyplot functions.

It saves plots directly to the disk without displaying.

Parameters:
  • *args – Positional parameters that the wrapped function takes. See matplotlib.pyplot.
  • **kwargs – Keyword parameters.
  • ci (list(float) or list(list(float)), optional) – Confidence interval for x_i[j] is y_i[j] +/- ci[i][j]. Effective only when func is 'plot'. List of floats for one line, and list of lists of floats for multiple lines.
  • func (str, optional) – Which pyplot function to invoke, e.g., 'plot' or 'bar'.
  • labels (list, optional) – Labels for plot objects, to appear in the legend. None means no label for this object.
  • legend_loc (str, optional) – Legend location: 'best', 'upper right', 'lower left', 'right', 'center left', 'lower center', 'upper center', 'center', etc. Effective only when labels is not None.
  • figsize (tuple, optional) – Width and height of the figure in inches.
  • figtitle (str, optional) – Figure title.
  • xlabel (str, optional) – Label of x-axis.
  • ylabel
  • xticks (array_like, optional) – Tick values of x-axis. None means auto.
  • yticks
  • xticks_locations (array_like, optional) – Locations of the ticks. None means starting from 0 and one next to another.
  • yticks_locations
  • *_fontsize (int, optional) – Font size.
  • *_rotation (float, optional) – Tick rotation in degrees.
  • xlim (list, optional) – Start and end values for x-axis. None means auto.
  • ylim
  • grid (bool, optional) – Whether to draw grid.
  • outpath (str, optional) – Path to which the visualization is saved to. None means os.path.join(const.Dir.tmp, 'pyplot_wrapper.png').
Writes
  • The plot.

xiuminglib.vis.geometry module

xiuminglib.vis.geometry.depth_as_image(depth_map, alpha_map=None, keep_alpha=False, outpath=None)[source]

Visualizes a(n) (aliased) depth map and an (anti-aliased) alpha map as a single depth image.

Output has black background, with bright values for closeness to the camera. If the alpha map is anti-aliased, the result depth map will be nicely anti-aliased.

Parameters:
  • depth_map (numpy.ndarray) – 2D array of (aliased) raw depth values.
  • alpha_map (numpy.ndarray, optional) – 2D array of (anti-aliased) alpha values.
  • keep_alpha (bool, optional) – Whether to keep alpha channel in output.
  • outpath (str, optional) – Path to which the visualization is saved to. None means os.path.join(const.Dir.tmp, 'depth_as_image.png').
Writes
  • The (anti-aliased) depth image.
xiuminglib.vis.geometry.normal_as_image(normal_map, alpha_map=None, keep_alpha=False, outpath=None)[source]

Visualizes the normal map by converting vectors to pixel values.

If not keeping alpha, the background is black, complying with industry standards (e.g., Adobe AE).

Parameters:
  • normal_map (numpy.ndarray) – H-by-W-by-3 array of normal vectors.
  • alpha_map (numpy.ndarray, optional) – H-by-W array of alpha values.
  • keep_alpha (bool, optional) – Whether to keep alpha channel in output.
  • outpath (str, optional) – Path to which the visualization is saved to. None means os.path.join(const.Dir.tmp, 'normal_as_image.png').
Writes
  • The normal image.
xiuminglib.vis.geometry.ptcld_as_isosurf(pts, out_obj, res=128, center=False)[source]

Visualizes point cloud as isosurface of its TDF.

Parameters:
  • pts (array_like) – Cartesian coordinates in object space, of shape N-by-3.
  • out_obj (str) – The output path of the surface .obj.
  • res (int, optional) – Resolution of the TDF.
  • center (bool, optional) – Whether to center these points around object space origin.
Writes
  • The .obj file of the isosurface.

xiuminglib.vis.html module

class xiuminglib.vis.html.HTML(title='Results', bgcolor='black', text_font='roboto', text_color='white')[source]

Bases: object

HTML Builder.

head
Type:str
body
Type:str
tail

Concatenating the three gives the complete file contents, as a string.

Type:str
children

Child elements, such as a table.

Type:dict
__init__(title='Results', bgcolor='black', text_font='roboto', text_color='white')[source]
Parameters:
  • title (str, optional) – Page title.
  • bgcolor (str, optional) – Background color. Supports at least color names (like, 'black') and Hex colors (like '#FFFFFF').
  • text_font (str, optional) – Supported values include 'arial', etc.
  • text_color (str, optional) – Text color.
add_header(text, level=1)[source]
add_table(name=None, header=None, width='100%', border=6)[source]

Adds a table to the HTML’s children.

Parameters:
  • name (str, optional) – Table name to enable easy access: self.children[name].
  • header (list(str), optional) – Table header.
  • width (str, optional) – Table width.
  • border (int, optional) – Border width.
Returns:

Table added.

Return type:

xiuminglib.vis.html.Table

save(index_file)[source]

Saves the generated HTML string to the index file.

Once called, this method also calls all children’s close(), so that everything (e.g., a table) is properly closed.

Parameters:index_file (str) – Path to the generated index.html.
Writes
  • An HTML index file.
class xiuminglib.vis.html.Table(header=None, width='100%', border=6)[source]

Bases: object

HTML Table.

head
Type:str
body
Type:str
tail

Concatenating the three gives the complete file contents, as a string.

Type:str
td

td start string that specifies a uniform style.

Type:str
__init__(header=None, width='100%', border=6)[source]
Parameters:
  • header (list(str), optional) – Table headers.
  • width (str, optional) – Table width.
  • border (int, optional) – Border width.
add_row(media, types, captions=None, media_width=256)[source]

Adds a row to the table.

Parameters:
  • media (list(str)) – Paths to media, or the text to display itself.
  • types (list(str)) – Types for all the media: 'image' or 'text'.
  • captions (list(str), optional) – Media captions to appear below the media.
  • media_width (int, optional) – Media width in pixels.
close()[source]

Closes the table.

Returns:The generated table as a string.
Return type:str

xiuminglib.vis.matrix module

xiuminglib.vis.matrix.matrix_as_heatmap(mat, cmap='viridis', center_around_zero=False, outpath=None, contents_only=False, figtitle=None)[source]

Visualizes a matrix as heatmap.

Parameters:
  • mat (numpy.ndarray) – Matrix to visualize as heatmp. May contain NaN’s, which will be plotted white.
  • cmap (str, optional) – Colormap to use.
  • center_around_zero (bool, optional) – Whether to center colorbar around 0 (so that zero is no color, i.e., white). Useful when matrix consists of both positive and negative values, and 0 means “nothing”. None means default colormap and auto range.
  • outpath (str, optional) – Path to which the visualization is saved to. None means os.path.join(const.Dir.tmp, 'matrix_as_heatmap.png').
  • contents_only (bool, optional) – Whether to plot only the contents (i.e., no borders, axes, etc.). If True, the heatmap will be of exactly the same size as your matrix, useful when you want to plot heatmaps separately and later concatenate them into a single one.
  • figtitle (str, optional) – Figure title. None means no title.
Writes
  • A heatmap of the matrix.
xiuminglib.vis.matrix.matrix_as_heatmap_complex(*args, **kwargs)[source]

Wraps matrix_as_heatmap() for complex number support.

Just pass in the parameters that matrix_as_heatmap() takes. '_mag' and '_phase' will be appended to outpath to produce the magnitude and phase heatmaps, respectively. Specifically, magnitude is computed by numpy.absolute(), and phase by numpy.angle().

Writes
  • A magnitude heatmap with '_mag' in its filename.
  • A phase heatmap with '_phase' in its filename.

xiuminglib.vis.plot module

class xiuminglib.vis.plot.Plot(figsize=None, legend_labels=None, legend_fontsize=None, legend_loc='best', figtitle=None, figtitle_fontsize=None, axis_labels=None, axis_label_fontsizes=None, axis_lim=None, axis_ticks=None, axis_tick_labels=None, axis_tick_label_fontsizes=None, axis_tick_label_rotations=None, grid=True)[source]

Bases: object

__init__(figsize=None, legend_labels=None, legend_fontsize=None, legend_loc='best', figtitle=None, figtitle_fontsize=None, axis_labels=None, axis_label_fontsizes=None, axis_lim=None, axis_ticks=None, axis_tick_labels=None, axis_tick_label_fontsizes=None, axis_tick_label_rotations=None, grid=True)[source]

Plotter.

Parameters:
  • figsize (tuple, optional) – Width and height of the figure in inches.
  • legend_labels (list, optional) – Legend labels.
  • legend_fontsize (int, optional) – Legend font size.
  • legend_loc (str, optional) – Legend location: 'best', 'upper right', 'lower left', 'right', 'center left', 'lower center', 'upper center', 'center', etc. Effective only when legend_labels is not None.
  • figtitle (str, optional) – Figure title.
  • figtitle_fontsize (int, optional) – Font size.
  • axis_labels (dict, optional) – Axis labels with 'x', 'y', and/or 'z' as keys.
  • axis_label_fontsizes (dict, optional) – Axis label font sizes with 'x', 'y', and/or 'z' as keys.
  • axis_lim (dict, optional) – Mapping 'x', 'y', or 'z' to an array_like of axis min. and max.
  • axis_ticks (dict, optional) – Axis tick locations, mapping 'x', 'y', or 'z' to an array_like of floats.
  • axis_tick_labels (dict, optional) – Axis tick labels, mapping 'x', 'y', or 'z' to a list of strings.
  • axis_tick_label_fontsizes (dict, optional) – Axis tick label font sizes, mapping 'x', 'y', or 'z' to a float.
  • axis_tick_label_rotations (dict, optional) – Axis tick label rotations in degrees, mapping 'x', 'y', or 'z' to a float.
  • grid (bool, optional) – Whether to draw grid.
bar(y, group_width=0.8, outpath=None)[source]

Bar plot.

Parameters:
  • y (array_like) – N-by-M array of N groups, each with M bars, or N-array of N groups, each with one bar.
  • group_width (float, optional) – Width allocated to each group, shared by all bars within the group.
  • outpath (str, optional) – Path to which the plot is saved. None means a temporary file in const.Dir.tmp.
Returns:

Path to the plot written.

Return type:

str

Writes
  • The bar plot.
line(xy, width=None, marker=None, marker_size=None, outpath=None)[source]

Line/curve plot.

Parameters:
  • xy (array_like) – N-by-M array of N x-values (first column) and their corresponding y-values (the remaining M-1 columns).
  • width (float, optional) – Line width.
  • marker (str, optional) – Marker.
  • marker_size (float, optional) – Marker size.
  • outpath (str, optional) – Path to which the plot is saved. None means a temporary file in const.Dir.tmp.
Returns:

Path to the plot written.

Return type:

str

Writes
  • The line plot.
scatter3d(xyz, colors=None, size=None, equal_axes=False, views=None, outpath=None)[source]

3D scatter plot.

Parameters:
  • xyz (array_like) – N-by-3 array of N points.
  • colors (array_like or list(str) or str, optional) – If N-array, these values are colormapped. If N-list, its elements should be color strings. If a single color string, all points use that color.
  • size (int, optional) – Scatter size.
  • equal_axes (bool, optional) – Whether to have the same scale for all axes.
  • views (list(tuple), optional) – List of elevation-azimuth angle pairs (in degrees). A good set of views is [(30, 0), (30, 45), (30, 90), (30, 135)].
  • outpath (str, optional) – Path to which the plot is saved. None means a temporary file in const.Dir.tmp.
Returns:

Path to the plot written.

Return type:

str

Writes
  • One or multiple (if views is provided) views of the 3D plot.

xiuminglib.vis.pt module

xiuminglib.vis.pt.scatter_on_img(pts, im, size=2, bgr=(0, 0, 255), outpath=None)[source]

Plots scatter on top of an image or just a white canvas, if you are being creative by feeding in just a white image.

Parameters:
  • pts (array_like) –

    Pixel coordinates of the scatter point(s), of length 2 for just one point or shape N-by-2 for multiple points. Convention:

    +-----------> dim1
    |
    |
    |
    v dim0
    
  • im (numpy.ndarray) – Image to scatter on. H-by-W (grayscale) or H-by-W-by-3 (RGB) arrays of unint type.
  • size (float or array_like(float), optional) – Size(s) of scatter points. If array_like, must be of length N.
  • bgr (tuple or array_like(tuple), optional) – BGR color(s) of scatter points. Each element \(\in [0, 255]\). If array_like, must be of shape N-by-3.
  • outpath (str, optional) – Path to which the visualization is saved to. None means os.path.join(const.Dir.tmp, 'scatter_on_img.png').
Writes
  • The scatter plot overlaid over the image.
xiuminglib.vis.pt.uv_on_texmap(uvs, texmap, ft=None, outpath=None, max_n_lines=None, dotsize=4, dotcolor='r', linewidth=1, linecolor='b')[source]

Visualizes which points on texture map the vertices map to.

Parameters:
  • uvs (numpy.ndarray) – N-by-2 array of UV coordinates. See xiuminglib.blender.object.smart_uv_unwrap() for the UV coordinate convention.
  • texmap (numpy.ndarray or str) – Loaded texture map or its path. If numpy.ndarray, can be H-by-W (grayscale) or H-by-W-by-3 (color).
  • ft (list(list(int)), optional) – Texture faces used to connect the UV points. Values start from 1, e.g., '[[1, 2, 3], [], [2, 3, 4, 5], ...]'.
  • outpath (str, optional) – Path to which the visualization is saved to. None means os.path.join(const.Dir.tmp, 'uv_on_texmap.png').
  • max_n_lines (int, optional) – Plotting a huge number of lines can be slow, so set this to uniformly sample a subset to plot. Useless if ft is None.
  • dotsize (int or list(int), optional) – Size(s) of the UV dots.
  • dotcolor (str or list(str), optional) – Their color(s).
  • linewidth (float, optional) – Width of the lines connecting the dots.
  • linecolor (str, optional) – Their color.
Writes
  • An image of where the vertices map to on the texture map.

xiuminglib.vis.text module

xiuminglib.vis.text.put_text(img, text, label_top_left_xy=None, font_size=None, font_color=(1, 0, 0), font_ttf=None)[source]

Puts text on image.

Parameters:
  • img (numpy.ndarray) – Should be of type uint and of shape H-by-W (grayscale) or H-by-W-by-3 (RGB).
  • text (str) – Text to be written on the image.
  • label_top_left_xy (tuple(int), optional) – The XY coordinate of the label’s top left corner.
  • font_size (int, optional) – Font size.
  • font_color (tuple(float), optional) – Font RGB, normalized to \([0,1]\). Defaults to red.
  • font_ttf (str, optional) – Path to the .ttf font file. Defaults to Arial.
Returns:

The modified image with text.

Return type:

numpy.ndarray

xiuminglib.vis.text.text_as_image(text, imsize=256, thickness=2, dtype='uint8', outpath=None, quiet=False)[source]

Rasterizes a text string into an image.

The text will be drawn in white to the center of a black canvas. Text size gets automatically figured out based on the provided thickness and image size.

Parameters:
  • text (str) – Text to be drawn.
  • imsize (float or tuple(float), optional) – Output image height and width.
  • thickness (float, optional) – Text thickness.
  • dtype (str, optional) – Image type.
  • outpath (str, optional) – Where to dump the result to. None means returning instead of writing it.
  • quiet (bool, optional) – Whether to refrain from logging. Effective only when outpath is not None.
Returns or Writes
  • An image of the text.

xiuminglib.vis.video module

xiuminglib.vis.video.make_comparison_video(imgs1, imgs2, bar_width=4, bar_color=(1, 0, 0), sweep_vertically=False, sweeps=1, label1='', label2='', font_size=None, font_ttf=None, label1_top_left_xy=None, label2_top_left_xy=None, **make_video_kwargs)[source]

Writes two lists of images into a comparison video that toggles between two videos with a sweeping bar.

Parameters:
  • imgs? (list(numpy.ndarray)) – Each image should be of type uint8 or uint16 and of shape H-by-W (grayscale) or H-by-W-by-3 (RGB).
  • bar_width (int, optional) – Width of the sweeping bar.
  • bar_color (tuple(float), optional) – Bar and label RGB, normalized to \([0,1]\). Defaults to red.
  • sweep_vertically (bool, optional) – Whether to sweep vertically or horizontally.
  • sweeps (int, optional) – Number of sweeps.
  • label? (str, optional) – Label for each video.
  • font_size (int, optional) – Font size.
  • font_ttf (str, optional) – Path to the .ttf font file. Defaults to Arial.
  • label?_top_left_xy (tuple(int), optional) – The XY coordinate of the label’s top left corner.
  • make_video_kwargs (dict, optional) – Keyword arguments for make_video().
Writes
  • A comparison video.
xiuminglib.vis.video.make_video(imgs, fps=24, outpath=None, method='matplotlib', dpi=96, bitrate=-1)[source]

Writes a list of images into a grayscale or color video.

Parameters:
  • imgs (list(numpy.ndarray)) – Each image should be of type uint8 or uint16 and of shape H-by-W (grayscale) or H-by-W-by-3 (RGB).
  • fps (int, optional) – Frame rate.
  • outpath (str, optional) – Where to write the video to (a .mp4 file). None means os.path.join(const.Dir.tmp, 'make_video.mp4').
  • method (str, optional) – Method to use: 'matplotlib', 'opencv', 'video_api'.
  • dpi (int, optional) – Dots per inch when using matplotlib.
  • bitrate (int, optional) – Bit rate in kilobits per second when using matplotlib; reasonable values include 7200.
Writes
  • A video of the images.