Skip to main content
`Ctrl`+`K`

# `StackView`: Plot a stack of images

QWidget displaying a 3D volume as a stack of 2D images.

The `StackView` class implements this widget.

Basic usage of `StackView` is through the following methods:

- `StackView.getColormap()`, `StackView.setColormap()` to update the default colormap to use and update the currently displayed image.

- `StackView.setStack()` to update the displayed image.

The `StackView` uses `PlotWindow` and also exposes a subset of the `silx.gui.plot.Plot` API for further control (plot title, axes labels, …).

The `StackViewMainWindow` class implements a widget that adds a status bar displaying the 3D index and the value under the mouse cursor.

Example:

    import numpy
    import sys
    from silx.gui import qt
    from silx.gui.plot.StackView import StackViewMainWindow

    app = qt.QApplication(sys.argv[1:])

    # synthetic data, stack of 100 images of size 200x300
    mystack = numpy.fromfunction(
        lambda i, j, k: numpy.sin(i/15.) + numpy.cos(j/4.) + 2 * numpy.sin(k/6.),
        (100, 200, 300)
    )

    sv = StackViewMainWindow()
    sv.setColormap("viridis", vmin=-4, vmax=4)
    sv.setStack(mystack)
    sv.setLabels(["1st dim (0-99)", "2nd dim (0-199)",
                  "3rd dim (0-299)"])
    sv.show()

    app.exec()

## `StackView` class

