skrt.better_viewer package

Submodules

Module contents

New version of QuickViewer that uses the scikit-rt Image class.

class skrt.better_viewer.BetterViewer(images=None, title=None, mask=None, dose=None, rois=None, grid=None, jacobian=None, df=None, share_slider=True, orthog_view=False, plots_per_row=None, match_axes=None, scale_in_mm=True, comparison=None, comparison_only=False, cb_splits=8, overlay_opacity=0.5, overlay_legend=False, legend_bbox_to_anchor=None, legend_loc='lower left', translation=False, translation_write_style=None, show_mse=False, dta_tolerance=5, dta_crit=1, diff_crit=15, suptitle=None, show=True, include_image=False, no_ui=None, ylabel_first_only=True, yticks_first_only=False, ytick_labels_first_only=True, colorbar_last_only=True, zoom=None, zoom_ui=None, **kwargs)

Bases: object

Display multiple SingleViewers and/or comparison images.

__init__(images=None, title=None, mask=None, dose=None, rois=None, grid=None, jacobian=None, df=None, share_slider=True, orthog_view=False, plots_per_row=None, match_axes=None, scale_in_mm=True, comparison=None, comparison_only=False, cb_splits=8, overlay_opacity=0.5, overlay_legend=False, legend_bbox_to_anchor=None, legend_loc='lower left', translation=False, translation_write_style=None, show_mse=False, dta_tolerance=5, dta_crit=1, diff_crit=15, suptitle=None, show=True, include_image=False, no_ui=None, ylabel_first_only=True, yticks_first_only=False, ytick_labels_first_only=True, colorbar_last_only=True, zoom=None, zoom_ui=None, **kwargs)

Display one or more interactive images.

Parameters:

imagesstring/Image/np.ndarray/list, default=None

Source(s) of image data for each plot. If multiple plots are to be shown, this must be a list. Image sources can be Image objects, or any of the valid sources for creating an Image object, including:

  1. The path to a NIfTI or DICOM file;

  2. The path to a file containing a NumPy array;

  3. A NumPy array;

  4. An Image object.

titlestring or list of strings, default=None

Custom title(s) to use for the image(s) to be displayed. If the number of titles given, n, is less than the number of images, only the first n figures will be given custom titles. If any titles are None, the name of the image file will be used as the title.

maskImage/list/ROI/str/StructureSet, default=None

Image object representing a mask or a source from which an Image object can be initialised. In addition to the sources accepted by the Image constructor, the source may be an ROI, a list of ROIs or a StructureSet. In the latter cases, the mask image is derived from the ROI mask(s).

dosestring/nifti/array/list, default=None

Source(s) of dose field array(s) to overlay on each plot (see valid image sources for <images>).

roisstr/list/dict, default=None

Locations of files from which to load ROIs. This argument can be any of:

  1. String:

    1. The path to a NIfTI file containing an ROI mask;

    2. The path to a DICOM file containing ROI contours;

    3. A wildcard matching one or more of the above file types;

    4. The path to a directory containing NIfTI or DICOM files;

    5. A wildcard matching one or more directories containing NIfTI or DICOM files.

    If the string is found to match a directory, the ROIs from all NIfTI or DICOM files inside that directory will be loaded.

    ROI names will be inferred from the filenames (NIfTI) or the ROI names inside the file (DICOM) unless the user indicates otherwise in the <roi_names> parameter; e.g. an ROI taken from a file called ‘right_parotid.nii.gz’ would automatically be called ‘right parotid’ in QuickViewer.

    If multiple loaded ROIs have the same names, QuickViewer will attempt to label each with a unique name in the UI:

    • If two ROIs named ‘heart’ are loaded from different directories dir1 and dir2, these will be labelled ‘Heart (dir1)’ and ‘Heart (dir2) in the UI.

    • If two ROIs named ‘heart’ are loaded from different files, file1.nii and file2.nii, these will be labelled ‘Heart (file1.nii)’ and ‘Heart (file2.nii)’ in the UI.

    However, if the <legend> option is used, the ROIs will be labelled with the same name in the figure legend. See the labelling option below in part (3) or the <roi_names> option for more customisation.

  2. List:

    1. A list of any of the strings described above; all ROI files found will be loaded.

    2. A list of pairs of paths to files containing ROIs to be compared to one another (see the <roi_comparison> option).

  3. Dict:

    ROI filepaths can be nested inside a dictionary, where the keys are labels which the user wishes to use to refer to ROIs in those files, and the values are any of the options listed above (except 2b).

    The label will be displayed in parentheses next to the ROIs names in the QuickViewer UI and ROI legend.

    The <roi_names> and <roi_options> arguments can also be nested inside a dictionary if the user wants to apply different name and color options to the ROIs associated with different labels.

