skrt.viewer.core module

Classes for combining image data for plotting in QuickViewer.

class skrt.viewer.core.DeformationImage(nii, spacing=30, plot_type='grid', **kwargs)

Bases: Image

Class for loading a plotting a deformation field.

__init__(nii, spacing=30, plot_type='grid', **kwargs)

Load deformation field.

Parameters:

niistr/array/nifti
Source of the image data to load. This can be either:
  1. The path to a NIfTI file;

  2. A nibabel.nifti1.Nifti1Image object;

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

  4. A NumPy array.

get_deformation_slice(view, sl=None, pos=None)

Get voxel positions and displacement vectors on a 2D slice.

plot(view, sl=None, pos=None, ax=None, mpl_kwargs=None, plot_type='grid', spacing=30, zoom=None, zoom_centre=None)

Plot deformation field.

Parameters:

viewstr

Orientation in which to plot (“x-y”/”y-z”/”x-z”).

slint, default=None

Slice number. If <sl> and <pos> are both None, the middle slice will be plotted.

posfloat, default=None

Position in mm of the slice to plot (will be rounded to the nearest slice). If <sl> and <pos> are both None, the middle slice will be plotted. If <sl> and <pos> are both given, <sl> supercedes <pos>.

axmatplotlib.pyplot.Axes, default=None

Axes on which to plot. If None, new axes will be created.

mpl_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.imshow().

showbool, default=True

If True, the plotted figure will be shown via matplotlib.pyplot.show().

plot_typestr, default=”grid”

Type of plot to produce. Can either be “grid” to produce a grid plot, “quiver” to produce a quiver (arrow) plot.

spacingint/float/tuple, default=30

Spacing between gridpoints when the deformation field is plotted. If scale_in_mm=True, spacing will be in mm; otherwise, it will be in number of voxels. If a single value is given, this value will be used for the spacing in all directions. A tuple of three separate spacing values in order (x, y, z) can also be given.

plot_grid(view, sl, pos, ax, mpl_kwargs=None, zoom=None, zoom_centre=None)

Draw a grid plot on a set of axes.

plot_quiver(view, sl, pos, ax, mpl_kwargs=None, zoom=None, zoom_centre=None)

Draw a quiver plot on a set of axes.

set_plotting_defaults()

Create dict of default matplotlib plotting arguments for grid plots and quiver plots.

set_slice(view, sl=None, pos=None)

Set 2D array corresponding to a slice of the deformation field in a given orientation.

set_spacing(spacing)

Assign grid spacing in each direction. If spacing in given in mm, convert it to number of voxels.

class skrt.viewer.core.Image(im, affine=None, voxel_sizes=(1, 1, 1), origin=(0, 0, 0), title=None, scale_in_mm=True, downsample=None, orientation='x-y', rescale=True, load=True)

Bases: object

Load and plot image arrays from NIfTI files or NumPy objects.

__init__(im, affine=None, voxel_sizes=(1, 1, 1), origin=(0, 0, 0), title=None, scale_in_mm=True, downsample=None, orientation='x-y', rescale=True, load=True)

Initialise from a NIfTI file, NIfTI object, or numpy array.

Parameters:

imstr/array/nifti
Source of the image data to load. This can be either:
  1. The path to a NIfTI or DICOM file;

  2. A nibabel.nifti1.Nifti1Image object;

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

  4. A NumPy array.

affine4x4 array, default=None

Affine matrix to be used if <im> is a NumPy array. If <im> is a file path or a nibabel object, 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 <im> 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 <im> is a numpy array and <affine> is None.

titlestr, default=None

Title to use when plotting. If None and the image was loaded from a file, the filename will be used.

scale_in_mmbool, default=True

If True, plot axes will be in mm; if False, plot axes will be in voxels.

orientationstr, default=”x-y”

String specifying the orientation of the image if a 2D array is given for <im>. Must be “x-y”, “y-z”, or “x-z”.

loadbool, default=True

If True, the image data will be loaded immediately. Otherwise, it can be loaded later using the get_data() function.

adjust_ax(view, zoom=None, zoom_centre=None)

Adjust axis limits.

convert_to_3d(voxel_sizes, origin, orientation)

Convert own image array to 3D and fill voxel sizes/origin.

downsample(d)

Downsample image by amount d = (dx, dy, dz) in the (x, y, z) directions. If <d> is a single value, the image will be downsampled equally in all directions.

