Visualization

Matplotlib - 2D plotting

You will find method to render 2D matplotlib figures with the mplt module:

timagetk.visu.mplt.grayscale_imshow(image, slice_id=None, axis='z', val_range='type', cmap='gray', **kwargs)[source]

Display a 2D grayscale image.

Uses matplotlib.imshow() and _multiple_plots if more than one image is given.

Parameters:
  • image (timagetk.components.spatial_image.SpatialImage or list of timagetk.components.spatial_image.SpatialImage) – 2D image(s) to represent, if 3D image(s), a contour_projection is first computed.

  • slice_id (int, optional) – Use all slices by default (None), else the z-slice to get for the histogram

  • axis (str, optional) – Axis to use when specifying a slice_id, 'z' by default.

  • val_range (str or list of str, optional) – Define the range of values used by the colormap, by default type

  • cmap (matplotlib.colors.ListedColormap or str or list of str, optional) – Colormap to use, see the stack_browser notes for advised colormaps

  • title (str) – If provided (default is empty), add this string of characters as title

  • suptitle (str) – A general title placed above the sub-figures titles, usually used when a list of images is given

  • threshold (int) – The intensity threshold to use with contour projection when using 3D images. Setting slice_id override the use of this parameter.

  • orientation ({-1, 1}) – The orinetation of the image, use -1 with an inverted microscope. In that case the top of the object is at the bottome of the image.

  • axe (.axes.Axes object) – Use it to combine plots in the same subfigure

  • cbar (bool) – If False, default is True, no colorbar will be displayed

  • extent (list of float) – If provided (default, None), set the extent of the displayed image. By default, use the real unit extent of the SpatialImage istance.

  • max_per_line (int) – Number of figure per line when using more than one images, default is 4

  • thumb_size (float) – Image size in inch (default=5.)

  • no_show (bool) – If True, default is False, do not call the blocking ‘show’ method

  • figname (str) – If a string is given, consider it’s a valid file location (path, name & extension) Do not show the figure, just create, write & close.

  • interpoplation (str) – The interpolation method used. See notes for more details. Defaults to ‘none’.

Returns:

AxesSubplot – Use it to combine plots in the same subfigure.

Notes

Supported values for val_range are:

  • auto, get the min and max value of the image;

  • type, get the maximum range from the image.dtype, e.g. ‘uint8’=[0, 255];

  • length-2 list of value, e.g. [10, 200];

If a list of image is given, a list of title should also be given.

If a list of image is given and only one val_range is given, we use the same range for all images.

Supported values for interpolation are ‘none’, ‘antialiased’, ‘nearest’, ‘bilinear’, ‘bicubic’, ‘spline16’,

‘spline36’, ‘hanning’, ‘hamming’, ‘hermite’, ‘kaiser’, ‘quadric’, ‘catrom’, ‘gaussian’, ‘bessel’, ‘mitchell’, ‘sinc’, ‘lanczos’, ‘blackman’. See matplotlib.axes._axes.Axes.imshow documentation for more details.

See also

matplotlib.axes._axes.Axes.imshow

Examples

>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_dataset
>>> from timagetk.visu.mplt import grayscale_imshow
>>> # - Get 'p58' shared intensity image:
>>> image = imread(shared_dataset("p58")[0])
>>> # Example 1 - Display the middle z-slice of the 3D image stack, with 'viridis' colormap:
>>> mid_z = image.get_shape('z')//2
>>> v = grayscale_imshow(image, mid_z, 'z', cmap='viridis', colorbar=True)
>>> # Example 2 - Display the middle x-slice of two 3D image stacks:
>>> from timagetk.algorithms.exposure import global_contrast_stretch
>>> stretch_img = global_contrast_stretch(image)
>>> mid_x = image.get_shape('x')//2
>>> v = grayscale_imshow([image, stretch_img], mid_x, 'x', suptitle="Effect of global stretching")
>>> # Example 3 - Display a z-axis projection of the 3D image:
>>> v = grayscale_imshow(image, title=image.filename)
timagetk.visu.mplt.image_n_hist(image, cmap='gray', title='', img_title='', figname='', **kwargs)[source]

Plot an image(s) along with its histogram and cumulative histogram.

Parameters:
  • image (numpy.ndarray or timagetk.components.spatial_image.SpatialImage or list) – Image to use to generate the histogram, can be a list.

  • cmap (str, optional) – Colormap to use, see the stack_browser notes for advised colormaps.

  • title (str, optional) – If provided (default is empty), add this string of characters as title.

  • img_title (str or list of str, optional) – If provided (default is empty), add this string of characters as title.

  • figname (str, optional) – If provided (default is empty), the image will be saved under this filename.

  • thumb_size (float) – Image size in inch (default=5.)

  • bins (integer or array_like) – If an integer is given, bins + 1 bin edges are returned. Unequally spaced bins are supported if bins is a sequence. Defaults to 256.

Notes

If a list of image is given, a list of img_title should also be given.

Examples

>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_data
>>> from timagetk.visu.mplt import image_n_hist
>>> from timagetk.algorithms.exposure import equalize_adapthist
>>> image_path = shared_dataset("p58")[0]
>>> image = imread(image_path)
>>> ks_range = [1/12., 1/10., 1/8., 1/6.]
>>> sh = image.shape[:2]
>>> out_imgs = [equalize_adapthist(image,kernel_size=[ks*sh[0], ks*sh[1]]) for ks in ks_range]
>>> subtitles = ["Original"] + ["Kernel-size {}".format(ks) for ks in ks_range]
>>> image_n_hist([image.get_slice(50, 'z')] + [img.get_slice(50, 'z') for img in out_imgs], title="adaptive histogram equalization (z-slice=50/{})".format(image.shape[-1]), img_title=subtitles)
timagetk.visu.mplt.image_plot(image, axe=None, cmap='gray', **kwargs)[source]

Display a 2D image with size unit and a coordinate centered pixel.