By default, each NIfTI file will be assumed to contain a single ROI. To load multiple label masks from a single NIfTI file, add the string ‘multi:’ before the filepath, e.g.:

  • rois=’multi:my_file.nii’

or alternatively use the multi_rois parameter.

roi_names : dict, default=None

rois_to_keep : list, default=None

rois_to_remove : list, default=None

roi_info : bool/list, default=False

If True, a table containg the volumes and centroids of each plotted ROI will be displayed below the plot. Can also be set to a list of ROI metrics - see skrt.structures.ROI.get_geometry() documentation for list of available metrics. If roi_info=True, metrics will be set to [“volume”, “centroid”, “area”].

compare_rois : bool/list, default=False

If True, a table containg the dice scores and centroid distances between ROIs will be displayed below the plot. Can also be set to a list of ROI comparison metrics - see skrt.structures.ROI.get_comparison() documentation for list of available metrics.

show_compared_rois_onlybool, default=True

If compare_rois is True, only ROIs that are being compared will be displayed. E.g. if two StructureSets are given in <rois> that have some ROIs with matching names, only those with matching names will be shown.

multi_rois : str/list/dict, default=None

Path(s) to file(s) from which to load multiple ROI label masks per file.

Same as the <rois> argument, except each file specified in the <multi_rois> argument will be checked for different labels instead of being treated as a binary mask.

This can be used in conjunction with <rois> to load single masks from some files and multiple masks from others.

roi_consensusbool, default=False

If True, add the option to plot the consensus of ROIs rather than plotting individually. Only works if a single StructureSet is provided for each image.

gridstring/nifti/array/list, default=None

Source(s) of grid array(s) to overlay on each plot (see valid image sources for <images>).

jacobianstring/nifti/array/list, default=None

Source(s) of jacobian determinant array(s) to overlay on each plot (see valid image sources for <images>).

dfstring/nifti/array/list, default=None

Source(s) of deformation field(s) to overlay on each plot (see valid image sources for <images>).

share_sliderbool, default=True

If True and all displayed images are in the same frame of reference, a single slice slider will be shared between all plots. If plots have different frames of reference, this option will be ignored.

orthog_viewbool, default=False

If True, an orthgonal view with an indicator line showing the current slice will be displayed alongside each plot.

plots_per_rowint, default=None

Number of plots to display before starting a new row. If None, all plots will be shown on a single row.

match_axesint/str, default=None

Method for adjusting axis limits. Can either be:

  • An integer n, where 0 < n < number of plots, or n is -1. The axes of all plots will be adjusted to be the same as those of plot n.

  • ‘all’/’both’: axes for all plots will be adjusted to cover the maximum range of all plots.

  • ‘overlap’: axes for all plots will be adjusted to just show the overlapping region.

  • ‘x’: same as ‘all’, but only applied to the current x axis. whatever the x axis is in the current view.

  • ‘y’: same as ‘all’, but only applied to the current y axis.

scale_in_mmbool, default=True

If True, the axis scales will be shown in mm instead of array indices.

show_cbbool, default=False

If True, a chequerboard image will be displayed. This option will only be applied if the number of images in <images> is 2.

show_overlaybool, default=False

If True, a blue/red transparent overlaid image will be displayed. This option will only be applied if the number of images in <images> is 2.

show_diffbool, default=False

If True, a the difference between two images will be shown. This option will only be applied if the number of images in <images> is 2.

comparisonbool/str/list, default=None

Indicator for which type(s) of comparison image(s) to show. If True or ‘all’, a comparison image control by a dropdown menu with all comparison options will be loaded. Can also be a single string or list containing any combination of ‘all’, ‘chequerboard’, ‘overlay’, and ‘difference’ to plot those images in the desired order.

comparison_onlybool, False

If True, only comparison images (overlay/chequerboard/difference) will be shown. If no comparison options are selected, this parameter will be ignored.

cb_splitsint, default=8

Number of sections to show for chequerboard image. Minimum = 1 (corresponding to no chequerboard). Can later be changed interactively.

overlay_opacityfloat, default=0.5

Initial opacity of overlay. Can later be changed interactively.

overlay_legendbool default=False

If True, a legend will be displayed on the overlay plot.

legend_bbox_to_anchorstr, default=None

Bounding box relative to which any legends are to be positioned. Must be a valid matplotlib legend bbox_to_anchor. See: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html

legend_locstr, default=’lower left’

Location for any legends being displayed. Must be a valid matplotlib legend location.

translationbool, default=False

If True, widgets will be displayed allowing the user to apply a translation to the image. Note that this will not change the Image object itself, only the image displayed in the viewer.