downsample_array(data_array)

Downsample a NumPy array by amount set in self.downsample.

get_ax_dict(val, default=1)

Convert a single value or tuple of values in order (x, y, z) to a dictionary containing x/y/z as keys.

get_coords()

Get lists of coordinates in each direction.

get_data()

Load image data if not already loaded, and return it. Also load geometrical settings.

get_idx(view, sl, pos, default_centre=True)

Convert a slice number or position in mm to an array index. If <default_centre> is set and <sl> and <pos> are both None, the middle slice will be taken; otherwise, an error will be raised.

get_image_centre(view)

Get midpoint of a given orientation.

get_kwargs(mpl_kwargs, default=None)

Return a dict of matplotlib keyword arguments, combining default values with custom values. If <default> is None, the class property self.mpl_kwargs will be used as default.

get_lengths(view)

Get the x and y lengths of the image in a given orientation.

get_min()
get_min_hu()

Get the minimum HU in the image.

get_relative_width(view, zoom=None, n_colorbars=0, figsize=None)

Get width:height ratio for this plot.

Parameters:

viewstr

Orientation (“x-y”/”y-z”/”x-z”).

zoomfloat/tuple/dict, default=None

Zoom factor.

n_colorbarsint, default=0

Number of colorbars to account for in computing the plot width.

get_slice(view, sl=None, pos=None)
get_zoomed_lims(view, zoom=None, zoom_centre=None)

Get axis limits zoomed in.

idx_to_pos(idx, ax)

Convert an index to a position in mm along a given axis.

idx_to_slice(idx, ax)

Convert an index to a slice number along a given axis.

label_ax(view, no_ylabel=False, no_title=False, annotate_slice=None)

Assign x/y axis labels and title to the plot.

length_to_voxels(length, ax)
match_size(im, fill_value=-1024)

Match shape to that of another Image.

plot(view='x-y', sl=None, pos=None, idx=None, ax=None, gs=None, figsize=None, zoom=None, zoom_centre=None, mpl_kwargs=None, show=True, colorbar=False, colorbar_label='HU', masked=False, invert_mask=False, mask_color='black', no_ylabel=False, no_title=False, annotate_slice=None, major_ticks=None, minor_ticks=None, ticks_all_sides=False, no_axis_labels=False)

Plot a 2D slice of the image.

Parameters:

viewstr, default=”x-y”

Orientation in which to plot (“x-y”/”y-z”/”x-z”).

slint, default=None

Slice number. If <sl> and <pos> are both None, the middle slice will be plotted.

posfloat, default=None

Position in mm of the slice to plot (will be rounded to the nearest slice). If <sl> and <pos> are both None, the middle slice will be plotted. If <sl> and <pos> are both given, <sl> supercedes <pos>.

axmatplotlib.pyplot.Axes, default=None

Axes on which to plot. If None, new axes will be created.

gsmatplotlib.gridspec.GridSpec, default=None

If not None and <ax> is None, new axes will be created on the current matplotlib figure with this gridspec.

mpl_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.imshow().

showbool, default=True

If True, the plotted figure will be shown via matplotlib.pyplot.show().

figsizefloat, default=None

Figure height in inches; only used if <ax> and <gs> are None. If None, the value in _default_figsize will be used.

zoomint/float/tuple, default=None

Factor by which to zoom in. If a single int or float is given, the same zoom factor will be applied in all directions. If a tuple of three values is given, these will be used as the zoom factors in each direction in the order (x, y, z). If None, the image will not be zoomed in.

zoom_centretuple, default=None

Position around which zooming is applied. If None, the centre of the image will be used.

colorbarbool, default=True

If True, a colorbar will be drawn alongside the plot.

colorbar_labelstr, default=”HU”

Label for the colorbar, if drawn.

maskedbool, default=False

If True and this object has attribute self.data_mask assigned, the image will be masked with the array in self.data_mask.

invert_maskbool, default=True

If True and a mask is applied, the mask will be inverted.

mask_colormatplotlib color, default=”black”

color in which to plot masked areas.

no_ylabelbool, default=False

If True, the y axis will not be labelled.

annotate_slicestr, default=None

Color for annotation of slice number. If None, no annotation will be added. If True, the default color (white) will be used.

pos_to_idx(pos, ax, force_int=True)

Convert a position in mm to an index along a given axis.