Parameters:
  • image (timagetk.components.spatial_image.SpatialImage) – 2D image to represent.

  • axe (matplotlib.axes.Axes) – Use it to combine plots in the same subfigure.

  • cmap (Any) – The Colormap instance or registered colormap name used to map scalar data to colors. This parameter is ignored for RGB(A) data.

  • val_range (str or list of int) – Define the range of values used by the colormap, by default ‘type’.

  • norm (matplotlib.colors.BoundaryNorm) – The .Normalize instance used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling mapping the lowest value to 0 and the highest to 1 is used. This parameter is ignored for RGB(A) data.

  • extent (list of float) – If provided, set the extent of the displayed image. By default, try to use the real extent of the SpatialImage instance or set to image.shape (voxel unit).

  • voxelsize (list of float) – If provided, set the voxelsize of the displayed image. By default, try to use the real voxelsize of the SpatialImage instance or set to [1., 1.] (voxel unit).

  • unit (str) – If provided, set the unit on the image axes. By default, try to use the real unit of the SpatialImage instance or set to 'voxels' (voxel unit).

  • interpoplation (str) – The interpolation method used. See notes for more details. Defaults to ‘none’.

Returns:

  • matplotlib.axes.Axes – The updated Axes object.

  • matplotlib.axes.Axes – The sub-figure object.

Notes

Supported values for interpolation are ‘none’, ‘antialiased’, ‘nearest’, ‘bilinear’, ‘bicubic’, ‘spline16’,

‘spline36’, ‘hanning’, ‘hamming’, ‘hermite’, ‘kaiser’, ‘quadric’, ‘catrom’, ‘gaussian’, ‘bessel’, ‘mitchell’, ‘sinc’, ‘lanczos’, ‘blackman’. See matplotlib.axes._axes.Axes.imshow documentation for more details.

See also

matplotlib.axes._axes.Axes.imshow

Examples