translation_write_stylebool, default=”normal”

Method for writing translations to a file. Can either be “normal” (will write x, y, z translations) or the name of a registration engine (will shift translations in a registration transform file). For historical reasons, “shift” is accepted as a synonym for “elastix” as registration engine.

show_msestr, default=None

Color for annotation of mean-squared-error if using comparison images. If None, no annotation will be added. Can be set to ‘True’ to use default colour (white).

dta_tolerancefloat, default=5

Tolerance to use when computing distance-to-agreement.

dta_critfloat, default=1

Critical value of distance-to-agreement to use when computing gamma index.

diff_critfloat, default=15

Critical value of difference to use when computing gamma index.

suptitlestring, default=None

Global title for all subplots. If None, no suptitle will be added.

showbool, default=True

If True, the plot will be displayed when the QuickViewer object is created. Otherwise, the plot can be displayed later via QuickViewer.show().

Keyword arguments:

timeseriesstr/list/dict, default=None

A series of image files taken at difference dates. This can be:

  1. The path to a directory containing multiple image files/ multiple directories each containing one image file;

  2. A list of paths to image files;

  3. A dict of dates and image files.

In cases (a) and (b), QuickViewer will attempt to infer the date first from the directory name, then from the filename if no valid date is found within the directory name. The date is taken from the first unbroken string of numbers that can be successfully parsed with dateutil.parser.

init_viewstring/None, default=’x-y’

Orientation (‘x-y’, ‘x-z’, ‘y-x’, ‘y-z’, ‘z-x’ , ‘z-y’) at which to initially display the image(s). If None, the initial view is chosen to match the image orienation.

init_sliceinteger, default=None

Slice number in the initial orientation direction at which to display the first image (can be changed interactively later). If None, the central slice will be displayed. Takes precedence over <init_idx>.

init_idxinteger, default=None

Index in the initial orienation direction of the slice in the array to plot.

init_posfloat, default=None

Position in mm of the first slice to display. This will be rounded to the nearest slice. If <init_pos> and <init_idx> are both given, <init_pos> will override <init_idx> only if <scale_in_mm> is True.

flattenbool/str, default=False

If True, images will be flattened across all slices in the orientation specified in <view>. If specified as a string, this should be the name of a numpy function with which to combine array values along an axis, for example “sum”, “max”, “min”, “mean”. Otherwise, values are combined by summing. A flattened image in a given view will be the same for all values of slice number, slice index and slice position, but the slices shown for (unflattened) overlays will change. Flattening isn’t applied to comparison images.

intensityfloat/tuple/str, default=None

Intensity central value or range thresholds at which to display the image. Can later be changed interactively. If a single value is given, the Intensity range will be centred at this value with width given by <intensity_width>. If a tuple is given, the intensity range will be set to the two values in the tuple. If None, default intensity will be taken from the image itself. If ‘auto’, lower and upper bounds are set to the minimum and maximum intensity in the image.

intensity_widthfloat, default=500

Initial width of the intensity window. Only used if <intensity> is a single value.

intensity_limitstuple, default=None

Full range to use for the intensity slider. Can also set to ‘auto’ to detect min and max intensity in the image. Defaults to (-2000, 2000) for Image objects and to ‘auto’ otherwise (for example, for Dose objects).

intensity_stepfloat, default=None

Step size to use for the intensity slider. Defaults to 1 if the maximum intensity is >= 10, otherwise 0.1.

figsizefloat/tuple, default=5

Height of the displayed figure in inches; figure width will be automatically generated from this. If None, the value in _default_figsize is used. Can also be a tuple containing (width, height) in inches in order to set width and height manually.

xlimtuple, default=None

Custom limits for the x axis. If one of the values in the tuple is None, the default x limits will be used.

ylimtuple, default=None

Custom limits for the y axis. If one of the values in the tuple is None, the default y limits will be used.

zlimtuple, default=None

Custom limits for the z axis. If one of the values in the tuple is None, the default z limits will be used.

cmapstr, default=None

Matplotlib colormap to use for image plotting. Supercedes any cmap included in <mpl_kwargs>.

colorbarint/bool, default=False

Indicate whether to display colour bar(s): - 1 or True: colour bar for main image; - 2: colour bars for main image and for any associated image or overlay; - 0 or False: no colour bar.

colorbar_last_onlybool, default=True

If True, and multiple plots are to be drawn, colorbar is set to False for all plots except the last.

colorbar_labelstr, default=None

Label for the colorbar and range slider. If None, will default to either ‘intensity’ if an image file is given, or ‘Dose (Gy)’ if a dose file is given without an image.

clb_kwargsdict, default=None

Dictionary of keyword arguments to pass to pyplot.colorbar(). For information on available keyword arguments, see: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.colorbar.html#matplotlib.pyplot.colorbar