pos_to_slice(pos, ax)

Convert a position in mm to a slice number.

process_mask(mask, threshold=0.5)

Convert a mask to boolean and downsample if needed.

resample(data, v, round_up=True)

Resample an image to have particular voxel sizes.

reset()
rotate(yaw=0, pitch=0, roll=0)

Rotate image data.

same_frame(im)

Check whether this image is in the same frame of reference as another Image <im> (i.e. same origin and shape).

set_ax(view, ax=None, gs=None, figsize=None, zoom=None, n_colorbars=0)

Assign axes to self or create new axes if needed.

Parameters:

viewstr

Orientation (“x-y”/”y-z”/”x-z”)

axmatplotlib.pyplot.Axes, default=None

Axes to assign to self for plotting. If None, new axes will be created.

gsmatplotlib.gridspec.GridSpec, default=None

Gridspec to be used to create axes on an existing figure. Only used if <ax> is None.

figsizefloat, default=None

Size of matplotlib figure in inches. Only used if <ax> and <gs> are both None.

zoomint/float/tuple, default=None

Factor by which to zoom in. If a single int or float is given, the same zoom factor will be applied in all directions. If a tuple of three values is given, these will be used as the zoom factors in each direction in the order (x, y, z). If None, the image will not be zoomed in.

n_colorbarsint, default=0

Number of colorbars that will be plotted on these axes. Used to determine the relative width of the axes. Only used if <ax> and <gs> are both None.

set_geom()

Assign geometric properties based on image data, origin, and voxel sizes.

set_mask(mask, threshold=0.5)

Set a mask for this image. Can be a single mask array or a dictionary of mask arrays. This mask will be used when self.plot() is called with masked=True. Note: mask_threshold only used if the provided mask is not already a boolean array.

set_plotting_defaults()

Create dict of default matplotlib plotting arguments.

set_shift(dx, dy, dz)

Set the current translation to apply, where dx/dy/dz are in voxels.

set_slice(view, sl=None, pos=None, masked=False, invert_mask=False)

Assign a 2D array corresponding to a slice of the image in a given orientation to class variable self.current_slice. If the variable self.shift contains nonzero elements, the slice will be translated by the amounts in self.shift.

Parameters:

viewstr

Orientation (“x-y”/”y-z”/”x-z”).

slint, default=None

Slice number. If <sl> and <pos> are both None, the middle slice will be plotted.

posfloat, default=None

Position in mm of the slice to plot (will be rounded to the nearest slice). If <sl> and <pos> are both None, the middle slice will be plotted. If <sl> and <pos> are both given, <sl> supercedes <pos>.

maskedbool, default=False

If True and self.data_mask is not None, the mask in data_mask will be applied to the image. Voxels above the mask threshold in self.data_mask will be masked.

invert_maskbool, default=False

If True, values below the mask threshold will be used to mask the image instead of above threshold. Ignored if masked is False.

slice_to_idx(sl, ax)

Convert a slice number to an index along a given axis.

slice_to_pos(sl, ax)

Convert a slice number to a position in mm.

translate(dx=0, dy=0, dz=0)

Apply a translation to the image data.

class skrt.viewer.core.ImageComparison(im1, im2, title=None, plot_type=None, **kwargs)

Bases: Image

Class for loading data from two arrays and plotting comparison images.

__init__(im1, im2, title=None, plot_type=None, **kwargs)

Load data from two arrays. <im1> and <im2> can either be existing Image objects, or objects from which Images can be created.

get_dta(tolerance=None)

Compute distance to agreement array on current slice.

get_gamma(invert=False, dta_crit=None, diff_crit=None)

Get gamma index on current slice.

get_relative_width(view, colorbar=False, figsize=None)

Get relative width first image.

plot(view=None, sl=None, invert=False, ax=None, mpl_kwargs=None, show=True, figsize=None, zoom=None, zoom_centre=None, plot_type=None, cb_splits=2, overlay_opacity=0.5, overlay_legend=False, overlay_legend_loc=None, colorbar=False, colorbar_label='HU', show_mse=False, dta_tolerance=None, dta_crit=None, diff_crit=None)

Create a comparison plot of the two images.

Parameters:

viewstr, default=None

Orientation to plot (“x-y”/”y-z”/”x-z”). If <view> and <sl> are both None, they will be taken from the current orientation and slice of the images to be compared.

slint, default=None