class StackView(parent=None, resetzoom=True, backend=None, autoScale=False, logScale=False, grid=False, colormap=True, aspectRatio=True, yinverted=True, copy=True, save=True, print_=True, control=False, position=None, mask=True)

  Stack view widget, to display and browse through stack of images.

  The profile tool can be switched to “3D” mode, to compute the profile on each image of the stack (not only the active image currently displayed) and display the result as a slice.

  Parameters:

    - parent (QWidget) – the Qt parent, or None

    - backend (str or `BackendBase.BackendBase`) – The backend to use for the plot (default: matplotlib). See `PlotWidget` for the list of supported backend.

    - resetzoom (bool) – Toggle visibility of reset zoom action.

    - autoScale (bool) – Toggle visibility of axes autoscale actions.

    - logScale (bool) – Toggle visibility of axes log scale actions.

    - grid (bool) – Toggle visibility of grid mode action.

    - colormap (bool) – Toggle visibility of colormap action.

    - aspectRatio (bool) – Toggle visibility of aspect ratio button.

    - yInverted (bool) – Toggle visibility of Y axis direction button.

    - copy (bool) – Toggle visibility of copy action.

    - save (bool) – Toggle visibility of save action.

    - print (bool) – Toggle visibility of print action.

    - control (bool) – True to display an Options button with a sub-menu to show legends, toggle crosshair and pan with arrows. (Default: False)

    - position – True to display widget with (x, y) mouse position (Default: False). It also supports a list of (name, funct(x, y)->value) to customize the displayed values. See `silx.gui.plot.PlotTools.PositionInfo`.

    - mask (bool) – Toggle visibilty of mask action.

  valueChanged

    Signals that the data value under the cursor has changed.

    It provides: row, column, data value.

  sigPlaneSelectionChanged

    Signal emitted when there is a change is perspective/displayed axes.

    It provides the perspective as an integer, with the following meaning:

    > - 0: axis Y is the 2nd dimension, axis X is the 3rd dimension

    > - 1: axis Y is the 1st dimension, axis X is the 3rd dimension

    > - 2: axis Y is the 1st dimension, axis X is the 2nd dimension

  sigStackChanged

    Signal emitted when the stack is changed. This happens when a new volume is loaded, or when the current volume is transposed (change in perspective).

    The signal provides the size (number of pixels) of the stack. This will be 0 if the stack is cleared, else it will be a positive integer.

  sigFrameChanged

    Signal emitter when the frame number has changed.

    This signal provides the current frame number.

  getAggregationModeAction()

    Action toggling the aggregation mode action

    Return type:

      `AggregationModeAction`

  getPerspective()

    Returns the index of the dimension the stack is browsed with

    Possible values are: 0, 1, or 2.

    Return type:

      int

  setPerspective(perspective)

    Set the index of the dimension the stack is browsed with:

    - slice plane Dim1-Dim2: perspective 0

    - slice plane Dim0-Dim2: perspective 1

    - slice plane Dim0-Dim1: perspective 2

    Parameters:

      perspective (int) – Orthogonal dimension number (0, 1, or 2)

  getCalibrations(order='array')

    Returns currently used calibrations for each axis

    Returned calibrations might differ from the ones that were set as non-linear calibrations used for image axes are temporarily ignored.

    Parameters:

      order (str) – ‘array’ to sort calibrations as data array (dim0, dim1, dim2), ‘axes’ to sort calibrations as currently selected x, y and z axes.

    Returns:

      Calibrations ordered depending on order

    Return type:

      List[AbstractCalibration]

  setStack(stack, perspective=None, reset=True, calibrations=None)

    Set the 3D stack.

    The perspective parameter is used to define which dimension of the 3D array is to be used as frame index. The lowest remaining dimension number is the row index of the displayed image (Y axis), and the highest remaining dimension is the column index (X axis).

    Parameters:

      - stack (3D numpy.ndarray, or 3D h5py.Dataset, or list/tuple of 2D numpy arrays, or None.) – 3D stack, or None to clear plot.

      - perspective (int) – Dimension for the frame index: 0, 1 or 2. Use `None` to keep the current perspective (default).

      - reset (bool) – Whether to reset zoom or not.

      - calibrations – Sequence of 3 calibration objects for each axis. These objects can be a subclass of `AbstractCalibration`, or 2-tuples (a, b) where a is the y-intercept and b is the slope of a linear calibration (\(x \mapsto a + b x\))

  getStack(copy=True, returnNumpyArray=False)

    Get the original stack, as a 3D array or dataset.

    The output has the form: [data, params] where params is a dictionary containing display parameters.

    Parameters:

      - copy (bool) – If True (default), then the object is copied and returned as a numpy array. Else, a reference to original data is returned, if possible. If the original data is not a numpy array and parameter returnNumpyArray is True, a copy will be made anyway.

      - returnNumpyArray (bool) – If True, the returned object is guaranteed to be a numpy array.

    Returns:

      3D stack and parameters.

    Return type:

      (numpy.ndarray, dict)

  getCurrentView(copy=True, returnNumpyArray=False)

    Get the stack, as it is currently displayed.

    The first index of the returned stack is always the frame index. If the perspective has been changed in the widget since the data was first loaded, this will be reflected in the order of the dimensions of the returned object.

    The output has the form: [data, params] where params is a dictionary containing display parameters.

    Parameters:

      - copy (bool) – If True (default), then the object is copied and returned as a numpy array. Else, a reference to original data is returned, if possible. If the original data is not a numpy array and parameter returnNumpyArray is True, a copy will be made anyway.

      - returnNumpyArray (bool) – If True, the returned object is guaranteed to be a numpy array.

    Returns:

      3D stack and parameters.

    Return type:

      (numpy.ndarray, dict)

  setFrameNumber(number)

    Set the frame selection to a specific value

    Parameters:

      number (int) – Number of the frame

  getFrameNumber()

    Set the frame selection to a specific value

    Returns:

      Index of currently displayed frame

    Return type:

      int

  setFirstStackDimension(first_stack_dimension)

    When viewing the last 3 dimensions of an n-D array (n>3), you can use this method to change the text in the combobox.

    For instance, for a 7-D array, first stack dim is 4, so the default “Dim1-Dim2” text should be replaced with “Dim5-Dim6” (dimensions numbers are 0-based).

    Parameters:

      first_stack_dim (int) – First stack dimension (n-3) when viewing the last 3 dimensions of an n-D array.

  setTitleCallback(callback)

    Set a user defined function to generate the plot title based on the image/frame index.

    The callback function must accept an integer as a its first positional parameter and must not require any other mandatory parameter. It must return a string.

    To switch back the default behavior, you can pass `None`:

        mystackview.setTitleCallback(None)

    To have no title, pass a function that returns an empty string:

        mystackview.setTitleCallback(lambda idx: "")

    Parameters:

      callback – Callback function generating the stack title based on the frame number.

  clear()

    Clear the widget:

    - clear the plot

    - clear the loaded data volume

  setLabels(labels=None)

    Set the labels to be displayed on the plot axes.

    You must provide a sequence of 3 strings, corresponding to the 3 dimensions of the original data volume. The proper label will automatically be selected for each plot axis when the volume is rotated (when different axes are selected as the X and Y axes).

    Parameters:

      labels (List[str]) – 3 labels corresponding to the 3 dimensions of the data volumes.

  getLabels()

    Return dimension labels displayed on the plot axes

    Returns:

      List of three strings corresponding to the 3 dimensions of the stack: (name_dim0, name_dim1, name_dim2)

  getColormap()

    Get the current colormap description.

    Returns:

      A description of the current colormap. See `setColormap()` for details.

    Return type:

      dict

  scaleColormapRangeToStack()

    Scale colormap range according to current stack data.

    If no stack has been set through `setStack()`, this has no effect.

    The range scaling mode is given by current `Colormap`’s `Colormap.getAutoscaleMode()`.

  setColormap(colormap=None, normalization=None, vmin=None, vmax=None, colors=None)

    Set the colormap and update active image.

    Parameters that are not provided are taken from the current colormap.

    The colormap parameter can also be a dict with the following keys:

    - name: string. The colormap to use: ‘gray’, ‘reversed gray’, ‘temperature’, ‘red’, ‘green’, ‘blue’.

    - normalization: string. The mapping to use for the colormap: either ‘linear’ or ‘log’.

    - autoscale: bool. Whether to use autoscale (True) or range provided by keys ‘vmin’ and ‘vmax’ (False).

    - vmin: float. The minimum value of the range to use if ‘autoscale’ is False.

    - vmax: float. The maximum value of the range to use if ‘autoscale’ is False.

    - colors: optional. Nx3 or Nx4 array of float in [0, 1] or uint8.

        List of RGB or RGBA colors to use (only if name is None)

    Parameters:

      - colormap (dict or str.) – Name of the colormap in ‘gray’, ‘reversed gray’, ‘temperature’, ‘red’, ‘green’, ‘blue’. Or a :class`.Colormap` object.

      - normalization (str) – Colormap mapping: ‘linear’ or ‘log’.

      - vmin (float) – The minimum value of the range to use.

      - vmax (float) – The maximum value of the range to use.

      - colors (numpy.ndarray) – Only used if name is None. Custom colormap colors as Nx3 or Nx4 RGB or RGBA arrays

  getPlotWidget()

    Return the `PlotWidget`.

    This gives access to advanced plot configuration options. Be warned that modifying the plot can cause issues, and some changes you make to the plot could be overwritten by the `StackView` widget’s internal methods and callbacks.

    Returns:

      instance of `PlotWidget` used in widget

  setOptionVisible(isVisible)

    Set the visibility of the browsing options.

    Parameters:

      isVisible (bool) – True to have the options visible, else False

  getProfileToolbar()

    Profile tools attached to this plot

  getGraphTitle()

    Return the plot main title as a str.

  setGraphTitle(title='')

    Set the plot main title.

    Parameters:

      title (str) – Main title of the plot (default: ‘’)

  getGraphXLabel()

    Return the current horizontal axis label as a str.

  setGraphXLabel(label=None)

    Set the plot horizontal axis label.

    Parameters:

      label (str) – The horizontal axis label

  getGraphYLabel(axis='left')

    Return the current vertical axis label as a str.

    Parameters:

      axis (str) – The Y axis for which to get the label (left or right)

  setGraphYLabel(label=None, axis='left')

    Set the vertical axis label on the plot.

    Parameters:

      - label (str) – The Y axis label

      - axis (str) – The Y axis for which to set the label (left or right)

  getColorBarAction()

    Returns the action managing the visibility of the colorbar.

    Warning

    to show/hide the plot colorbar call directly the ColorBar widget using getColorBarWidget()

    Return type:

      QAction

  addShape(*args, **kwargs)

    See `Plot.Plot.addShape()`

## `StackViewMainWindow` class

class StackViewMainWindow(parent=None)

  Bases: `StackView`

  This class is a `StackView` with a menu, an additional toolbar to set the plot limits, and a status bar to display the value and 3D index of the data samples hovered by the mouse cursor.

  Parameters:

    parent (QWidget) – Parent widget, or None

  setStack(stack, *args, **kwargs)

    Set the displayed stack.

    See `StackView.setStack()` for details.