clb_label_kwargsdict, default=None

Dictionary of keyword arguments to pass to colorbar.set_label(). For information on available keyword arguments, see: https://matplotlib.org/stable/api/colorbar_api.html#matplotlib.colorbar.Colorbar.set_label

xlabelstr, default=None

Custom label for the x axis. If None, the label is set to be the coordinate axis and units, for example ‘x (mm)’. If False or ‘’, the x axis will not be labelled.

no_xlabelbool, default=False

If True, the x axis will not be labelled.

xtickstuple/dict, default=None

Tick locations and custom tick labels for the x axis. Locations and labels are specified via a tuple of values, or a dictionary of key-value pairs, that can be passed to matplotlib.axes.Axes.set_x_ticks(), for example:

  • xticks=((1, 5), (“label1”, “label2”))

  • xticks={“ticks”: (1, 5), “labels”: (“label1”, “label2”)}

For additional values that can be passed, see:

https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_xticks.html

Disregarded if None, if <no_xticks> is True, or if <no_xtick_labels> is True.

no_xticksbool, default=False

If True, ticks and tick labels on the x axis will not be shown.

no_xtick_labelsbool, default=False

If True ticks on the x axis will not be labelled. Disregarded if <no_xticks> is True.

ylabelstr, default=None

Custom label for the y axis. If None, the label is set to be the coordinate axis and units, for example ‘y (mm)’. If False or ‘’, the x axis will not be labelled.

no_ylabelbool, default=False

If True, the y axis will not be labelled.

ytickstuple/dict, default=None

Tick locations and custom tick labels for the y axis. Locations and labels are specified via a tuple of values, or a dictionary of key-value pairs, that can be passed to matplotlib.axes.Axes.set_y_ticks(), for example:

  • yticks=((1, 5), (“label1”, “label2”))

  • yticks={“ticks”: (1, 5), “labels”: (“label1”, “label2”)}

For additional values that can be passed, see:

https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_yticks.html

Disregarded if None, if <no_yticks> is True, or if <no_ytick_labels> is True.

no_yticksbool, default=False

If True, ticks and tick labels on the y axis will not be shown.

no_ytick_labelsbool, default=False

If True ticks on the y axis will not be labelled. Disregarded if <no_yticks> is True.

ylabel_first_onlybool, default=True

If True, and multiple plots are to be displayed, the y axis will be labelled only for the first plot only. If <no_ylabel> is True, the y axis won’t be labelled for any plot.

yticks_first_onlybool, default=False

If True, and multiple plots are to be displayed, ticks on the y axis will be shown for the first plot only. If <no_yticks> is True, ticks on the y axis won’t be shown for any plot.

ytick_labels_first_onlybool, default=True

If True, and multiple plots are to be displayed, ticks on the y axis will be labelled only for the first plot only. If <no_ytick_labels> is True, ticks on the y axis won’t be labelled for any plot.

mpl_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.pyplot.imshow for the main image.See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html for options. Some useful keywords are:

  • ‘cmap’: colormap (default=’gray’).

  • ‘interpolation’: interpolation method (default=’antialiased’)

dose_opacityfloat, default=0.5

Initial opacity of the overlaid dose field. Can later be changed interactively.

dose_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.pyplot.imshow for the dose image. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html for options. Some useful keywords are:

  • ‘cmap’: colormap (default=’jet’).

  • ‘interpolation’: interpolation method (default=’antialiased’)

dose_rangelist, default=None

Min and max dose range to plot. This can also be set via the ‘vmin’ and ‘xmax’ keys in <dose_kwargs>; <dose_range> will take precedence if set.

dose_cmapstr, default=’jet’

Matplotlib colormap to use for dose field plotting. Supercedes any cmap in <dose_kwargs>

maskedbool, default=True

If True and a mask is specified, the image is masked.

invert_maskbool, default=False

If True, any masks applied will be inverted.

mask_colormatplotlib color, default=’black’

color in which to display masked areas.

mask_thresholdfloat, default=0.5

Threshold on mask array; voxels with values below this threshold will be masked (or values above, if <invert_mask> is True).

grid_opacityfloat, default=1.0

Initial opacity of the overlaid grid. Can later be changed interactively.

grid_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.pyplot.imshow for the grid. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html for options.

jacobian_opacityfloat, default=0.8

Initial opacity of the overlaid jacobian determinant. Can later be changed interactively.

jacobian_rangelist, default=None

Min and max jacobian value to plot. This can also be set via the ‘vmin’ and ‘xmax’ keys in <jacobian_kwargs>; <jacobian_range> will take precedence if set. If None, the values of jacobian._default_vmin and jacobian._default_vmax are used.