Index of the slice to plot. If <view> and <sl> are both None, they will be taken from the current orientation and slice of the images to be compared.

invertbool, default=False

If True, the plotting order of the two images will be reversed.

axmatplotlib.pyplot.Axes, default=None

Axes on which to plot the comparison. If None, new axes will be created.

mpl_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib for plotting the two images.

showbool, default=True

If True, the figure will be shown via matplotlib.pyplot.show().

figsizefloat, default=None

Figure height in inches to be used if a new figure is created. If None, the value in _default_figsize will be used.

plot_chequerboard(invert=False, n_splits=2)

Produce a chequerboard plot with <n_splits> squares in each direction.

plot_difference(invert=False, ab=False)

Produce a difference plot.

plot_dta(tolerance=5)

Produce a distance-to-agreement plot.

plot_gamma(invert=False, dta_crit=None, diff_crit=None)

Produce a distance-to-agreement plot.

plot_overlay(invert=False, opacity=0.5, legend=False, legend_loc='auto')

Produce an overlay plot with a given opacity.

class skrt.viewer.core.MultiImage(nii=None, dose=None, mask=None, jacobian=None, df=None, structs=None, multi_structs=None, timeseries=None, struct_colors=None, structs_as_mask=False, struct_names=None, compare_structs=False, comp_type='auto', ignore_empty_structs=False, ignore_unpaired_structs=False, structs_to_keep=None, structs_to_ignore=None, autoload_structs=True, mask_threshold=0.5, **kwargs)

Bases: Image

Class for loading and plotting an image along with an optional mask, dose field, structures, jacobian determinant, and deformation field.

__init__(nii=None, dose=None, mask=None, jacobian=None, df=None, structs=None, multi_structs=None, timeseries=None, struct_colors=None, structs_as_mask=False, struct_names=None, compare_structs=False, comp_type='auto', ignore_empty_structs=False, ignore_unpaired_structs=False, structs_to_keep=None, structs_to_ignore=None, autoload_structs=True, mask_threshold=0.5, **kwargs)

Load a MultiImage object.

Parameters:

niistr/nifti/array

Path to a .nii/.npy file, or an nibabel nifti object/numpy array.

titlestr, default=None

Title for this image when plotted. If None and <nii> is loaded from a file, the filename will be used.

dosestr/nifti/array, default=None

Path or object from which to load dose field.

maskstr/nifti/array, default=None

Path or object from which to load mask array.

jacobianstr/nifti/array, default=None

Path or object from which to load jacobian determinant field.

dfstr/nifti/array, default=None

Path or object from which to load deformation field.

structsstr/list, default=None

A string containing a path, directory, or wildcard pointing to nifti file(s) containing structure(s). Can also be a list of paths/directories/wildcards.

struct_colorsdict, default=None

Custom colors to use for structures. Dictionary keys can be a structure name or a wildcard matching structure name(s). Values should be any valid matplotlib color.

structs_as_maskbool, default=False

If True, structures will be used as masks.

struct_nameslist/dict, default=None

For multi_structs, this parameter will be used to name the structures. Can either be a list (i.e. the first structure in the file will be given the first name in the list and so on), or a dict of numbers and names (e.g. {1: “first structure”} etc).

compare_structsbool, default=False

If True, structures will be paired together into comparisons.

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).

get_date_dict(timeseries, single_layer=False, allow_dirs=False)

Convert list/dict/directory to sorted dict of dates and files.

get_n_colorbars(colorbar=False)

Count the number of colorbars needed for this plot.

get_relative_width(view, zoom=None, colorbar=False, figsize=None)

Get the relative width for this plot, including all colorbars.

load_df(df)

Load deformation field data from a path.

load_structs(structs=None, multi_structs=None, names=None, colors=None, compare_structs=False, ignore_empty=False, ignore_unpaired=False, comp_type='auto', to_keep=None, to_ignore=None, autoload=True)

Load structures from a path/wildcard or list of paths/wildcards in <structs>, and assign the colors in <colors>.

load_to(nii, attr, kwargs)

Load image data into a class attribute.