>>> import matplotlib.pyplot as plt
>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_data
>>> from timagetk.visu.mplt import image_plot
>>> fname = 'p58-t0-a0.lsm'
>>> image_path = shared_data(fname, "p58")
>>> img = imread(image_path)
>>> # - Display the middle z-slice of the 3D image, with 'viridis' colormap:
>>> fig = plt.figure()
>>> ax_img = plt.subplot()
>>> mid_z = img.get_slice(img.get_shape('z')//2, 'z')  # get the middle z-slice
>>> ax_img, fig_img = image_plot(mid_z,ax_img,cmap='viridis')
>>> axe.set_title(fname)  # add the file name as title
>>> fig.colorbar(fig_img, ax=axe, label='intensity')  # add the intensity colorbar
timagetk.visu.mplt.imshow_property(image, ppty, slice_id=None, axis='z', val_range='auto', cmap='viridis', **kwargs)[source]

Plot a labelled image with property values instead of labels.

Parameters:
  • image (timagetk.LabelledImage) – Labelled image to map property values.

  • ppty (dict) – Label based dictionary of values.

  • slice_id (int, optional) – Use all slices by default (None), else the z-slice to get for the histogram

  • axis (str, optional) – Axis to use when specifying a slice_id, 'z' by default.

  • val_range (2-list of int, optional) – Define the range of values used by the colormap. By default, "auto" scale it to the range of mapped property.

  • cmap (str, optional) – Name of the colormap to use, defaults to "viridis".

Examples

>>> from timagetk.io import imread
>>> from timagetk import TissueImage3D
>>> from timagetk.io.util import shared_dataset
>>> from timagetk.visu.mplt import imshow_property
>>> from timagetk.visu.mplt import grayscale_imshow
>>> from timagetk.components.labelled_image import labels_at_stack_margins
>>> from timagetk.features.cells import volume
>>> image_path = shared_dataset("p58", "segmented")[0]
>>> image = imread(image_path, TissueImage3D, background=1, not_a_label=0)
>>> # List cells too close to stack margin, as they should be excluded:
>>> margin_labels = labels_at_stack_margins(image, 5)
>>> # Compute the cell volumes:
>>> vol = volume(image, cell_ids=set(image.cell_ids())-set(margin_labels))
>>> axis = 'y'
>>> mid_sh = image.get_shape(axis) // 2
>>> imshow_property(image, vol, mid_sh, axis, cmap='viridis', ppty_name="Volume")
>>> imshow_property(image, vol, cmap='viridis')
timagetk.visu.mplt.intensity_histogram(image, slice_id=None, axis='z', **kwargs)[source]

Intensity distribution as histogram and cumulative histogram.

Uses matplotlib.hist() and _multiple_plots if more than one image is given.

Parameters:
  • image (numpy.ndarray or timagetk.components.spatial_image.SpatialImage) – Image to use to generate the histogram, can also be a list.

  • slice_id (int, optional) – Use all slices by default (None), else the z-slice to get for the histogram.

  • axis (str, optional) – Axis to use when specifying a slice_id, 'z' by default.

  • title (list of str) – A list of titles to use as sub-figures titles, usually used when a list of images is given.

  • suptitle (str) – A general title placed above the sub-figures titles, usually used when a list of images is given.

  • axe (plt.axes) – Matplotlib axes to use with _multiple_plots, then no_show should be True.

  • max_per_line (int) – Number of figure per line when using more than one images, default is 4.

  • thumb_size (float) – Image size in inch, default is 5.

  • no_show (bool) – If True``do not call the blocking 'show' method. Default is ``False.

  • no_left_ylab (bool) – If True``remove the left y-axis label. Default is ``False.

  • no_right_ylab (bool) – If True``remove the right y-axis label. Default is ``False.

Examples

>>> from timagetk.io.util import shared_data
>>> from timagetk.io import imread
>>> from timagetk.visu.mplt import intensity_histogram
>>> import matplotlib.pyplot as plt
>>> img = imread(shared_data("p58-t0-a0.lsm", "p58"))
>>> intensity_histogram(img)
>>> intensity_histogram(img, slice_id=5, axis="z")
>>> from timagetk.algorithms.exposure import global_contrast_stretch
>>> stretch_img = global_contrast_stretch(img)
>>> intensity_histogram([img, stretch_img], suptitle="Effect of global stretching on intensity distribution")
timagetk.visu.mplt.plot_img_and_hist(image, cmap='gray', suptitle='', title='', **kwargs)[source]

Plot an image along with its histogram and cumulative histogram.

Example from .. [#] https://scikit-image.org/docs/stable/auto_examples/color_exposure/plot_local_equalize.html#sphx-glr-auto-examples-color-exposure-plot-local-equalize-py

Parameters:
  • image (timagetk.components.spatial_image.SpatialImage) – 2D image to represent.

  • cmap (str or list of str, optional) – Colormap to use, see the stack_browser notes for advised colormaps.

  • suptitle (str, optional) – If provided (default is empty), add this string of characters as figure title.

  • title (str, optional) – If provided (default is empty), add this string of characters as image title.

  • axe (plt.axes) – Two matplotlib axes to use to plot the image and the histogram.

  • extent (list of float) – If provided (default, None), set the extent of the displayed image. By default, use the real unit extent of the SpatialImage istance.

  • data (numpy.ndarray) – An array of date used to create the histograms.

  • threshold (None or float) – A theshold value to display on the histogram.

Notes

As Numpy and Matplotlib have different axis order convention, we transpose the first two axis of the given numpy array to display the first axis (rows, ‘X’) horizontally per the usual plotting convention.

Examples

>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_dataset
>>> from timagetk.visu.mplt import plot_img_and_hist
>>> fname = 'p58-t0-a0.lsm'
>>> image_path = shared_dataset("p58",'intensity')[0]
>>> img = imread(image_path)
>>> # - Display the middle z-slice of the 3D image, with 'viridis' colormap:
>>> mid_z = img.get_slice(img.get_shape('z')//2, 'z')
>>> ax_img, ax_hist, ax_cdf = plot_img_and_hist(mid_z, cmap='viridis')
>>> # - Create a top z-axis projection to display the 3D image and show the 3D image histograms:
>>> from timagetk.visu.projection import projection
>>> proj = projection(img, method='contour', orientation=1)
>>> ax_img, ax_hist, ax_cdf = plot_img_and_hist(proj, data=img)
timagetk.visu.mplt.plot_profiles(image, axe, x=None, y=None, z=None, title='', vmin=None, vmax=None)[source]

Plot a profile of given line coordinates.

The profile is the line at the intersection of the two planes. You thus need to specify two , and only two of the three axis. They act as numpy array index.

Parameters:
  • axe

  • title

  • image (timagetk.components.spatial_image.SpatialImage) – Image to use to plot the profile.

  • x (int, optional) – X-axis plane coordinates.

  • y (int, optional) – Y-axis plane coordinates.

  • z (int, optional) – Z-axis plane coordinates.

  • vmin (int | float, optional) – Minimum value to use in colormap.

  • vmax (int | float, optional) – Maximum value to use in colormap.

Examples

>>> import matplotlib.pyplot as plt
>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_data
>>> from timagetk.visu.mplt import plot_profiles
>>> image_path = shared_dataset("p58")[0]
>>> image = imread(image_path)
>>> plt.figure(figsize=[9., 5.])
>>> ax = plt.subplot()
>>> # Plot the original profile and the equalized one:
>>> ax = plot_profiles(image, ax, x=int(image.get_shape('x')/2.), z=40, title="original")
>>> from timagetk.algorithms.exposure import equalize_adapthist
>>> eq_img = equalize_adapthist(image)
>>> ax = plot_profiles(eq_img, ax, x=int(image.get_shape('x')/2.), z=40, title="equalized")
>>> from timagetk.algorithms.linearfilter import gaussian_filter
>>> std = 1.
>>> smooth_img = gaussian_filter(image, sigma=std, real=True)
>>> ax = plot_profiles(smooth_img, ax, x=int(image.get_shape('x')/2.), z=40, title="smoothed({}um)".format(std))
>>> eq_smooth_img = equalize_adapthist(gaussian_filter(image, sigma=std, real=True))
>>> ax = plot_profiles(eq_smooth_img, ax, x=int(image.get_shape('x')/2.), z=40, title="equalized & smoothed({}um)".format(std))
>>> plt.legend()
>>> plt.show()
timagetk.visu.mplt.profile_details(image, x=None, y=None, z=None, title='', vmin=None, vmax=None, plane='z', figname='', **kwargs)[source]

Plot a profile of given line coordinates and an image zoom-in around it.

The profile is the line at the intersection of the two planes. You thus need to specify two , and only two of the three axis. They act as numpy array index. The ‘plane’ define which one will be used for the image display.

Parameters:
  • image (timagetk.components.spatial_image.SpatialImage) – Image to use to plot the profile.

  • x (int, optional) – X-axis plane coordinates.

  • y (int, optional) – Y-axis plane coordinates.

  • z (int, optional) – Z-axis plane coordinates.

  • title (str, optional) – Title to give to the figure.

  • vmin (int | float, optional) – Minimum value to use in colormap.

  • vmax (int | float, optional) – Maximum value to use in colormap.

  • plane (str, optional) – Plane to use for image display.

  • figname (str, optional) – If provided (default is empty), the image will be saved under this filename.

  • zone (int) – Width of the zone around the line.

  • cmap (str) – Colormap to use, see the notes of stack_browser for advised colormaps.

Examples

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from matplotlib import gridspec
>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_data
>>> from timagetk.visu.mplt import profile_details
>>> image_path = shared_dataset("p58")[0]
>>> image = imread(image_path)
>>> # Plot the profile details:
>>> profile_details(image, x=int(image.get_shape('x')/2.), z=40, title="original")
timagetk.visu.mplt.profile_hmin(image, x=None, y=None, z=None, title='', intensity_range='auto', plane='z', **kwargs)[source]

Plot a profile of given line coordinates and an image zoom-in around it.

The profile is the line at the intersection of the two planes. You thus need to specify two , and only two of the three axis. They act as numpy array index. The ‘plane’ define which one will be used for the image display.

Parameters:
  • image (timagetk.components.spatial_image.SpatialImage) – Image to use to plot the profile

  • x (int, optional) – X-axis plane coordinates.

  • y (int, optional) – Y-axis plane coordinates.

  • z (int, optional) – Z-axis plane coordinates.

  • title (str, optional) – Title to give to the figure, e.g. the file name, default is empty.

  • intensity_range (str | list, optional) – Define the range of values used by the colormap, by default ‘type’.

  • plane (str, optional) – Plane to use for image display.

  • zone (int) – Width of the zone around the line.

  • cmap (str) – Colormap to use, see the notes of stack_browser for advised colormaps.

  • no_show (bool) – If True, do not call plt.show() automatically.

  • hmin_max (int) – Change the slider max value of h-minima.

  • hmin_init (int) – Change the slider initial value of h-minima.

  • hmin_step (int) – Change the slider step value of h-minima.

Examples

>>> import numpy as np
>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_data
>>> from timagetk.visu.mplt import profile_hmin
>>> fname = 'p58-t0-a0.lsm'
>>> image_path = shared_data(fname, "p58")
>>> image = imread(image_path)
>>> zslice = 40
>>> x_coord = int(image.get_shape('x')/2.)
>>> # - Interactive 'h-min' search on 'original' image:
>>> profile_hmin(image, x=x_coord, z=zslice, title=fname)
>>> # - Interactive 'h-min' search on 'smoothed' image:
>>> from timagetk.algorithms.linearfilter import gaussian_filter
>>> smooth_img = gaussian_filter(image, sigma=1., real=True)
>>> profile_hmin(smooth_img, x=x_coord, z=zslice, title=fname+" - smoothed")
>>> # - Interactive 'h-min' search on 'isometric & smoothed' image:
>>> from timagetk.algorithms.linearfilter import gaussian_filter
>>> from timagetk.algorithms.resample import isometric_resampling
>>> iso_smooth_img = gaussian_filter(isometric_resampling(image), sigma=0.3, real=True)
>>> iso_zslice = iso_smooth_img.get_shape('z') / image.get_shape('z') * zslice
>>> profile_hmin(iso_smooth_img, x=x_coord, z=iso_zslice, title=fname+" - isometric & smoothed")
>>> # - Interactive 'h-min' search on 'isometric, smoothed & equalized' image:
>>> from timagetk.algorithms.exposure import equalize_adapthist
>>> iso_smooth_eq_img = equalize_adapthist(iso_smooth_img)
>>> profile_hmin(iso_smooth_eq_img, x=x_coord, z=iso_zslice, title=fname+" - isometric, smoothed & equalized'")
timagetk.visu.mplt.slice_n_hist(image, title='', img_title='', figname='', vmin=None, vmax=None, **kwargs)[source]

Display a 2D image with value histogram and cumulative histogram.

Parameters:
  • image (numpy.ndarray or timagetk.components.spatial_image.SpatialImage) – 2D image to represent

  • title (str, optional) – If provided (default is empty), add this string of characters as title

  • img_title (str, optional) – If provided (default is empty), add this string of characters as title

  • figname (str, optional) – If provided (default is empty), the image will be saved under this filename.

  • vmin (int or float, optional) – Minimum value to use in colormap

  • vmax (int or float, optional) – Maximum value to use in colormap

  • bins (int) – The number of bins in the histogram. 256 by default.

  • val_range (str or list of str, optional) – Define the range of values used by the colormap, by default type

  • cmap (str or list of str, optional) – Colormap to use, see the stack_browser notes for advised colormaps

Examples

>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_data
>>> from timagetk.visu.mplt import slice_n_hist
>>> fname = 'p58-t0-a0.lsm'
>>> image_path = shared_data(fname, "p58")
>>> img = imread(image_path)
>>> # - Display the middle z-slice of the 3D image, with 'viridis' colormap:
>>> mid_z = img.get_slice(img.get_shape('z')//2, 'z')
>>> slice_n_hist(mid_z, title=img.filename, cmap='viridis')
timagetk.visu.mplt.vignette(image, cmap='gray', **kwargs)[source]

Create a vignette of a 2D image.

Parameters:
  • image (timagetk.components.spatial_image.SpatialImage) – 2D image to represent.

  • cmap (Any) – The Colormap instance or registered colormap name used to map scalar data to colors. This parameter is ignored for RGB(A) data.

  • figname (str) – If a string is given, consider it’s a valid file location (path, name & extension) Do not show the figure, just create, write & close.

  • interpoplation (str) – The interpolation method used. See notes for more details. Defaults to ‘none’.

Stack browsing - Matplotlib interactive visualization

You can access simple interactive stack browsers with the stack module:

Regroup plotting function for browsing stack images.

timagetk.visu.stack.channels_stack_browser(images, channel_names=None, colors=['red', 'green', 'blue', 'yellow', 'cyan', 'magenta'], title='', axis='z', **kwargs)[source]

Multi channel stack browser, by slices along given axis.

Use matplotlib widget (GUI agnostic).

Parameters:
  • images (list of SpatialImage, MultiChannelImage) – List of 3D SpatialImage to browse

  • channel_names (list of str, optional) – List of channel names

  • colors (list of str in DEF_CHANNEL_COLORS, optional) – List of color to use, see combine_channels for known names

  • title (str, optional) – Title to give to the figure, e.g. the file name, default is empty

  • axis (str, in ['x', 'y', 'z']) – Axis to use for slicing

  • init_slice (int) – Slice id to use as starting point, should be inferior to max slice number for given axis

  • extent (list of float) – If provided (default, None), set the extent of the displayed image. By default, use the real unit extent of the SpatialImage istance.

See also

visu.util.DEF_CHANNEL_COLORS

the list of available channel colors.

Examples

>>> from timagetk.io.util import shared_data
>>> from timagetk.io import imread
>>> from timagetk.algorithms.blockmatching import blockmatching
>>> from timagetk.visu.stack import channels_stack_browser
>>> from timagetk.algorithms.trsf import apply_trsf
>>> from timagetk.algorithms.quaternion import centered_rotation_trsf
>>> # EXAMPLE: Visualize the registration of a floating image (green) on a reference image (red)
>>> float_img = imread(shared_data('p58-t0-a0.lsm', "p58"))
>>> ref_img = imread(shared_data('p58-t0-a1.lsm', "p58"))
>>> trsf_z = centered_rotation_trsf(ref_img, -90, 'z')  # Initialize registration with a -90° rotation along Z
>>> trsf = blockmatching(float_img, ref_img, method='affine', init_trsf=trsf_z)  # Intensity registration
>>> res_img = apply_trsf(float_img, trsf, template_img=ref_img)  # Apply trnsformation to floating image
>>> b = channels_stack_browser([res_img, ref_img], ['t0 on t1', 't1'], ['green', 'red'], "affine registration")
timagetk.visu.stack.orthogonal_view(image, x_slice=None, y_slice=None, z_slice=None, suptitle='', figname='', cmap='gray', **kwargs)[source]

Orthogonal representation of an image by three slices along each axes.

Slice numbering starts at 0 (like indexing).

Parameters:
  • image (numpy.ndarray or timagetk.components.spatial_image.SpatialImage or timagetk.components.multi_channel.MultiChannelImage or timagetk.components.multi_channel.BlendImage) – Image from which to extract the slice.

  • x_slice (int, optional) – Value defining the slice to represent in x direction. By default, the middle of the axis.

  • y_slice (int, optional) – Value defining the slice to represent in y direction. By default, the middle of the axis.

  • z_slice (int, optional) – Value defining the slice to represent in z direction. By default, the middle of the axis.

  • suptitle (str, optional) – If provided (default is empty), add this string of characters as title.

  • figname (str or pathlib.Path, optional) – If provided (default is empty), the image will be saved under this filename.

  • cmap (str) – Colormap to use, see the notes of stack_browser for advised colormaps.

  • val_range ({'type', 'auto'} or list of int) – Define the range of values used by the colormap. Defaults to 'type'. See the “Notes” section for detailled explanations.

  • figsize (tuple) – Lenght two tuple defining desired figure size. Defaults to (10, 10).

  • dpi (int) – The resolution in dots per inch. Defaults to 96.

Notes

Accepted val_range may be:

  • auto, get the min and max value of the image;

  • type (default), get the maximum range from the image.dtype, e.g. ‘uint8’=[0, 255];

  • length-2 list of value, e.g. [10, 200];

Examples

>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_dataset
>>> from timagetk.visu.stack import orthogonal_view
>>> # EXAMPLE 1 - Orthogonal view of a grayscale intensity image:
>>> image = imread(shared_dataset("p58", "intensity")[0])
>>> orthogonal_view(image, suptitle=image.filename)
>>> # EXAMPLE 2 - Orthogonal view of a labelled image:
>>> image = imread(shared_dataset("p58", "segmented")[0])
>>> orthogonal_view(image, cmap='glasbey', val_range='auto', suptitle=image.filename)
timagetk.visu.stack.rgb_stack_browser(image, title='', cmap='gray', val_range=None, axis='z', **kwargs)[source]

RGB stack browser, along last physical dimension.

Use matplotlib widget (GUI agnostic).

Parameters:
  • image (timagetk.BlendImage or timagetk.MultiChannelImage) – An RGB 3D array to browse along its last “physical” dimension P, i.e. not the RGB values.

  • title (str, optional) – Title to give to the figure, e.g. the file name, default is empty

  • cmap (str, optional) – Colormap to use, see the notes for advised colormaps

  • val_range (list(int, int), {'type', 'auto'}, optional) – Minimum and maximum values to use for the colormap, can be given as a list of length 2 values. If None (default), set to ‘auto’ for a LabelledImage, set to ‘type’ for a SpatialImage. See notes for more explanations.

  • axis (str in ['x', 'y', 'z'], optional) – Axis to use for slicing

  • init_slice (int) – Slice id to use as starting point, should be inferior to max slice number for given axis

  • extent (list of float) – If provided (default, None), set the extent of the displayed image. By default, use the real unit extent of the SpatialImage istance.

Notes

As Numpy and Matplotlib have different axis order convention, we transpose the first two axis of the given numpy array to display the first axis (rows, ‘X’) horizontally per the usual plotting convention.

If specified, the xy_ratio is also inverted to match that modification.

Examples

>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_data
>>> from timagetk.visu.stack import rgb_stack_browser
>>> from skimage.color import gray2rgb
>>> fname = 'p58-t0-a0.lsm'
>>> img = imread(shared_data(fname, "p58"))
>>> rgb_img = gray2rgb(img)
>>> # imread return XYZ SpatialImage, the browser will move along the z-plane:
>>> rgb_stack_browser(rgb_img,"z-plane browsing")
>>> # transposing Y & Z axis, the browser will now move along the y-plane:
>>> rgb_stack_browser(rgb_img.transpose((0,2,1,3)),"y-plane browsing")
>>> # Better example with an actual RGB image
>>> from timagetk.components.multi_channel import label_blending
>>> from timagetk.tasks.segmentation import watershed_segmentation
>>> from timagetk.components.multi_channel import label_blending
>>> img = imread(shared_data("p58-t0-a0.lsm", "p58"))
>>> vx, vy, vz = img.voxelsize
>>> seg_img = watershed_segmentation(img, hmin=10)
>>> blend = label_blending(seg_img, img)
>>> b = rgb_stack_browser(blend,"Intensity & segmentation blending",xy_ratio=vx/vy)
timagetk.visu.stack.slider(label, mini, maxi, init, step=1, fmt='%1.0f')[source]

Matplotlib slider creation.

Parameters:
  • label (str) – Name of the slider

  • mini (int) – Min value of the slider

  • maxi (int) – Max value of the slider

  • init (int) – Initial value of the slider

  • step (int, optional) – Step value of the slider

  • fmt (str, optional) – Formatting of the displayed value selected by the slider

Notes

The parameter step is not accessible for matplotlib version before 2.2.2.

Returns:

matplotlib.widgets.Slider – A matplotlib slider to use in figures to select values

timagetk.visu.stack.stack_browser(image, title='', cmap='gray', val_range=None, axis='z', **kwargs)[source]

Image stack browser, move along given axis, slice by slice.

Use matplotlib widget (GUI agnostic).

Parameters:
  • image (timagetk.components.spatial_image.SpatialImage) – 3D image to browse

  • title (str, optional) – Title to give to the figure, e.g. the file name, default is empty

  • cmap (matplotlib.colors.ListedColormap or str, optional) – Colormap to use, see the notes for advised colormaps

  • val_range (list(int, int), {'type', 'auto'}, optional) – Minimum and maximum values to use for the colormap, can be given as a list of length 2 values. If None (default), set to ‘auto’ for a LabelledImage, set to ‘type’ for a SpatialImage. See the “Notes” section for detailled explanations.

  • axis (str in ['x', 'y', 'z'], optional) – Axis to use for slicing

  • init_slice (int) – Slice id to use as starting point, default to 0. Should be inferior to max slice number for given axis

  • extent (list of float) – If provided (default, None), set the extent of the displayed image. By default, use the real unit extent of the SpatialImage istance.

  • colorbar (bool) – If True (default False), add a colorbar to the figure.

Notes

We advise to use the sequential colormaps, such as:

  • Sequential (2) [mplt_cmap_sequential]: ‘binary’, ‘gist_yarg’, ‘gist_gray’, ‘gray’, ‘bone’, ‘pink’, ‘summer’, ‘Wistia’.

  • Perceptually Uniform Sequential [mplt_cmap_sequential2]: ‘viridis’, ‘plasma’, ‘inferno’, ‘magma’, ‘cividis’.

To understand the differences in “perception” induced by the different colormaps, see: [mplt_cmap_perception]

Accepted str for val_range can be:

  • ‘auto’: get the min and max value of the image;

  • ‘type’: get the maximum range from the image.dtype, e.g. ‘uint8’=[0, 255];

Examples

>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_dataset
>>> from timagetk.visu.stack import stack_browser
>>> fname = shared_dataset("p58", "intensity")[0]
>>> img = imread(fname)
>>> stack_browser(img, fname)
>>> stack_browser(img, fname, axis='x')
>>> from timagetk import LabelledImage
>>> from timagetk.visu.util import greedy_colormap
>>> fname = shared_dataset("p58", "segmented")[0]
>>> img = imread(fname, LabelledImage, not_a_label=0)
>>> stack_browser(img, fname, cmap=greedy_colormap(img), init_slice=80)
>>> from timagetk.visu.stack import stack_browser
>>> from timagetk.visu.util import greedy_colormap
>>> from timagetk.array_util import dummy_labelled_image_3D
>>> img = dummy_labelled_image_3D((0.2, 0.5, 0.5))  # ZYX sorted voxel-sizes
>>> cmap = greedy_colormap(img)
>>> stack_browser(img, "Dummy", cmap=cmap , init_slice=2)

References

timagetk.visu.stack.stack_browser_threshold(image, title='', cmap='gray', val_range=None, axis='z', **kwargs)[source]

Stack browser, by slices along given axis.

Use matplotlib widget (GUI agnostic).

Parameters:
  • image (timagetk.SpatialImage) – 3D image to browse

  • title (str, optional) – Title to give to the figure, e.g. the file name, default is empty

  • cmap (str, optional) – Colormap to use, see the notes for advised colormaps

  • val_range (list(int, int), {'type', 'auto'}, optional) – Minimum and maximum values to use for the colormap, can be given as a list of length 2 values. If None (default), set to ‘auto’ for a LabelledImage, set to ‘type’ for a SpatialImage. See notes for more explanations.

  • axis (str in ['x', 'y', 'z'], optional) – Axis to use for slicing

  • init_slice (int) – Slice id to use as starting point, should be inferior to max slice number for given axis

  • extent (list of float) – If provided (default, None), set the extent of the displayed image. By default, use the real unit extent of the SpatialImage istance.

Notes

We advise to use the sequential colormaps, such as:

  • Sequential (2) [mplt_cmap_sequential]: ‘binary’, ‘gist_yarg’, ‘gist_gray’, ‘gray’, ‘bone’, ‘pink’, ‘summer’, ‘Wistia’.

  • Perceptually Uniform Sequential [mplt_cmap_sequential2]: ‘viridis’, ‘plasma’, ‘inferno’, ‘magma’, ‘cividis’.

To understand the differences in “perception” induced by the different colormaps, see: [mplt_cmap_perception]

Accepted str for val_range can be:

  • ‘auto’: get the min and max value of the image;

  • ‘type’: get the maximum range from the image.dtype, e.g. ‘uint8’=[0, 255];

Examples

>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_data
>>> from timagetk.visu.stack import stack_browser_threshold
>>> fname = 'p58-t0-a0.lsm'
>>> img = imread(shared_data(fname, "p58"))
>>> b = stack_browser_threshold(img, fname)  # do not forget to assign to a variable because "you need to keep the sliders around globally"

References

timagetk.visu.stack.stack_panel(image, axis='z', step=1, start=0, stop=-1, **kwargs)[source]

Create a panel of slices taken from image along given axis.

Parameters:
  • image (timagetk.components.spatial_image.SpatialImage or timagetk.components.spatial_image.LabelledImage or timagetk.components.multi_channel.BlendImage or timagetk.components.multi_channel.MultiChannelImage) – Image to represent as a panel of slices

  • axis (str, optional) – Axis along which to move to get the slices to display, default is ‘z’

  • step (int, optional) – Slices step, default is 1

  • start (int, optional) – Starting slice, default is first

  • stop (int, optional) – Stopping slice, default is last

  • suptitle (str) – A general title placed above the sub-figures titles, usually used when a list of images is given

  • max_per_line (int) – Number of figure per line when using more than one images. Defaults to 4.

  • thumb_size (float) – Image size in inch (default=5.)

  • val_range ({'auto', 'type'} or list of int, optional) – Define the range of values used by the colormap. Defaults to 'type'. See the “Notes” section for detailled explanations.

  • cmap (str) – Colormap to use, see the stack_browser notes for advised colormaps

  • figname (str, optional) – If provided (default is empty), the image will be saved under this filename.

Raises:

ValueError – If given start value is above axis max dimension - step

Notes

Accepted val_range may be:

  • auto, get the min and max value of the image;

  • type (default), get the maximum range from the image.dtype, e.g. ‘uint8’=[0, 255];

  • length-2 list of value, e.g. [10, 200];

Examples

>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_dataset
>>> from timagetk.visu.stack import stack_panel
>>> img = imread(shared_dataset("p58", "intensity")[0])
>>> stack_panel(img, axis="z", step=5)
>>> stack_panel(img, axis="z", step=5, suptitle=img.filename)
>>> stack_panel(img, axis="x", step=10, suptitle=img.filename)
>>> from timagetk import LabelledImage
>>> from timagetk.components.multi_channel import label_blending
>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_dataset
>>> from timagetk.visu.stack import rgb_stack_browser
>>> from timagetk.visu.stack import stack_panel
>>> int_path = shared_dataset("sphere", 'intensity')[0]
>>> seg_path = shared_dataset("sphere", 'segmented')[0]
>>> int_img = imread(int_path)
>>> seg_img = LabelledImage(imread(seg_path), not_a_label=0)
>>> blend = label_blending(seg_img, int_img)
>>> stack_panel(blend, step=10, suptitle="Intensity & segmentation blending")
>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_dataset
>>> from timagetk.algorithms.blockmatching import blockmatching
>>> from timagetk.algorithms.trsf import apply_trsf
>>> from timagetk.visu.stack import stack_panel
>>> int_imgs = shared_dataset("p58", "intensity")
>>> flo_img = imread(int_imgs[0])
>>> ref_img = imread(int_imgs[1])
>>> rigid_trsf = blockmatching(flo_img, ref_img, method='rigid')
>>> reg_img = apply_trsf(flo_img, rigid_trsf, template_img=ref_img, interpolation='linear')
>>> from timagetk import MultiChannelImage
>>> mc = MultiChannelImage([reg_img, ref_img], channel_names=['Registered', 'Reference'])
>>> stack_panel(mc, axis="z", step=mc.get_shape("z")//5)

Stack browsing - Creating animations

You can create GIFs and .mp4 videos (x264 codec) with the animations module:

Nuclei - Quantitative signal

You can visualize quantitative information about nuclei signal with the functions of the nuclei module:

timagetk.visu.nuclei.channel_signal(nuclei_array, nuclei_signal, channel_image, channel_name, cmap='viridis', figname='')[source]

Create a figure with the channel image and the quantified signals.

Parameters:
  • nuclei_array (numpy.ndarray) – The X,Y(,Z) coordinates of the nuclei.

  • nuclei_signal (numpy.ndarray) – The quantified nuclei signals.

  • channel_image (timagetk.components.spatial_image.SpatialImage or timagetk.MultiChannelImage) – The channel intensity image used to quantify the nuclei signal.

  • channel_name (str) – Name of the channel image.

  • cmap (str or list of str, optional) – Name of the colormap to use for the nuclei scatter plot, ‘viridis’ by default. See notes for advised color maps.

  • figname (str or pathlib.Path) – If a string is given, consider it’s a valid file location (path, name & extension) Do not show the figure, just create, write & close.

Notes

We advise to use the sequential color maps, such as:

  • Sequential (2) [mplt_cmap_sequential]: ‘binary’, ‘gist_yarg’, ‘gist_gray’, ‘gray’, ‘bone’, ‘pink’, ‘summer’, ‘Wistia’.

  • Perceptually Uniform Sequential [mplt_cmap_sequential2]: ‘viridis’, ‘plasma’, ‘inferno’, ‘magma’, ‘cividis’.

To understand the differences in “perception” induced by the different color maps, see: [mplt_cmap_perception]

Examples

>>> from timagetk.visu.nuclei import channel_signal
>>> from timagetk.tasks.nuclei_detection import nuclei_detection
>>> from timagetk.tasks.nuclei_detection import compute_nuclei_channel_intensities
>>> from timagetk.synthetic_data.nuclei_image import example_nuclei_signal_images
>>> from timagetk import MultiChannelImage
>>> nuclei_img, signal_img = example_nuclei_signal_images(n_points=30, extent=20., signal_type='random')
>>> nuclei_arr, _ = nuclei_detection(nuclei_img)
>>> image = MultiChannelImage([nuclei_img, signal_img], channel_names=['tag', 'signal'])
>>> nuclei_sig, _ = compute_nuclei_channel_intensities(image, nuclei_arr, ['signal'])
>>> channel_signal(nuclei_arr, nuclei_sig["signal"], image, "signal", cmap='gray')
timagetk.visu.nuclei.nuclei_signals(nuclei_array, nuclei_signals, x_extent, y_extent, cmap='viridis', figname='')[source]

Create scatter plot(s) of quantified nuclei signal(s).

Parameters:
  • nuclei_array (numpy.ndarray) – The X,Y(,Z) coordinates of the nuclei.

  • nuclei_signals (dict) – The dictionary of quantified nuclei signals with signal(s) name(s) as key(s).

  • x_extent (int or float) – The extent of the x-axis.

  • y_extent (int or float) – The extent of the y-axis.

  • cmap (str or list of str, optional) – Name of the colormap to use, ‘viridis’ by default. See notes for advised color maps.

  • figname (str or pathlib.Path) – If a string is given, consider it’s a valid file location (path, name & extension) Do not show the figure, just create, write & close.

Notes

We advise to use the sequential color maps, such as:

  • Sequential (2) [mplt_cmap_sequential]: ‘binary’, ‘gist_yarg’, ‘gist_gray’, ‘gray’, ‘bone’, ‘pink’, ‘summer’, ‘Wistia’.

  • Perceptually Uniform Sequential [mplt_cmap_sequential2]: ‘viridis’, ‘plasma’, ‘inferno’, ‘magma’, ‘cividis’.

To understand the differences in “perception” induced by the different color maps, see: [mplt_cmap_perception]

Examples

>>> from timagetk.visu.nuclei import nuclei_signals
>>> from timagetk.tasks.nuclei_detection import nuclei_detection
>>> from timagetk.tasks.nuclei_detection import compute_nuclei_channel_intensities
>>> from timagetk.synthetic_data.nuclei_image import example_nuclei_signal_images
>>> from timagetk import MultiChannelImage
>>> nuclei_img, signal_img = example_nuclei_signal_images(n_points=30, extent=20., signal_type='random')
>>> nuclei_arr, _ = nuclei_detection(nuclei_img)
>>> image = MultiChannelImage([nuclei_img, signal_img], channel_names=['tag', 'signal'])
>>> nuclei_sig, _ = compute_nuclei_channel_intensities(image, nuclei_arr, ['signal'])
>>> nuclei_signals(nuclei_arr, nuclei_sig, image.get_extent('x'), image.get_extent('y'))

Time series & time lapse

This module contains tools to generate 2D intensity projections for a time series of grayscale images.

timagetk.visu.temporal_projection.mips2gif(mips, gif_fname, fps=1.0, reshape=None)[source]

Write an animated GIF file from the sequence of mips.

Parameters:
  • mips (list(SpatialImages)) – List of MIPs, i.e. 2D projections of images

  • gif_fname (str) – Name of the gif file to write

  • fps (float, optional) – Frame per second, default is 1.

  • reshape (list, optional) – The shape of the GIF image to return, e.g. [256, 256]

Notes

If your images have different shapes, you should register them over the temporal sequence or specify a shape to apply to all images so they all fit in the GIF.

Examples

>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_dataset
>>> from timagetk.visu.temporal_projection import sequence_projections
>>> from timagetk.visu.temporal_projection import mips2gif
>>> times = shared_dataset("p58", "time-points")
>>> list_fnames = shared_dataset("p58", "intensity")
>>> list_images = [imread(fname) for fname in list_fnames]
>>> # Register image list then generates the max intensity projections:
>>> mips = sequence_projections(list_images, threshold_value=45, register=True)
>>> # Example #1 - Generate GIF animation:
>>> from timagetk.io.util import shared_data
>>> mips2gif(mips, shared_data("p58_TimeLapse.gif", "p58"))
>>> # Example #2 - Generate GIF animation and control the final size to 265x256:
>>> mips2gif(mips, shared_data("p58_TimeLapse.gif", "p58"), reshape=[256, 256])
timagetk.visu.temporal_projection.sequence_projections(list_img, method='contour', register=False, export_png=False, **kwargs)[source]

Get the list of Max Intensity Projections from list of images.

Parameters:
  • list_img (list of SpatialImage) – List of 3D image to project.

  • method (str, optional) – Method to use for projection, see PROJECTION_METHODS for available methods.

  • register (bool, optional) – If True, default is False, performs a rigid sequence registration before generating MIPs.

  • export_png (bool, optional) – If True, default is False, export the individual MIPs as PNG files.

  • axis ({'x', 'y', 'z'}) – Axis to use for projection.

  • invert_axis (bool) – If True, revert the selected axis before projection.

  • threshold (int) – Threshold to use with the ‘contour’ method.

Returns:

list – 2D SpatialImage

See also

timagetk.visu.projection.PROJECTION_METHODS

Examples

>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_dataset
>>> from timagetk.tasks.registration import sequence_registration
>>> from timagetk.visu.temporal_projection import sequence_projections
>>> from timagetk.visu.mplt import grayscale_imshow
>>> times = shared_dataset("p58", "time-points")
>>> list_fnames = shared_dataset("p58", "intensity")
>>> list_images = [imread(fname) for fname in list_fnames]
>>> # Generates the max intensity projections:
>>> mips = sequence_projections(list_images, method='maximum')
>>> grayscale_imshow(mips)
>>> # Generates & save the max intensity projections as PNGs:
>>> mips = sequence_projections(list_images, threshold=45, export_png=True)
>>> # Register image list then generates & save the max intensity projections as PNGs:
>>> mips = sequence_projections(list_images, threshold=45, register=True, export_png=True)

Matplotlib - Intensity profiles

You will find method to render intensity profile figures with the profiles module:

timagetk.visu.profiles.slices_profile(image, axis='z', method=None)[source]

Plot the intensity profile by slices.

The selected method determine the type of function applied to each slice.

Parameters:
  • image (timagetk.components.spatial_image.SpatialImage) – A 3D image to use for profile display.

  • axis (str in {'x', 'y', 'z'}) – The axis to use.

  • method (str or list in {'mean', 'sum', 'median'}) – The (list of) function to apply to each slice for the profile(s).

Notes

Beware of the scale of the profile values if you are using more than one method. For example ‘sum’ will have much higher values than ‘mean’ and the corresponding ‘mean’ curve would appear flat at the bottom.

Examples

>>> from timagetk.visu.profiles import slices_profile
>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_dataset
>>> # - Get 'p58' shared intensity image:
>>> image = imread(shared_dataset("p58")[0])
>>> slices_profile(image, 'z', method=['mean', 'median'])
>>> slices_profile(image, 'y', method=['mean', 'median'])
>>> slices_profile(image, 'x', method=['mean', 'median'])
timagetk.visu.profiles.slices_profile_boxplot(image, axis='z', method=None)[source]

Plot the intensity profile by slices.

The selected method determine the type of function applied to each slice.

Parameters:
  • image (timagetk.components.spatial_image.SpatialImage) – A 3D image to use for profile display.

  • axis (str in {'x', 'y', 'z'}) – The axis to use.

  • method (str or list in {'mean', 'sum', 'median'}) – The (list of) function to apply to each slice for the profile(s).

Notes

Beware of the scale of the profile values if you are using more than onemethod. For example ‘sum’ will have much higher values than ‘mean’ and the corresponding ‘mean’ curve would appear flat at the bottom.

Examples

>>> from timagetk.visu.profiles import slices_profile_boxplot
>>> from timagetk.io import imread
>>> from timagetk.io.util import shared_dataset
>>> # - Get 'p58' shared intensity image:
>>> image = imread(shared_dataset("p58")[0])
>>> slices_profile_boxplot(image.get_region([0, 5, 0, 10, 0, 10]), 'z')
>>> slices_profile_boxplot(image, 'z')
>>> slices_profile_boxplot(image.get_region([0, 5, 0, 10, 0, 10]), 'y')
>>> slices_profile_boxplot(image, 'x')