jacobian_cmapstr, default=None

Matplotlib colormap to use for jacobian plotting. Supercedes any cmap in <jacobian_kwargs>. If None, the value of jacobian._default_cmap is used.

jacobian_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.pyplot.imshow for the jacobian determinant. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html for options. Some useful keywords are:

  • ‘cmap’: colormap (default=’seismic’).

  • ‘interpolation’: interpolation method (default=’antialiased’)

df_plot_typestr, default=’quiver’

Option for initial plotting of deformation field. Can be ‘quiver’, ‘grid’, ‘x-displacement’, ‘y-displacement’, ‘z-displacement’, ‘3d-displacement’, or ‘none’. Can later be changed interactively. All quantities relate to the mapping of points from fixed image to moving image in image registration.

df_spacingint/tuple, default=30

Spacing between arrows on the quiver plot/gridlines on the grid plot of a deformation field. Can be a single value for spacing in all directions, or a tuple with values for (x, y, z). Dimensions are mm if <scale_in_mm> is True, or voxels if <scale_in_mm> is False.

df_opacityfloat, default=0.5

Initial opacity of the overlaid deformation field. Can later be changed interactively.

df_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib when plotting the deformation field. Note that different keyword arguments are accepted for different plot types.

For grid plotting options, see https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html. Some useful keywords are:

  • ‘linewidth’: default=2

  • ‘color’: default=’green’

For quiver plotting options, see https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.quiver.html.

roi_plot_typestr, default=’contour’

Option for initial plot of ROIs. Can be ‘contour’, ‘mask’, ‘filled’, or ‘none’. Can later be changed interactively.

roi_opacityfloat, default=None

Initial opacity of ROIs when plotted as masks or filled contours. Can later be changed interactively. Default=1 for masks, 0.3 for filled contours.

roi_linewidthfloat, default=2

Initial linewidth of ROIs when plotted as contours. Can later be changed interactively.

roi_infobool, default=False

If True, the lengths and volumes of each ROI will be displayed below the plot.

roi_info_dpint, default=2

Number of decimal places to show for floats in ROI info and comparison tables.

length_unitsstr, default=None

Units in which to display the lengths of ROIs if <roi_info> if True. If None, units will be voxels if <scale_in_mm> is False, or mm if <scale_in_mm> is True. Options:

  1. ‘mm’

  2. ‘voxels’

area_unitsstr, default=None

Units in which to display the areas of ROIs if <roi_info> if True. If None, units will be voxels if <scale_in_mm> is False, or mm if <scale_in_mm> is True. Options:

  1. ‘mm’

  2. ‘voxels’

vol_unitsstr, default=None

Units in which to display the volumes of ROIs if <roi_info> if True. If None, units will be voxels if <scale_in_mm> is False, or mm^3 if <scale_in_mm> is True. Options:

  1. ‘mm’ for mm^3

  2. ‘voxels’ for voxels

  3. ‘ml’ for ml

legendbool, default=False

If True, a legend will be displayed for any plot with ROIs.

init_roistr, default=None

If set to an ROI name, the first slice to be displayed will be the central slice of that ROI. This supercedes <init_pos> and <init_slice>.

roi_nameslist/dict, default=None

Custom names for ROIs.