plot(view='x-y', sl=None, pos=None, ax=None, gs=None, figsize=None, zoom=None, zoom_centre=None, mpl_kwargs=None, n_date=1, show=True, colorbar=False, colorbar_label='HU', dose_kwargs=None, masked=False, invert_mask=False, mask_color='black', jacobian_kwargs=None, df_kwargs=None, df_plot_type='grid', df_spacing=30, struct_kwargs=None, struct_plot_type='contour', struct_legend=True, legend_loc='lower left', struct_plot_grouping=None, struct_to_plot=None, annotate_slice=None, major_ticks=None, minor_ticks=None, ticks_all_sides=False, no_axis_labels=False)

Plot a 2D slice of this image and all extra features.

Parameters:

viewstr

Orientation in which to plot (“x-y”/”y-z”/”x-z”).

slint, default=None

Slice number. If <sl> and <pos> are both None, the middle slice will be plotted.

posfloat, default=None

Position in mm of the slice to plot (will be rounded to the nearest slice). If <sl> and <pos> are both None, the middle slice will be plotted. If <sl> and <pos> are both given, <sl> supercedes <pos>.

axmatplotlib.pyplot.Axes, default=None

Axes on which to plot. If None, new axes will be created.

gsmatplotlib.gridspec.GridSpec, default=None

If not None and <ax> is None, new axes will be created on the current matplotlib figure with this gridspec.

figsizefloat, default=None

Figure height in inches; only used if <ax> and <gs> are None. If None, the value in _default_figsize will be used.

zoomint/float/tuple, default=None

Factor by which to zoom in. If a single int or float is given, the same zoom factor will be applied in all directions. If a tuple of three values is given, these will be used as the zoom factors in each direction in the order (x, y, z). If None, the image will not be zoomed in.

mpl_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.imshow() for the main image.

showbool, default=True

If True, the plotted figure will be shown via matplotlib.pyplot.show().

colorbarbool, default=True

If True, a colorbar will be drawn alongside the plot.

dose_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.imshow() for the dose field.

maskedbool, default=False

If True and this object has attribute self.data_mask assigned, the image will be masked with the array in self.data_mask.

invert_maskbool, default=True

If True and a mask is applied, the mask will be inverted.

mask_colormatplotlib color, default=”black”

color in which to plot 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).

jacobian_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.imshow() for the jacobian determinant.

df_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.imshow() for the deformation field.

df_plot_typestr, default=”grid”

Type of plot (“grid”/”quiver”) to produce for the deformation field.

df_spacingint/float/tuple, default=30

Grid spacing for the deformation field plot. If self.scale_in_mm is true, the spacing will be in mm; otherwise in voxels. Can be either a single value for all directions, or a tuple of values for each direction in order (x, y, z).

struct_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib for structure plotting.

struct_plot_typestr, default=”contour”

Plot type for structures (“contour”/”mask”/”filled”)

struct_legendbool, default=True

If True, a legend will be drawn labelling any structrues visible on this slice.

legend_locstr, default=’lower left’

Position for the structure legend, if used.

annotate_slicestr, default=None

Color for annotation of slice number. If None, no annotation will be added. If True, the default color (white) will be used.

set_date(n)

Go to the nth image in series.

set_masks()

Assign mask(s) to self and dose image.

set_plotting_defaults()

Set default matplotlib plotting options for main image, dose field, and jacobian determinant.

class skrt.viewer.core.OrthogonalImage(*args, **kwargs)

Bases: MultiImage

MultiImage to be displayed with an orthogonal view of the main image next to it.

__init__(*args, **kwargs)

Initialise a MultiImage and set default orthogonal slice positions.

get_relative_width(view, zoom=None, colorbar=False, figsize=None)

Get width:height ratio for the full plot (main plot + orthogonal view).

plot(view, sl=None, pos=None, ax=None, gs=None, figsize=None, zoom=None, zoom_centre=None, mpl_kwargs=None, show=True, colorbar=False, colorbar_label='HU', struct_kwargs=None, struct_plot_type=None, major_ticks=None, minor_ticks=None, ticks_all_sides=False, no_axis_labels=False, **kwargs)

Plot MultiImage and orthogonal view of main image and structs.

set_axes(view, ax=None, gs=None, figsize=None, zoom=None, colorbar=False)

Set up axes for the plot. If <ax> is not None and <orthog_ax> has already been set, these axes will be used. Otherwise if <gs> is not None, the axes will be created within a gridspec on the current matplotlib figure. Otherwise, a new figure with height <figsize> will be produced.

class skrt.viewer.core.Struct(nii=None, name=None, color=None, label='', load=True, contours=None, shape=None, origin=None, voxel_sizes=None, **kwargs)

Bases: Image

Class to load and plot a structure as a contour or mask.

__init__(nii=None, name=None, color=None, label='', load=True, contours=None, shape=None, origin=None, voxel_sizes=None, **kwargs)

Load structure mask or contour.

Parameters:

niistr/array/nifti, default=None

Source of the image data to load. This can be either:

  1. The path to a NIfTI file;

  2. A nibabel.nifti1.Nifti1Image object;

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

  4. A NumPy array.

This mask will be used to generate contours. If None, the <contours> argument must be provided instead.

namestr, default=None

Name to assign to this structure. If the structure is loaded from a file and name is None, the name will be inferred from the filename.

colormatplotlib color, default=None

color in which to plot this structure. If None, a random color will be assigned. Can also be set later using self.assign_color(color).

labelstr, default=””

User-defined category to which this structure belongs.

loadbool, default=True

If True, the structure’s data will be loaded and its mask/contours will be created during initialise. Otherwise, this information can be loaded later with the load() function.

contoursdict, default=None

Dictionary of contour points in the x-y orientation, where the keys are the z positions and values are the 3D contour point coordinates. Only used if the <nii> argument is None. These contours are used to generate a mask.

shapelist, default=None

Number of voxels in the image in the (x, y, z) directions. Used to specify the image shape for the structure mask if <contours> is used.

originlist, default=None

Origin position in (x, y, z) coordinates. Used if the structure is defined through a NumPy array or a coordinate dictionary.

voxel_sizeslist, default=None

Voxel sizes in (x, y, z) coordinates. Used if the structure is defined through a NumPy array or a coordinate dictionary.

kwargsdict

Keyword arguments passed to initialisation of the parent quickviewer.image.Image object.

assign_color(color, custom=True)

Assign a color, ensuring that it is compatible with matplotlib.

centroid(view='x-y', sl=None, units='mm')

Get the centroid position in 3D.

convert_xy_contours(contours)

Convert index number to position or slice number for a set of contours in the x-y plane.

get_area(view, sl, units='mm')

Get the area on a given slice.

get_centre(view, sl)

Get the coordinates of the centre of this structure in a given view on a given slice.

get_contour_slice(view, sl)

Convert mask to contours on a given slice <sl> in a given orientation <view>.

get_length(units='mm')

Get the total x, y, z length in voxels or mm.

get_struct_centre(units=None)

Get the centre of this structure in voxels or mm. If no units are given, units will be mm if <self_in_mm> is True.

get_volume(units='mm')

Get total structure volume in voxels, mm, or ml.

load()

Load struct data and create contours in all orientations.

mid_slice(view='x-y')

Get central slice of this structure in a given orientation.

on_slice(view, sl)

Return True if a contour exists for this structure on a given slice.

plot(view, sl=None, pos=None, ax=None, mpl_kwargs=None, plot_type='contour', zoom=None, zoom_centre=None, show=False, no_title=False)

Plot structure.

Parameters:

viewstr

Orientation in which to plot (“x-y”/”y-z”/”x-z”).

slint, default=None

Slice number. If <sl> and <pos> are both None, the middle slice will be plotted.

posfloat, default=None

Position in mm of the slice to plot (will be rounded to the nearest slice). If <sl> and <pos> are both None, the middle slice will be plotted. If <sl> and <pos> are both given, <sl> supercedes <pos>.

axmatplotlib.pyplot.Axes, default=None

Axes on which to plot. If None, new axes will be created.

mpl_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.imshow().

plot_typestr, default=”contour”

Type of plot to produce. Can be “contour” for a contour plot, “mask” for a mask plot.

zoomfloat/tuple, default=None

Factor by which to zoom in.

plot_contour(view, sl, pos, ax, mpl_kwargs=None, zoom=None, zoom_centre=None, centroid=False, no_title=False)

Plot structure as a contour.

plot_mask(view, sl, pos, ax, mpl_kwargs=None, zoom=None, zoom_centre=None, no_title=False)

Plot structure as a colored mask.

set_contours()

Compute positions of contours on each slice in each orientation.

set_label(label)

Set the label for this structure and use to generate nice name.

set_mask()

Compute structure mask using contours.

set_plotting_defaults()

Set default matplotlib plotting keywords for both mask and contour images.

slices(view='x-y')

Get list of slice numbers on which this structure is nonzero in a given orientation.