If only one ROI is to be loaded per file, this should be a dictionary where the keys are the desired custom names. The values of the dictionary can be either:

  1. A string containing the path of the file containing the ROI to be renamed;

  2. A string containing the name of the ROI to be renamed within a DICOM file;

  3. A string containing the automatically-generated name of the ROI to be renamed (e.g. if the ROI came from a file right_parotid.nii, its automatically generated name would be ‘right parotid’;

  4. A wildcard matching any of the above;

  5. A list of any of the above.

The list functionality allows the user to list multiple names that should be replaced by a single custom name, e.g. to handle cases where the same ROI may have different names in different DICOM files.

If multiple ROIs are to be loaded from files (i.e. the <multi_rois> parameter is set, or paths in the <rois> parameter are prefixed with ‘multi:’) the <roi_names> parameter can either be:

  1. A list of names, where the Nth name in the list will be applied to the ROI with mask label N in the ROI array; or

  2. A dictionary where the keys are integers such that the name associated with key N will be applied to the ROI with mask label N in the ROI array.

Any of the options described above can also be nested into a dictionary where the keys are labels, if a label dictionary was used to load ROIs in the <rois> parameter. The nested options for each key will only be applied to ROIs whose label is that key.

roi_colorsdict, default=None

A dictionary mapping ROI names to colors in which the ROI will be displayed.

The dictionary keys should be either ROI names or wildcards matching ROI name(s). Note that ROI names are inferred from the ROI’s filename unless otherwise specified in the <roi_names> parameter.

The values of the dictionary can be any matplotlib colorlike object.

The color dictionary can also be nested into a dictionary where the keys are labels, if a label dictionary was used to load ROIs in the <rois> parameter. The nested options for each key will only be applied to ROIs whose label is that key.

rois_as_maskbool, default=True

If True, any loaded ROIs will be used to mask the image and dose field.

compare_roisbool, default=False

If True, slice-by-slice comparison metrics for pairs of ROIs will be displayed below the plot, and compared ROI masks will be plotted with their overlapping region in a different colour.

The ROIs to compare can be set in three different ways:

  1. The user can explicitly indicate which ROIs should be compared by giving a list of lists for the <rois> argument, where each sublist contains exactly 2 filepaths corresponding to a pair of ROIs to be compared (see option 2b for <rois>).

  2. If only two ROIs are found for the filepaths/wildcards given in the <rois> option, these two ROIs will be compared.

  3. Otherwise, QuickViewer will search for pairs of loaded ROIs with the same name (either inferred from the filenames or specified manually by the user in the <roi_names> option). If no ROIs with matching names are found, no comparisons will be performed.

ignore_empty_roisbool, default=False

If True, any loaded ROIs array that only contains zeros will be ignored. If False, the names of empty ROIs will be displayed in the UI with ‘(empty)’ next to them.

ignore_unpaired_roisbool, default=False

If <roi_comparison> is True and ROI pairs are automatically detected based on their names, this parameter determines whether any ROIs for which a matching name is not found should be displayed.

If True, only the pairs of ROIs with matching names will be shown. If False, all loaded ROIs will be shown regardless of whether they have a comparison match.

rois_to_keeplist, default=True

List of ROI names or wildcards matching ROIs that you wish to load. All other ROIs will be ignored.

rois_to_ignorelist, default=True

List of ROI names or wildcards matching ROIs that you wish to ignore.

autoload_roisbool, default=True

If True, ROIs will all be automatically loaded and plotted. If False, all ROIs will be initially turned off and will only be loaded if the user turns them on via the ROI checkbox UI.

continuous_updatebool, default=False

If True, sliders in the UI will continuously update the figure as they are adjusted. Can cause lag.

annotate_slicestr, default=None

Color for annotation of slice number. Can be set to ‘True’ to use default colour (white). If None, no annotation will be added unless viewing outside jupyter, in which case the annotation will be white by default.

save_asstr, default=None

File to which the figure will be saved upon creation. If not None, a text input and button will be added to the UI, allowing the user to save the figure again at a later point.

zoomdouble/tuple, default=None

Amount between by which to zoom in (e.g. zoom=2 would give a 2x zoom). Can be a single value for all directions or a tuple of values for the (x, y, z) directions.

zoom_centretuple, default=None

Centrepoint of zooming in order (x, y, z). If any of the values are None, the midpoint of the image will be used in that direction.

zoom_uibool, default=None

If True, a UI for zooming will be displayed. Default is False unless rois are loaded, in which case default is True.

downsampleint/tuple, default=None

Factor by which to downsample an image. Can be a single value for all directions or a tuple of values in the (x, y, z) directions. For no downsampling, set values to None or 1, e.g. to downsample in the z direction only: downsample=(1, 1, 3).

affine4x4 array, default=None

Affine matrix to be used if image source(s) are NumPy array(s). If image sources are nifti file paths or nibabel objects, this parameter is ignored. If None, the arguments <voxel_sizes> and <origin> will be used to set the affine matrix.

voxel_sizestuple, default=(1, 1, 1)

Voxel sizes in mm, given in the order (y, x, z). Only used if image source is a numpy array and <affine> is None.

origintuple, default=(0, 0, 0)

Origin position in mm, given in the order (y, x, z). Only used if image source is a numpy array and <affine> is None.

major_xticksfloat, default=None

If not None, this value will be used as the interval between major tick marks on the x-axis. Otherwise, automatic matplotlib axis tick spacing will be used.

major_yticksfloat, default=None

If not None, this value will be used as the interval between major tick marks on the y-axis. Otherwise, automatic matplotlib axis tick spacing will be used.

major_ticksfloat, default=None

If not None, this value will be used as the interval between major tick marks. Otherwise, automatic matplotlib axis tick spacing will be used. This parameter applies to both x-axis and y-axis, but is overridden by a non-None value for major_xticks or major_yticks.

minor_xticksint, default=None

If None, no minor ticks will be plotted for the x-axis. Otherwise, this value will be the number of minor tick divisions per major tick interval.

minor_yticksint, default=None

If None, no minor ticks will be plotted for the y-axis. Otherwise, this value will be the number of minor tick divisions per major tick interval.

minor_ticksint, default=None

If None, no minor ticks will be plotted. Otherwise, this value will be the number of minor tick divisions per major tick interval. This parameter applies to both x-axis and y-axis, but is overridden by a non-None value for minor_xticks or minor_yticks.

ticks_all_sidesbool, default=False

If True, major (and minor if using) tick marks will be shown above and to the right hand side of the plot as well as below and to the left. The top/right ticks will not be labelled.

include_imagebool, default=False

If True, and image has associated image, overlay former on the latter.

no_uibool, default=None

If True, omit user-interface elements (Jupyter widgets) for interaction with viewed image(s). This can be useful for including graphics in stored notebooks. On GitHub, for example, static plots in notebooks are rendered correctly, but Jupyter widgets can cause problems. If None, set to the value of skrt.core.Default().no_ui.

any_attr(attr)

Check whether any of this object’s viewers have a given attribute.

apply_translation()

Update the description of translation sliders to show translation in mm if the translation is changed.

get_input_list(inp, allow_sublist=False)

Convert an input to a list with one item per image to be displayed.

load_comparison(comparison)

Create any comparison images.

make_comparison_ui()
make_fig(view_changed)
make_lower_ui(no_roi=False)

Make lower UI for ROI checkboxes.

make_reset_zoom(viewer)

Make a reset zoom function for a given viewer that updates zoom without plotting, then plots afterwards.

make_translation_ui()
make_ui(no_roi=False, no_intensity=False)
match_axes(match_axes)

Adjust axes of plots to match if the match_axes option is set.

on_key(event)

Callbacks for key presses.

on_scroll(event)

Callbacks for scroll events.

plot(tight_layout=True, **kwargs)

Plot all images.

set_callbacks()

Set callbacks for scrolls and keypresses.

set_slider_widths()

Adjust widths of slider UI.

show(show=True)
write_translation_to_file(_)

Write current translation to file.

class skrt.better_viewer.SingleViewer(im=None, init_view='x-y', init_slice=None, init_idx=None, init_pos=None, intensity=None, intensity_width=500, intensity_limits=None, intensity_step=None, figsize=6, xlim=None, ylim=None, zlim=None, zoom=None, zoom_centre=None, zoom_ui=None, cmap=None, colorbar=False, colorbar_label=None, clb_kwargs=None, clb_label_kwargs=None, xlabel=None, ylabel=None, no_xlabel=False, no_ylabel=False, xticks=None, yticks=None, no_xticks=False, no_yticks=False, no_xtick_labels=False, no_ytick_labels=False, mpl_kwargs=None, dose=None, dose_opacity=0.5, dose_kwargs=None, dose_range=None, dose_cmap=None, masked=True, invert_mask=False, mask=None, mask_color='black', grid=None, grid_opacity=1.0, grid_kwargs=None, jacobian=None, jacobian_opacity=0.8, jacobian_range=None, jacobian_cmap=None, jacobian_kwargs=None, df=None, df_plot_type='quiver', df_opacity=None, df_spacing=30, df_kwargs=None, rois=None, roi_names=None, rois_to_keep=None, rois_to_remove=None, roi_plot_type='contour', roi_opacity=None, roi_linewidth=2, roi_info=False, roi_info_dp=2, roi_kwargs=None, compare_rois=False, show_compared_rois_only=True, length_units='mm', area_units='mm', vol_units='mm', legend=False, legend_bbox_to_anchor=None, legend_loc='lower left', init_roi=None, roi_consensus=False, consensus_color='blue', standalone=True, continuous_update=False, annotate_slice=None, save_as=None, show=True, major_xticks=None, major_yticks=None, major_ticks=None, minor_xticks=None, minor_yticks=None, minor_ticks=None, ticks_all_sides=False, no_axis_labels=False, scale_in_mm=True, title=None, include_image=False, flatten=False, **kwargs)

Bases: object

Class for displaying an Image with interactive elements.

__init__(im=None, init_view='x-y', init_slice=None, init_idx=None, init_pos=None, intensity=None, intensity_width=500, intensity_limits=None, intensity_step=None, figsize=6, xlim=None, ylim=None, zlim=None, zoom=None, zoom_centre=None, zoom_ui=None, cmap=None, colorbar=False, colorbar_label=None, clb_kwargs=None, clb_label_kwargs=None, xlabel=None, ylabel=None, no_xlabel=False, no_ylabel=False, xticks=None, yticks=None, no_xticks=False, no_yticks=False, no_xtick_labels=False, no_ytick_labels=False, mpl_kwargs=None, dose=None, dose_opacity=0.5, dose_kwargs=None, dose_range=None, dose_cmap=None, masked=True, invert_mask=False, mask=None, mask_color='black', grid=None, grid_opacity=1.0, grid_kwargs=None, jacobian=None, jacobian_opacity=0.8, jacobian_range=None, jacobian_cmap=None, jacobian_kwargs=None, df=None, df_plot_type='quiver', df_opacity=None, df_spacing=30, df_kwargs=None, rois=None, roi_names=None, rois_to_keep=None, rois_to_remove=None, roi_plot_type='contour', roi_opacity=None, roi_linewidth=2, roi_info=False, roi_info_dp=2, roi_kwargs=None, compare_rois=False, show_compared_rois_only=True, length_units='mm', area_units='mm', vol_units='mm', legend=False, legend_bbox_to_anchor=None, legend_loc='lower left', init_roi=None, roi_consensus=False, consensus_color='blue', standalone=True, continuous_update=False, annotate_slice=None, save_as=None, show=True, major_xticks=None, major_yticks=None, major_ticks=None, minor_xticks=None, minor_yticks=None, minor_ticks=None, ticks_all_sides=False, no_axis_labels=False, scale_in_mm=True, title=None, include_image=False, flatten=False, **kwargs)
centre_on_roi(roi)

Set the current zoom centre to be the centre of an ROI.

decrease_slice(n=1)

Decrease slice slider value by n slices.

get_intensity_range()

Get vmin and vmax from intensity sliders.

get_visible_rois()

Get list of names of currently visible ROIs from checkboxes.

increase_slice(n=1)

Increase slice slider value by n slices.

jump_to_roi()

Jump to the mid slice of an ROI.

load_df(df)

Load deformation field.

load_dose(dose)

Load dose field.

load_grid(grid)

Load grid.

load_jacobian(jacobian)

Load jacobian determinant.

load_rois(rois, roi_names=None, rois_to_keep=None, rois_to_remove=None)

Load ROIs, apply names/filters, and assign to a single StructureSet.

make_image(im, *args, **kwargs)

Set up image object.

make_lower_ui(no_roi=False)
make_ui(other_viewer=None, share_slider=True, no_roi=False, no_intensity=False)

Make Jupyter notebook UI. If other_viewer contains another SingleViewer instance, the UI will be taken from that image. If share_slider is False, independent intensity and slice sliders will be created.

on_key(event)

Events run on keypress outside jupyter notebook.

on_scroll(event)

Events run on scroll outside jupyter notebook.

on_view_change()

Deal with a view change.

plot(**kwargs)

Plot a slice with current settings.

plot_image(im, view, **kwargs)

Plot an Image, reusing existing axes if outside a Jupyter notebook.

reset_zoom(_)

Reset zoom values to 1 and zoom centres to defaults.

roi_is_visible(roi)

Check whether a given ROI is currently visible. If the ROI isn’t in the checkbox list, return True (used to ensure that consensus contours always count as visible for comparison table).

save_fig(_=None)

Save figure to a file.

save_roi_comparison_table(_=None)

Save ROI comparison table to a file.

save_roi_info_table(_=None)

Save ROI geometric info table to a file.

set_callbacks()

Set up matplotlib callback functions for interactive plotting.

set_slice(view, sl)

Set the current slice number in a specific orientation.

set_slice_and_view()

Get the current slice and view to plot from the UI.

set_slice_from_idx(view, idx)

Set the current slice number from index of slice in image array.

set_slice_from_pos(view, pos)

Set the current slice number from a position in mm.

show(show=True)

Display plot and UI.

show_in_notebook(show)

Display interactive output in a jupyter notebook.

slice_to_slider(sl, ax=None)

Convert a slice number to a slider value.

slider_to_slice(val, ax=None)

Convert a slider value to a slice number.

update_roi_comparison()

Update lower ROI comparison UI to reflect current view/slice/ROI visibility.

update_roi_info_table()

Update lower ROI info UI to reflect current view/slice/ROI visibility.

update_roi_sliders()

Update ROI sliders depending on current plot type.

update_slice_slider()

Update the slice slider to show the axis corresponding to the current view, with value set to the last value used on that axis.

update_slice_slider_desc()

Update slice slider description to reflect current axis and position.

update_slider(slider, new_min, new_max, val)

Update slider min, max, and value without causing errors due to values outside range.

update_zoom_sliders()

Update zoom sliders to reflect the current view.

skrt.better_viewer.in_notebook()

Check whether current code is being run within a Jupyter notebook.

skrt.better_viewer.to_inches(size)

Convert a size string to a size in inches. If a float is given, it will be returned. If a string is given, the last two characters will be used to determine the units:

  • “in”: inches

  • “cm”: cm

  • “mm”: mm

  • “px”: pixels