struct_extent(view='x-y', sl=None, units='mm')

Get extent of structure. If <sl> is not given, the extents in all 3 directions will be returned; otherwise, only the two extents on a given slice will be returned.

class skrt.viewer.core.StructComparison(struct1, struct2, name='', comp_type=None, **kwargs)

Bases: object

Class for computing comparison metrics for two structures and plotting the structures together.

__init__(struct1, struct2, name='', comp_type=None, **kwargs)

Initialise from a pair of Structs, or load new Structs.

abs_centroid_distance(view='x-y', sl=None, units='mm', force=False)

Get magnitude of centroid distance.

area_ratio(view, sl)
centroid_distance(view='x-y', sl=None, units='mm')

Get centroid displacement in each direction. If <sl> is not given, the 3D centroid displacement will be returned; otherwise, only the centroid displacement within a slice will be returned.

dice(view='x-y', sl=None, force=False)

Get dice score on a given slice.

extent_ratio(view, sl)
hausdorff_distance(view='x-y', sl=None, connectivity=2)
is_valid()

Check both structures are valid and in same reference frame.

mean_surface_distance(view='x-y', sl=None, connectivity=2)
on_slice(view, sl)

Check whether both structures are on a given slice.

plot(view, sl=None, pos=None, ax=None, mpl_kwargs=None, plot_type='contour', zoom=None, zoom_centre=None, show=False, plot_grouping=None)

Plot comparison structures.

plot_mask(view, sl, pos, ax, mpl_kwargs, zoom, zoom_centre)

Plot two masks, with intersection in different colour.

relative_area(view, sl)

Get relative structure area difference on a slice.

relative_vol()

Get relative structure volume difference.

rms_surface_distance(view='x-y', sl=None, connectivity=2)
surface_distances(view='x-y', sl=None, connectivity=2)

Get vector of surface distances.

update_s2_data(comp_type=None)

Update the data in struct2 using struct visibility and potential new comp type.

vol_ratio()

Get relative volume of the two structures.

class skrt.viewer.core.StructureSet(structs=None, multi_structs=None, names=None, colors=None, comp_type='auto', struct_kwargs=None, image=None, to_keep=None, to_ignore=None, autoload=True)

Bases: object

Class for loading and storing multiple Structs.

__init__(structs=None, multi_structs=None, names=None, colors=None, comp_type='auto', struct_kwargs=None, image=None, to_keep=None, to_ignore=None, autoload=True)

Load structures.

Parameters:

structsstr/list/dict

Sources of structures files to load structures from. Can be:

(a) A string containing a filepath, directory path, or wildcard to a file or directory path. If a directory is given, all .nii and .nii.gz files within that directory will be loaded. (b) A list of strings as described in (a). All files/directories in the list will be loaded. (c) A dictionary, where keys are labels and values are strings or lists as described in (a) and (b). The files loaded for each entry will be given the label in the key. (d) A list of pairs filepaths or wildcard filepaths, which should point to one file only. These pairs of files will then be used for comparisons.

multi_structs : str/list/dict

nameslist/dict, default=None

A dictionary where keys are filenames or wildcards matching filenames, and values are names to give the structure(s) in those files. Keys can also be lists of several potential filenames. If None, defaults will be taken from the file given in the default_struct_names parameter ~/.quickviewer/settings.ini, if it exists.

If using multiple structures per file, this can also be either:

(a) A list of names, where the order reflects the order of structure masks in the file (i.e. the nth item in the list will refer to the structure with label mask n + 1). (b) A dictionary where the keys are integers referring to the label masks and values are structure names.

This can also be nested in a dictionary to give multiple naming options for different labels.

colorsdict, default=None

A dictionary of colours to assign to structures with a given name. Can also be a nested dictionary inside a dictionary where keys are labels, so that different sets of structure colours can be used for different labels. If None, defaults will be taken from the file given in ~/.quickviewer/settings.ini, if it exists.

struct_kwargsdict, default=None

Keyword arguments to pass to any created Struct objects.

comp_typestr, default=”auto”

Option for method of comparing any loaded structures. Can be:

  • “auto”: Structures will be matched based on name if many are loaded, pairs if a list of pairs is given, or simply matched if only two structs are loaded.

  • “pairs”: Every possible pair of loaded structs will be compared.

  • “other”: Each structure will be compared to the consenues of all of the others.

  • “overlap”: Each structure will be comapred to the overlapping region of all of the others.

to_keeplist, default=None

List of structure names/wildcards to keep. If this argument is set, all otehr structures will be ignored.

to_ignorelist, default=None

List of structure names to ignore.

autoloadbool, default=True

If True, all structures will be loaded before being returned.

add_struct_array(array, name, colors)

Create Struct object from a NumPy array and add to list.

add_struct_file(path, label, names, colors, multi=False)

Create Struct object(s) from file and add to list.

find_color_match(colors, name)

Find the first color in a color dictionary that matches a given structure name.

find_comparisons()

Find structures suitable for comparison and make a list of StructComparison objects.

find_name_match(names, path)

Assign a name to a structure based on its path.

get_comparison_dict(ignore_empty=False)
get_comparisons(ignore_empty=False)

Get list of StructComparison objects.

get_standalone_structs(ignore_unpaired=False, ignore_empty=False)

Get list of the structures that are not part of a comparison pair.

get_struct(name)

Get a structure with a specific name.

get_struct_dict(ignore_unpaired=False, ignore_empty=False, sort=False)

Get dictionary of structures, where keys are structure names.

get_structs(ignore_unpaired=False, ignore_empty=False, sort=False)

Get list of all structures. If <ignore_unpaired> is True, only structures that are part of a comparison pair will be returned.

keep_struct(name)

Check whether a structure with a given name should be kept or ignored.

load_all()

Load all structures and assign custom colours and unique names.

load_settings(settings)

Process a settings dict into a standard format.

load_struct_pairs(structs, names, colors)

Load structs from pairs and create a StructComparison for each.

load_structs(structs, names, colors, multi=False)

Load a list/dict of structres.

load_structs_from_dicom(path, label, names, colors)

Attempt to load structures from a DICOM file.

load_structs_from_file(paths, label, names, colors, multi=False)

Search for filenames matching <paths> and load structs from all files.

reassign_colors(colors)

Reassign colors such that any structures in the <colors> dict are given that color, and any not in the dict are given unique colors and added to it.

set_unique_name(struct)

Create a unique name for a structure with respect to all other loaded structures.

skrt.viewer.core.contours_to_indices(contours, origin, voxel_sizes, shape)

Convert contours from positions in mm to array indices.

skrt.viewer.core.contours_to_mask(contours, shape, level=0.25, save_name=None, affine=None)

Convert contours to mask.

skrt.viewer.core.find_date(s)

Find a date-like object in a string.

skrt.viewer.core.find_files(paths, ext='', allow_dirs=False)

Find files from a path, list of paths, directory, or list of directories. If <paths> contains directories, files with extension <ext> will be searched for inside those directories.

skrt.viewer.core.get_dicom_sequence(ds=None, basename='')
skrt.viewer.core.get_rotation_matrix(yaw, pitch, roll, centre)
skrt.viewer.core.get_translation_matrix(dx, dy, dz)
skrt.viewer.core.get_unique_path(p1, p2)

Get the part of path p1 that is unique from path p2.

skrt.viewer.core.is_list(var)

Check whether a variable is a list/tuple.

skrt.viewer.core.is_nested(d)

Check whether a dict <d> has further dicts nested inside.

skrt.viewer.core.load_dicom(path, rescale=True)

Load a DICOM image array and affine matrix from a path.

skrt.viewer.core.load_dicom_multiple_files(paths, series_num=None, rescale=True, orientation=None)

Load a single dicom image from multiple files.

skrt.viewer.core.load_dicom_single_file(ds, rescale=True)

Load DICOM image from a single DICOM object.

skrt.viewer.core.load_image(im, affine=None, voxel_sizes=None, origin=None, rescale=True)
Load image from either:
  1. a numpy array;

  2. an nibabel nifti object;

  3. a file containing a numpy array;

  4. a nifti or dicom file.

Returns image data, tuple of voxel sizes, tuple of origin points, and path to image file (None if image was not from a file).

skrt.viewer.core.load_structs(path)

Load structures from a DICOM file.

skrt.viewer.core.make_name_nice(name)

Replace underscores with spaces and make uppercase.

skrt.viewer.core.make_three(var)

Ensure a variable is a tuple with 3 entries.

skrt.viewer.core.standard_str(string)

Convert a string to lowercase and replace all spaces with underscores.

skrt.viewer.core.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