Package scm_confocal

Sub-modules

scm_confocal.util

Classes

class sp8_image (filename, image)

Subclass of sp8_lif for relevant attributes and functions for a specific image in the .lif file. Should not be called directly, but rather be obtained through sp8_lif.get_image()

Parameters

filename : str
file name of the parent .lif file
image : int
index number of the image in the parent .lif file

Attributes

image : int
index number of the image in the parent .lif file
lifimage : readlif.LifImage class instance
The underlying class instance of the readlif library.

Additionally, attributes and functions of the parent sp8_lif instance are inherited and directly accessible, as well as all attributes of the readlif.LifImage instance.

inherit all functions and attributes from parent sp8_lif class and add some image specific ones

Ancestors

  • scm_confocal.sp8.sp8_lif

Methods

def export_with_scalebar(self, frame=0, channel=0, filename=None, **kwargs)

saves an exported image of the confocal slice with a scalebar in one of the four corners, where barsize is the scalebar size in data units (e.g. µm) and scale the overall size of the scalebar and text with respect to the width of the image. Additionally, a colormap is applied to the data for better visualisation.

Parameters

frame : int, optional
index of the frame to export. The default is 0.
channel : int or list of int, optional
the channel to pull the image data from. For displaying multiple channels in a single image, a list of channel indices can be given, as well as a list of colormaps for each channel through the cmap parameter. The default is 0.
filename : string or None, optional
Filename + extension to use for the export file. The default is the filename sans extension of the original .lif file, with image name and '_exported.png' appended.
crop : tuple or None, optional

range describing a area of the original image (before rescaling the resolution) to crop out for the export image. Can have two forms:

  • ((xmin,ymin),(xmax,ymax)), with the integer indices of the top left and bottom right corners respectively.

  • (xmin,ymin,w,h) with the integer indices of the top left corner and the width and heigth of the cropped image in pixels (prior to optional rescaling using resolution).

The default is None which takes the entire image.

crop_unit : 'pixels' or 'data', optional
sets the unit in which the width and height in crop are specified when using the (x,y,w,h) format, with 'pixels' to give the size in pixels or 'data' to specify the size in the physical unit used for the scalebar (after optional unit conversion via the convert parameter). Note that the position of the top left corner is given in pixels. The ((xmin,ymin),(xmax,ymax)) format must be always given in pixels, and crop_unit is ignored if crop is given in this format. The default is 'pixels'.
resolution : int, optional
the resolution along the x-axis (i.e. image width in pixels) to use for the exported image. The default is None, which uses the size of the original image (after optional cropping using crop).
cmap : str or callable or list of str or list of callable, optional

name of a named Matplotlib colormap used to color the data. see the Matplotlib documentation for more information. The default is 'inferno'.

In addition to the colormaps listed there, the following maps for linearly incrementing pure RGB channels are available, useful for e.g. displaying multichannel data with complementary colors (no overlap between between colormaps possible): ['pure_reds', 'pure_greens', 'pure_blues', 'pure_yellows', 'pure_cyans', 'pure_purples','pure_greys'] where for example 'pure_reds' scales between RGB values (0,0,0) and (255,0,0), and 'pure_cyans' between (0,0,0) and (0,255,255).

Alternatively, a fully custom colormap may be used by entering a ListedColormap or LinearSegmentedColormap object from the Matplotlib.colors module. For more information on creating colormaps, see the Matplotlib documentation linked above.

For multichannel data, a list of colormaps must be provided, with a separate colormap for each channel.

cmap_range : tuple of form (min,max) or None or 'automatic', optional
sets the scaling of the colormap. The minimum and maximum values to map the colormap to, values outside of this range will be colored according to the min and max value of the colormap. The default is None, which is to take the lowest and highest value in the image. Alternatively 'automatic' may be specified which scales between the 10th and 99th percentile. For multichannel data a list of cmap_range options per channel may be provided.
draw_bar : boolean, optional
whether to draw a scalebar on the image, such that this function may be used to put other text on the image or just to apply a colormap (by setting draw_bar=False and draw_text=False). The default is True.
barsize : float or None, optional
size (in data units matching the original scale bar, e.g. nm) of the scale bar to use. The default None, wich takes the desired length for the current scale (ca. 15% of the width of the image for scale=1) and round this to the nearest option from a list of "nice" values.
scale : float, optional
factor to change the size of the scalebar+text with respect to the width of the image. Scale is chosen such, that at scale=1 the font size of the scale bar text is approximately 10 pt when the image is printed at half the width of the text in a typical A4 paper document (e.g. two images side-by-side). Note that this is with respect to the output image, so after optional cropping and/or up/down sampling has been applied. The default is 1.
loc : int, one of [0,1,2,3], optional
Location of the scalebar on the image, where 0, 1, 2 and 3 refer to the top left, top right, bottom left and bottom right respectively. The default is 2, which is the bottom left corner.
convert : str, one of ['fm','pm','Å' or A,'nm','µm' or 'um','mm','cm','dm','m'], optional
Unit that will be used for the scale bar, the value will be automatically converted if this unit differs from the pixel size unit. The default is None, which uses micrometers.
barcolor : tuple of ints, optional
RGB color to use for the scalebar and text, given as a tuple of form (R,G,B) or (R,G,B,A) where R, G B and A are values between 0 and 255 for red, green, blue and alpha respectively. The default is (255,255,255), which gives a white scalebar.
barthickness : int, optional
thickness in printer points of the scale bar itself. The default is 16.
barpad : int, optional
size in printer points of the padding between the scale bar and the surrounding box. The default is 10.
draw_text : bool, optional
whether to draw the text specified in text on the image, the text is place above the scale bar if draw_bar=True. The default is True.
text : str, optional
the text to draw on the image (above the scale bar if draw_bar=True). The default is None, which gives the size and unit of the scale bar (e.g. '10 µm').
font : str, optional
filename of an installed TrueType font ('.ttf' file) to use for the text on the scalebar. The default is 'arialbd.ttf'.
fontsize : int, optional
base font size to use for the scale bar text. The default is 16. Note that this size will be re-scaled according to resolution and scale.
fontcolor : tuple of int, optional
(R,G,B) tuple where R, G and B are red, green and blue values from 0 to 255. The default is (255,255,255) giving white text.
fontbaseline : int, optional
vertical offset for the baseline of the scale bar text in from the top of the scale bar in printer points. The default is 10.
fontpad : int, optional
minimum size in printer points of the space/padding between the text and surrounding box. The default is 10.
draw_box : bool, optional
Whether to put a colored box behind the scalebar and text to enhance contrast on busy images. The default is False.
boxcolor : tuple of ints, optional
RGB color to use for the box behind/around the scalebar and text, given as a tuple of form (R,G,B) or (R,G,B,A) where R, G B and A are values between 0 and 255 for red, green and blue respectively. If no A is given, boxopacity is used. The default is (0,0,0) which gives a black box.
boxopacity : int, optional
value between 0 and 255 for the opacity/alpha of the box, useful for creating a semitransparent box. The default is 255.
boxpad : int, optional
size of the space/padding around the box (with respect to the sides of the image) in printer points. The default is 10.
save : bool, optional
whether to save the image as file. The default is True.
show_figure : bool, optional
whether to open matplotlib figure windows. The default is True.

Returns

Y×X×4 numpy.array containing the BGRA pixel data
 
def get_channel(self, chl)

get info from the metadata on a specific channel

Parameters

chl : int
index number of the channel.

Returns

channel : dict
dictionary containing all metadata for that channel
def get_channels(self)

parse the images xml data for the channels.

Returns

list of dictionaries
 
def get_detector_settings(self)

Parses the xml metadata for the detector settings.

Returns

dictionary or (in case of multichannel data) a list thereof
 
def get_dimension(self, dim)

Gets the dimension data for a particular dimension of an image. Dimension can be given both as integer index (as specified by the Leica MetaData which may not correspond to the indexing order of the data stack) or as string containing the physical meaning, e.g. 'x-axis', 'time', 'excitation wavelength', etc.

Parameters

dim : int or str
dimension to get metadata of specified as integer or as name.

Returns

dimension : dict
dictionary containing all metadata for that dimension
def get_dimension_steps(self, dim, load_stack_indices=False)

returns a list of corresponding physical values for all steps along a given dimension, e.g. a list of time steps or x coordinates. Dimension can be given both as integer index (as specified by the Leica MetaData, which may not correspond to the indexing order of the data stack), or as string containing the physical meaning, e.g. 'x-axis', 'time', 'excitation wavelength', etc.

Parameters

dim : int or str
dimension to get metadata of specified as integer or as name.

Returns

steps : list of float
physical values of the steps along the chosen dimension, (e.g. a list of pixel x-coordinates, list of time stamps, …).
unit : str
physical unit of the data.
def get_dimension_stepsize(self, dim)

returns the step size along a dimension, e.g. time interval, pixel size, etc, as (value, unit) tuple. Dimension can be given both as integer index (as specified by the Leica MetaData, which may not correspond to the indexing order of the data stack), or as string containing the physical meaning, e.g. 'x-axis', 'time', 'excitation wavelength', etc.

Parameters

dim : int or str
dimension to get metadata of specified as integer or as name.

Returns

stepsize : float
physical size of one step (e.g. pixel, time interval, …).
unit : str
physical unit of the data.
def get_dimensions(self)

parse the images xml data for the dimensions.

Returns

list of dictionaries
 
def get_laser_settings(self)

Parses the xml metadata for the laser settings.

Returns

dictionary with laser data
 
def get_name(self)

shortcut for getting the name of the dataset / image for e.g. automatically generating filenames for stored results.

The format is: <lif file name (without file extension)>_<image name>

def get_pixelsize(self)

shorthand for get_dimension_stepsize() to get the pixel/voxel size converted to micrometer, along whatever spatial dimensions are present in the data in order of slowest to fastest axis, i.e. typically (z,y,x) but e.g. (y,z,x) for an xzy scan. data are skipped.

Returns

pixelsize : tuple of float
physical size in µm of the pixels/voxels along (z,y,x)
def get_stage_position(self)

Returns base (z,y,x) position of the stage in micrometer

def load_frame(self, i=0, channel=None)

returns specified image frame where a frame is considered a 2D image in the plane of the two fastes axes in the recording order (typically xy).

Parameters

i : int, optional
the index number of the requested image. The default is 0.
channel : int or list of int, optional
which channel(s) to return. For multiple channels, a tuple with an numpy.ndarray for each image is returned, for a single channel a single numpy.ndarray is returned. The default is to return all channels.

Returns

frame : numpy.ndarray or tuple of numpy.ndarray
the raw image data values for the requested frame / channel(s)
def load_plane(self, display_dims=None, indices=None)

load 2D plane / slice of arbitrary orientation from the data

Parameters

display_dims : tuple of length 2, optional
the 2 dimensions defining the 2D image plane to load. The default is the imaging plane (the two fastest axes, typically xy).
indices : dict, optional
index values for all other planes. The default is 0 for all dims.

Returns

np.ndarray
array containing the pixel values of the selected plane.
def load_stack(self, dim_range=None, dtype=None, quiet=False)

Similar to sp8_series.load_data(), but converts the 3D array of images automatically to a np.ndarray of the appropriate dimensionality.

Array dimensions are specified as follows:

  • If the number of detector channels is 2 or higher, the first array axis is the detector channel index (named 'channel').

  • If the number of channels is 1, the first array axis is the first available dimension (instead of 'channel').

  • Each subsequent array axis corresponds to a dimension as specified by and in reversed order of the metadata exported by the microscope software, excluding dimensions which are not available. The default order of dimensions in the metadata is:

    1. 'channel' (excluded for single channel data)

    2. 'x-axis'

    3. 'y-axis'

    4. 'z-axis'

    5. 'time'

    6. 'detection wavelength'

    7. 'excitation wavelength'

    8. 'mosaic'

  • As an example, a 2 channel xyt measurement would result in a 4-d array with axis order ('channel','time','y-axis', 'x-axis'), and a single channel xyz scan would be returned as ('z-axis','y-axis','x-axis')

For loading only part of the total dataset, the dim_range parameter can be used to specify a range along any of the dimensions. This will be more memory efficient than loading the entire stack and then discarding part of the data. For slicing along the x or y axis this is not possible and whole (xy) images must be loaded prior to discarding data outside the specified x or y axis range.

Parameters

dim_range : dict, optional

dict, with keys corresponding to channel/dimension labels as above and int or slice objects as values. This allows you to only load part of the data along any of the dimensions, such as only loading one channel of multichannel data or a particular z-range. An example use for only taking time steps up to 5 and z-slice 20 to 30 would be:

dim_range={'time':slice(None,5), 'z-axis':slice(20,30)}.

When an int is given, only that slice along the dimension is taken and the dimensionis squeezed out of the data. The default is {}.

dtype : (numpy) datatype, optional
type to scale data to. The default is None which uses the same bit depth as the original image (either 8- or 16-bit unsigned int).

Returns

data : numpy.ndarray
ndarray with the pixel values
dimorder : tuple
tuple with lenght data.ndim specifying the ordering of dimensions in the data with labels from the metadata of the microscope.
def print_metadata(self)

Prints a somewhat formatted version of the full image metadata, the xml hierarchy is indicated with prepended dashes.

def save_metadata(self, filename=None)

stores the image xml metadata to a file

Parameters

filename : str, optional
filename to use. The default is the result of get_name() '_metadata.xml' appended.
class sp8_lif (filename=None, quiet=False)

Class of functions related to the sp8 microscope, for data saved as .lif files, the default file format for the Leica LAS-X software. Essentially a wrapper around the readlif library, which provides access to the data and metadata directly in Python.

The underlying readlif.LifFile instance can be accessed directly using the sp8_lif.liffile attribute, and any of it attributes are accessible through sp8_lif directly.

Parameters

filename : str
Filename of the .lif file. Extension may be (but is not required to be) included.
quiet : bool, optional
can be used to suppress printing the contents of the file. The default is False.

Returns

sp8_lif class instance

Attributes

liffile : readlif.LifFile instance
The underlying class instance of the readlif library.
filename : str
filename of the loaded .lif file with file extention included, even if it was not given when initializing the class.

See Also

sp8_image
a subclass for specific images in the dataset.
readlif
the library used for acessing the files, which can be found here Initialize the class instance and the underlying LifFile instance

Subclasses

  • scm_confocal.sp8.sp8_image

Methods

def get_image(self, image=0)

returns an sp8_image instance containing relevant attributes and functions for the specific image in the dataset, which provides the "bread and butter" of data access.

Parameters

image : int or str, optional
The image (or image series) to obtain. May be given as index number (int) or as the name of the series (string). The default is the first image in the file.

Returns

sp8_image class instance

def get_liffile_image(self, image=0)

returns the readlif.LifImage instance for a particular image in the dataset.

Parameters

image : int or str, optional
The image (or image series) to obtain. May be given as index number (int) or as the name of the series (string). The default is the first image in the file.

Returns

readlif.LifImage class instance

def get_name(self)

shortcut for getting the name (filename sans extention) of the dataset for e.g. automatically generating filenames for stored results.

def save_metadata(self, filename=None)

stores the xml metadata to a file

Parameters

filename : str, optional
filename to use. The default is the name of the Lif file with '_metadata.xml' appended.
class sp8_series (fmt='*.tif')

Class of functions related to the sp8 microscope. The functions assume that the data are exported as .tif files and placed in a own folder per series. The current working directory is assumed to be that folder. For several functions it is required that the xml metadata is present in a subfolder of the working directory called 'MetaData', which is normally generated automatically when exporting tif files as raw data.

Attributes

filenames : list of str
the filenames loaded associated with the series
data : numpy array
the image data as loaded on the most recent call of sp8_series.load_data()
metadata : xml.Elementtree root
the recording parameters associated with the image series

Initialize the class instance and assign the filenames of the data.

Parameters

fmt : str, optional
format to use for finding the files. Uses the notation of the glob library. The default is '*.tif'.

Methods

def export_with_scalebar(self, frame=0, channel=0, filename=None, **kwargs)

saves an exported image of the confocal slice with a scalebar in one of the four corners, where barsize is the scalebar size in data units (e.g. µm) and scale the overall size of the scalebar and text with respect to the width of the image. Additionally, a colormap is applied to the data for better visualisation.

Parameters

frame : int, optional
index of the frame to export. The default is 0.
channel : int or list of int, optional
the channel to pull the image data from. For displaying multiple channels in a single image, a list of channel indices can be given, as well as a list of colormaps for each channel through the cmap parameter. The default is 0.
filename : string or None, optional
Filename + extension to use for the export file. The default is the filename sans extension of the original TEM file, with '_exported.png' appended.
crop : tuple or None, optional

range describing a area of the original image (before rescaling the resolution) to crop out for the export image. Can have two forms:

  • ((xmin,ymin),(xmax,ymax)), with the integer indices of the top left and bottom right corners respectively.

  • (xmin,ymin,w,h) with the integer indices of the top left corner and the width and heigth of the cropped image in pixels (prior to optional rescaling using resolution).

The default is None which takes the entire image.

crop_unit : 'pixels' or 'data', optional
sets the unit in which the width and height in crop are specified when using the (x,y,w,h) format, with 'pixels' to give the size in pixels or 'data' to specify the size in the physical unit used for the scalebar (after optional unit conversion via the convert parameter). Note that the position of the top left corner is given in pixels. The ((xmin,ymin),(xmax,ymax)) format must be always given in pixels, and crop_unit is ignored if crop is given in this format. The default is 'pixels'.
resolution : int, optional
the resolution along the x-axis (i.e. image width in pixels) to use for the exported image. The default is None, which uses the size of the original image (after optional cropping using crop).
cmap : str or callable or list of str or list of callable, optional

name of a named Matplotlib colormap used to color the data. see the Matplotlib documentation for more information. The default is 'inferno'.

In addition to the colormaps listed there, the following maps for linearly incrementing pure RGB channels are available, useful for e.g. displaying multichannel data with complementary colors (no overlap between between colormaps possible): ['pure_reds', 'pure_greens', 'pure_blues', 'pure_yellows', 'pure_cyans', 'pure_purples','pure_greys'] where for example 'pure_reds' scales between RGB values (0,0,0) and (255,0,0), and 'pure_cyans' between (0,0,0) and (0,255,255).

Alternatively, a fully custom colormap may be used by entering a ListedColormap or LinearSegmentedColormap object from the Matplotlib.colors module. For more information on creating colormaps, see the Matplotlib documentation linked above.

For multichannel data, a list of colormaps must be provided, with a separate colormap for each channel.

cmap_range : tuple of form (min,max) or None or 'automatic', optional
sets the scaling of the colormap. The minimum and maximum values to map the colormap to, values outside of this range will be colored according to the min and max value of the colormap. The default is None, which is to take the lowest and highest value in the image. Alternatively 'automatic' may be specified which scales between the 10th and 99th percentile. For multichannel data a list of cmap_range options per channel may be provided.
draw_bar : boolean, optional
whether to draw a scalebar on the image, such that this function may be used to put other text on the image or just to apply a colormap (by setting draw_bar=False and draw_text=False). The default is True.
barsize : float or None, optional
size (in data units matching the original scale bar, e.g. nm) of the scale bar to use. The default None, wich takes the desired length for the current scale (ca. 15% of the width of the image for scale=1) and round this to the nearest option from a list of "nice" values.
scale : float, optional
factor to change the size of the scalebar+text with respect to the width of the image. Scale is chosen such, that at scale=1 the font size of the scale bar text is approximately 10 pt when the image is printed at half the width of the text in a typical A4 paper document (e.g. two images side-by-side). Note that this is with respect to the output image, so after optional cropping and/or up/down sampling has been applied. The default is 1.
loc : int, one of [0,1,2,3], optional
Location of the scalebar on the image, where 0, 1, 2 and 3 refer to the top left, top right, bottom left and bottom right respectively. The default is 2, which is the bottom left corner.
convert : str, one of ['fm','pm','Å' or A,'nm','µm' or 'um','mm','cm','dm','m'], optional
Unit that will be used for the scale bar, the value will be automatically converted if this unit differs from the pixel size unit. The default is None, which uses micrometers.
barcolor : tuple of ints, optional
RGB color to use for the scalebar and text, given as a tuple of form (R,G,B) or (R,G,B,A) where R, G B and A are values between 0 and 255 for red, green, blue and alpha respectively. The default is (255,255,255), which gives a white scalebar.
barthickness : int, optional
thickness in printer points of the scale bar itself. The default is 16.
barpad : int, optional
size in printer points of the padding between the scale bar and the surrounding box. The default is 10.
draw_text : bool, optional
whether to draw the text specified in text on the image, the text is place above the scale bar if draw_bar=True. The default is True.
text : str, optional
the text to draw on the image (above the scale bar if draw_bar=True). The default is None, which gives the size and unit of the scale bar (e.g. '10 µm').
font : str, optional
filename of an installed TrueType font ('.ttf' file) to use for the text on the scalebar. The default is 'arialbd.ttf'.
fontsize : int, optional
base font size to use for the scale bar text. The default is 16. Note that this size will be re-scaled according to resolution and scale.
fontcolor : tuple of int, optional
(R,G,B) tuple where R, G and B are red, green and blue values from 0 to 255. The default is (255,255,255) giving white text.
fontbaseline : int, optional
vertical offset for the baseline of the scale bar text in from the top of the scale bar in printer points. The default is 10.
fontpad : int, optional
minimum size in printer points of the space/padding between the text and surrounding box. The default is 10.
draw_box : bool, optional
Whether to put a colored box behind the scalebar and text to enhance contrast on busy images. The default is False.
boxcolor : tuple of ints, optional
RGB color to use for the box behind/around the scalebar and text, given as a tuple of form (R,G,B) or (R,G,B,A) where R, G B and A are values between 0 and 255 for red, green and blue respectively. If no A is given, boxopacity is used. The default is (0,0,0) which gives a black box.
boxopacity : int, optional
value between 0 and 255 for the opacity/alpha of the box, useful for creating a semitransparent box. The default is 255.
boxpad : int, optional
size of the space/padding around the box (with respect to the sides of the image) in printer points. The default is 10.
save : bool, optional
whether to save the image as file. The default is True.
show_figure : bool, optional
whether to open matplotlib figure windows. The default is True.

Returns

Y×X×4 numpy.array containing the BGRA pixel data
 
def get_dimension_steps(self, dim, load_stack_indices=False)

Gets a list of values for each step along the specified dimension, e.g. a list of timestamps for the images or a list of height values for all slices of a z-stack. For specification of dimensions, see sp8_series.get_metadata_dimension()

Parameters

dim : int or str
dimension to get steps for
load_stack_indices : bool
if True, trims down the list of steps based on the dim_range used when last loading data with load_stack

Returns

steps : list
list of values for every logical step in the data
unit : str
physical unit of the step values
def get_dimension_stepsize(self, dim)

Get the size of a single step along the specified dimension, e.g. the pixelsize in x, y or z, or the time between timesteps. For specification of dimensions, see sp8_series.get_metadata_dimension()

Parameters

dim : int or str
dimension to get stepsize for

Returns

value : float
stepsize
unit : int
physical unit of value
def get_laser_settings(self)

Parses the xml metadata for the laser settings.

Returns

dictionary with laser data
 
def get_metadata_channels(self)

Gets the channel information from the metadata

Returns

channels : list of dict
list of dictionaries with length equal to number of channels where each dict contains the metadata for one channel
def get_metadata_dimension(self, dim)

Gets the dimension data for a particular dimension. Dimension can be given both as integer index (as specified by the Leica exported MetaData which may not correspond to the indexing order of the data stack) or as string containing the physical meaning, e.g. 'x-axis', 'time', 'excitation wavelength', etc.

Parameters

dim : int or str
dimension to get metadata of specified as integer or as name.

Returns

dimension : dict
dictionary containing all metadata for that dimension
def get_metadata_dimensions(self)

Gets the dimension information from the metadata

Returns

dimensions : list of dict
list of dictionaries with length number of dimensions where each dict contains the metadata for one data dimension
def get_name(self)

Returns a string containing the filename (sans file extension) under which the series is saved.

Returns

name : str
name of the series
def get_pixelsize(self)

shorthand for get_dimension_stepsize() to get the pixel/voxel size converted to micrometer, along whatever spatial dimensions are present in the data. Is given as (z,y,x) where dimensions not present in the data are skipped.

Returns

pixelsize : tuple of float
physical size in µm of the pixels/voxels along (z,y,x)
def get_series_name(self)

Deprecated, renamed to get_name()

def load_data(self, filenames=None, first=None, last=None, dtype=numpy.uint8)

Loads the sequence of images into ndarray of form (files,y,x) and converts the data to dtype

Parameters

filenames : list of str, optional
filenames of images to load. The default is what is passed from init, which by default is all .tif images in the current working directory.
first : None or int, optional
index of first image to load. The default is None.
last : None or int, optional
index of last image to load plus one. The default is None.
dtype : (numpy) datatype, optional
type to scale data to. The default is np.uint8.

Returns

data : numpy.ndarray
3d numpy array with dimension order (filenames,y,x).
def load_metadata(self)

Load the xml metadata exported with the files as xml_root object which can be indexed with xml.etree.ElementTree

Returns

metadata : xml.etree.ElementTree object
Parsable xml tree object containing all the metadata
def load_stack(self, dim_range=None, dtype=numpy.uint8)

Similar to sp8_series.load_data(), but converts the 3D array of images automatically to a np.ndarray of the appropriate dimensionality.

Array dimensions are specified as follows:

  • If the number of detector channels is 2 or higher, the first array axis is the detector channel index (named 'channel').

  • If the number of channels is 1, the first array axis is the first available dimension (instead of 'channel').

  • Each subsequent array axis corresponds to a dimension as specified by and in reversed order of the metadata exported by the microscope software, excluding dimensions which are not available. The default order of dimensions in the metadata is:

    1. 'channel' (excluded for single channel data)

    2. 'x-axis'

    3. 'y-axis'

    4. 'z-axis'

    5. 'time'

    6. 'detection wavelength'

    7. 'excitation wavelength'

  • As an example, a 2 channel xyt measurement would result in a 4-d array with axis order ('channel','time','y-axis', 'x-axis'), and a single channel xyz scan would be returned as ('z-axis','y-axis','x-axis')

For loading only part of the total dataset, the dim_range parameter can be used to specify a range along any of the dimensions. This will be more memory efficient than loading the entire stack and then discarding part of the data. For slicing along the x or y axis this is not possible and whole (xy) images must be loaded prior to discarding data outside the specified x or y axis range.

Parameters

dim_range : dict, optional

dict, with keys corresponding to channel/dimension labels as above and int or slice objects as values. This allows you to only load part of the data along any of the dimensions, such as only loading one channel of multichannel data or a particular z-range. An example use for only taking time steps up to 5 and z-slice 20 to 30 would be:

dim_range={'time':slice(None,5), 'z-axis':slice(20,30)}.

When an int is given, only that slice along the dimension is taken and the dimensionis squeezed out of the data. The default is {}.

dtype : (numpy) datatype, optional
type to scale data to. The default is np.uint8.

Returns

data : numpy.ndarray
ndarray with the pixel values
dimorder : tuple
tuple with lenght data.ndim specifying the ordering of dimensions in the data with labels from the metadata of the microscope.
class visitech_faststack (filename, zsize, zstep, zbacksteps, zstart=0, magnification=63, binning=1)

functions for fast stacks taken with the custom MicroManager Visitech driver, saved to multipage .ome.tiff files containing entire stack

initialize class (lazy-loads data)

Parameters

filenames : string
name of first ome.tiff file (extension optional)
zsize : float
z size (in um) of stack (first im to last)
zstep : float
step size in z
zbacksteps : int
number of backwards steps in z direction after each stack
zstart : float
actual height of bottom of stack/lowest slice. The default is 0.
magnification : float, optional
magnification of objective lens used. The default is 63.
binning : int
binning factor performed at the detector level, e.g. in MicroManager software, in XY

Methods

def export_with_scalebar(self, stack=0, zslice=0, filename=None, **kwargs)

saves an exported image of the confocal slice with a scalebar in one of the four corners, where barsize is the scalebar size in data units (e.g. µm) and scale the overall size of the scalebar and text with respect to the width of the image. Additionally, a colormap is applied to the data for better visualisation.

Parameters

stack : int, optional
integer index of the z-stack to take the frame to export from. The default is 0.
zslice : int, optional
integer index of the frame within stack to export. The default is 0.
filename : string or None, optional
Filename + extension to use for the export file. The default is the filename sans extension of the original TEM file, with '_exported.png' appended.
crop : tuple or None, optional

range describing a area of the original image (before rescaling the resolution) to crop out for the export image. Can have two forms:

  • ((xmin,ymin),(xmax,ymax)), with the integer indices of the top left and bottom right corners respectively.

  • (xmin,ymin,w,h) with the integer indices of the top left corner and the width and heigth of the cropped image in pixels (prior to optional rescaling using resolution).

The default is None which takes the entire image.

crop_unit : 'pixels' or 'data', optional
sets the unit in which the width and height in crop are specified when using the (x,y,w,h) format, with 'pixels' to give the size in pixels or 'data' to specify the size in the physical unit used for the scalebar (after optional unit conversion via the convert parameter). Note that the position of the top left corner is given in pixels. The ((xmin,ymin),(xmax,ymax)) format must be always given in pixels, and crop_unit is ignored if crop is given in this format. The default is 'pixels'.
resolution : int, optional
the resolution along the x-axis (i.e. image width in pixels) to use for the exported image. The default is None, which uses the size of the original image (after optional cropping using crop).
cmap : str or callable or list of str or list of callable, optional

name of a named Matplotlib colormap used to color the data. see the Matplotlib documentation for more information. The default is 'inferno'.

In addition to the colormaps listed there, the following maps for linearly incrementing pure RGB channels are available, useful for e.g. displaying multichannel data with complementary colors (no overlap between between colormaps possible): ['pure_reds', 'pure_greens', 'pure_blues', 'pure_yellows', 'pure_cyans', 'pure_purples','pure_greys'] where for example 'pure_reds' scales between RGB values (0,0,0) and (255,0,0), and 'pure_cyans' between (0,0,0) and (0,255,255).

Alternatively, a fully custom colormap may be used by entering a ListedColormap or LinearSegmentedColormap object from the Matplotlib.colors module. For more information on creating colormaps, see the Matplotlib documentation linked above.

For multichannel data, a list of colormaps must be provided, with a separate colormap for each channel.

cmap_range : tuple of form (min,max) or None or 'automatic', optional
sets the scaling of the colormap. The minimum and maximum values to map the colormap to, values outside of this range will be colored according to the min and max value of the colormap. The default is None, which is to take the lowest and highest value in the image. Alternatively 'automatic' may be specified which scales between the 10th and 99th percentile. For multichannel data a list of cmap_range options per channel may be provided.
draw_bar : boolean, optional
whether to draw a scalebar on the image, such that this function may be used to put other text on the image or just to apply a colormap (by setting draw_bar=False and draw_text=False). The default is True.
barsize : float or None, optional
size (in data units matching the original scale bar, e.g. nm) of the scale bar to use. The default None, wich takes the desired length for the current scale (ca. 15% of the width of the image for scale=1) and round this to the nearest option from a list of "nice" values.
scale : float, optional
factor to change the size of the scalebar+text with respect to the width of the image. Scale is chosen such, that at scale=1 the font size of the scale bar text is approximately 10 pt when the image is printed at half the width of the text in a typical A4 paper document (e.g. two images side-by-side). Note that this is with respect to the output image, so after optional cropping and/or up/down sampling has been applied. The default is 1.
loc : int, one of [0,1,2,3], optional
Location of the scalebar on the image, where 0, 1, 2 and 3 refer to the top left, top right, bottom left and bottom right respectively. The default is 2, which is the bottom left corner.
convert : str, one of ['fm','pm','Å' or A,'nm','µm' or 'um','mm','cm','dm','m'], optional
Unit that will be used for the scale bar, the value will be automatically converted if this unit differs from the pixel size unit. The default is None, which uses micrometers.
barcolor : tuple of ints, optional
RGB color to use for the scalebar and text, given as a tuple of form (R,G,B) or (R,G,B,A) where R, G B and A are values between 0 and 255 for red, green, blue and alpha respectively. The default is (255,255,255), which gives a white scalebar.
barthickness : int, optional
thickness in printer points of the scale bar itself. The default is 16.
barpad : int, optional
size in printer points of the padding between the scale bar and the surrounding box. The default is 10.
draw_text : bool, optional
whether to draw the text specified in text on the image, the text is place above the scale bar if draw_bar=True. The default is True.
text : str, optional
the text to draw on the image (above the scale bar if draw_bar=True). The default is None, which gives the size and unit of the scale bar (e.g. '10 µm').
font : str, optional
filename of an installed TrueType font ('.ttf' file) to use for the text on the scalebar. The default is 'arialbd.ttf'.
fontsize : int, optional
base font size to use for the scale bar text. The default is 16. Note that this size will be re-scaled according to resolution and scale.
fontcolor : tuple of int, optional
(R,G,B) tuple where R, G and B are red, green and blue values from 0 to 255. The default is (255,255,255) giving white text.
fontbaseline : int, optional
vertical offset for the baseline of the scale bar text in from the top of the scale bar in printer points. The default is 10.
fontpad : int, optional
minimum size in printer points of the space/padding between the text and surrounding box. The default is 10.
draw_box : bool, optional
Whether to put a colored box behind the scalebar and text to enhance contrast on busy images. The default is False.
boxcolor : tuple of ints, optional
RGB color to use for the box behind/around the scalebar and text, given as a tuple of form (R,G,B) or (R,G,B,A) where R, G B and A are values between 0 and 255 for red, green and blue respectively. If no A is given, boxopacity is used. The default is (0,0,0) which gives a black box.
boxopacity : int, optional
value between 0 and 255 for the opacity/alpha of the box, useful for creating a semitransparent box. The default is 255.
boxpad : int, optional
size of the space/padding around the box (with respect to the sides of the image) in printer points. The default is 10.
save : bool, optional
whether to save the image as file. The default is True.
show_figure : bool, optional
whether to open matplotlib figure windows. The default is True.

Returns

Y×X×4 numpy.array containing the BGRA pixel data
 
def get_metadata(self)

loads OME metadata from visitech .ome.tif file and returns xml tree object

Returns

xml.etree.ElementTree
formatted XML metadata. Can be indexed with xml_root.find('')
def get_pixelsize(self)

shortcut to get (z,y,x) pixelsize with unit

def get_series_name(self)

Returns a name for the series based on the filename.

Returns

str
 
def get_timestamps(self, load_stack_indices=False)

loads OME metadata from visitech .ome.tif file and returns timestamps

Parameters

load_stack_indices : boolean
if True, only returns timestamps from frames which were loaded at call to visitech_faststack.load_stack(), and using the same dimension order / stack shape

Returns

times : numpy (nd)array of floats
list/stack of timestamps for each of the the frames in the data
def load_data(self, indices=slice(None, None, None), dtype=numpy.uint16, xslice=None, yslice=None)

load images from datafile into 3D numpy array

Parameters

indices : slice object or list of ints, optional
which images from tiffstack to load. The default is slice(None,None,None).

Returns

numpy.ndarray containing image data in dim order (im,y,x)
 
def load_stack(self, dim_range={}, dtype=numpy.uint16, remove_backsteps=True, offset=0, force_reshape=False)

Load the data and reshape into 4D stack with the following dimension order: ('time','z-axis','y-axis','x-axis')

For loading only part of the total dataset, the dim_range parameter can be used to specify a range along any of the dimensions. This will be more memory efficient than loading the entire stack and then discarding part of the data. For slicing along the x or y axis this is not possible and whole (xy) images must be loaded prior to discarding data outside the specified x or y axis range.

Parameters

dim_range : dict, optional

dict, with keys corresponding to channel/dimension labels as above and slice objects as values. This allows you to only load part of the data along any of the dimensions, such as only loading two time steps or a particular z-range. An example use for only taking time steps up to 5 and z-slice 20 to 30 would be:

dim_range={'time':slice(None,5), 'z-axis':slice(20,30)}.

The default is {} which corresponds to the full file.

dtype : (numpy) datatype, optional
type to scale data to. The default is np.uint16.
remove_backsteps : bool
whether to discard the frames which were recorded on the backsteps downwards
offset : int
offset the indices by a constant number of frames in case the first im is not the first slice of the first stack
force_reshape : bool
in case of incorrect number of steps during acquisition, you can use this to ignore the reshape-error occuring upon trying to sort 2d images into 4d stack series

Returns

data : numpy.ndarray
ndarray with the pixel values
def save_stack(self, data, filename_prefix='visitech_faststack', sequence_type='multipage')

save stacks to tiff files

Parameters

data : numpy ndarray with 3 or 4 dimensions
image series pixel values with dimension order (z,y,x) or (t,z,y,x)
filename_prefix : string, optional
prefix to use for filename. The time/z-axis index is appended if relevant. The default is 'visitech_faststack'.
sequence_type : {'multipage','image_sequence','multipage_sequence'}, optional

The way to store the data. The following options are available:

- 'image_sequence' : stores as a series of 2D images with time 
and or frame number appended
- 'multipage' : store all data in a single multipage tiff file
- 'multipage_sequence' : stores a multipage tiff file for each 
time step

The default is 'multipage'.

Returns

None, but writes file(s) to working directory.

def yield_stack(self, dim_range={}, dtype=numpy.uint16, remove_backsteps=True, offset=0, force_reshape=False)

Lazy-load the data and reshape into 4D stack with the following dimension order: ('time','z-axis','y-axis','x-axis'). Returns a generator which yields a z-stack for each call, which is loaded upon calling it.

For loading only part of the total dataset, the dim_range parameter can be used to specify a range along any of the dimensions. This will be more memory efficient than loading the entire stack and then discarding part of the data. For slicing along the x or y axis this is not possible and whole (xy) images must be loaded prior to discarding data outside the specified x or y axis range. The shape of the stack can be accessed without loading data using the stack_shape attribute after creating the yield_stack object.

Parameters

dim_range : dict, optional

dict, with keys corresponding to channel/dimension labels as above and slice objects as values. This allows you to only load part of the data along any of the dimensions, such as only loading two time steps or a particular z-range. An example use for only taking time steps up to 5 and z-slice 20 to 30 would be:

dim_range={'time':slice(None,5), 'z-axis':slice(20,30)}.

The default is {} which corresponds to the full file.

dtype : (numpy) datatype, optional
type to scale data to. The default is np.uint16.
remove_backsteps : bool
whether to discard the frames which were recorded on the backsteps downwards
offset : int
offset the indices by a constant number of frames in case the first im is not the first slice of the first stack
force_reshape : bool
in case of incorrect number of steps during acquisition, you can use this to ignore the reshape-error occuring upon trying to sort 2d images into 4d stack series

Returns

zstack : iterable/generator yielding numpy.ndarray
list of time steps, with for each time step a z-stack as np.ndarray with the pixel values
class visitech_series (filename, magnification=63, binning=1)

Functions for image series taken with the multi-D acquisition menu in MicroManager with the Visitech saved to multipage .ome.tiff files. For the custom fast stack sequence use visitech_faststack.

initialize class (lazy-loads data)

Parameters

filenames : string
name of first ome.tiff file (extension optional)
magnification : float, optional
magnification of objective lens used. The default is 63.
binning : int
binning factor performed at the detector level, e.g. in MicroManager software, in XY

Methods

def export_with_scalebar(self, frame=0, filename=None, **kwargs)

saves an exported image of the confocal slice with a scalebar in one of the four corners, where barsize is the scalebar size in data units (e.g. µm) and scale the overall size of the scalebar and text with respect to the width of the image. Additionally, a colormap is applied to the data for better visualisation.

Parameters

frame : int, optional
index of the frame to export. The default is 0.
filename : string or None, optional
Filename + extension to use for the export file. The default is the filename sans extension of the original TEM file, with '_exported.png' appended.
crop : tuple or None, optional

range describing a area of the original image (before rescaling the resolution) to crop out for the export image. Can have two forms:

  • ((xmin,ymin),(xmax,ymax)), with the integer indices of the top left and bottom right corners respectively.

  • (xmin,ymin,w,h) with the integer indices of the top left corner and the width and heigth of the cropped image in pixels (prior to optional rescaling using resolution).

The default is None which takes the entire image.

crop_unit : 'pixels' or 'data', optional
sets the unit in which the width and height in crop are specified when using the (x,y,w,h) format, with 'pixels' to give the size in pixels or 'data' to specify the size in the physical unit used for the scalebar (after optional unit conversion via the convert parameter). Note that the position of the top left corner is given in pixels. The ((xmin,ymin),(xmax,ymax)) format must be always given in pixels, and crop_unit is ignored if crop is given in this format. The default is 'pixels'.
resolution : int, optional
the resolution along the x-axis (i.e. image width in pixels) to use for the exported image. The default is None, which uses the size of the original image (after optional cropping using crop).
cmap : str or callable or list of str or list of callable, optional

name of a named Matplotlib colormap used to color the data. see the Matplotlib documentation for more information. The default is 'inferno'.

In addition to the colormaps listed there, the following maps for linearly incrementing pure RGB channels are available, useful for e.g. displaying multichannel data with complementary colors (no overlap between between colormaps possible): ['pure_reds', 'pure_greens', 'pure_blues', 'pure_yellows', 'pure_cyans', 'pure_purples','pure_greys'] where for example 'pure_reds' scales between RGB values (0,0,0) and (255,0,0), and 'pure_cyans' between (0,0,0) and (0,255,255).

Alternatively, a fully custom colormap may be used by entering a ListedColormap or LinearSegmentedColormap object from the Matplotlib.colors module. For more information on creating colormaps, see the Matplotlib documentation linked above.

For multichannel data, a list of colormaps must be provided, with a separate colormap for each channel.

cmap_range : tuple of form (min,max) or None or 'automatic', optional
sets the scaling of the colormap. The minimum and maximum values to map the colormap to, values outside of this range will be colored according to the min and max value of the colormap. The default is None, which is to take the lowest and highest value in the image. Alternatively 'automatic' may be specified which scales between the 10th and 99th percentile. For multichannel data a list of cmap_range options per channel may be provided.
draw_bar : boolean, optional
whether to draw a scalebar on the image, such that this function may be used to put other text on the image or just to apply a colormap (by setting draw_bar=False and draw_text=False). The default is True.
barsize : float or None, optional
size (in data units matching the original scale bar, e.g. nm) of the scale bar to use. The default None, wich takes the desired length for the current scale (ca. 15% of the width of the image for scale=1) and round this to the nearest option from a list of "nice" values.
scale : float, optional
factor to change the size of the scalebar+text with respect to the width of the image. Scale is chosen such, that at scale=1 the font size of the scale bar text is approximately 10 pt when the image is printed at half the width of the text in a typical A4 paper document (e.g. two images side-by-side). Note that this is with respect to the output image, so after optional cropping and/or up/down sampling has been applied. The default is 1.
loc : int, one of [0,1,2,3], optional
Location of the scalebar on the image, where 0, 1, 2 and 3 refer to the top left, top right, bottom left and bottom right respectively. The default is 2, which is the bottom left corner.
convert : str, one of ['fm','pm','Å' or A,'nm','µm' or 'um','mm','cm','dm','m'], optional
Unit that will be used for the scale bar, the value will be automatically converted if this unit differs from the pixel size unit. The default is None, which uses micrometers.
barcolor : tuple of ints, optional
RGB color to use for the scalebar and text, given as a tuple of form (R,G,B) or (R,G,B,A) where R, G B and A are values between 0 and 255 for red, green, blue and alpha respectively. The default is (255,255,255), which gives a white scalebar.
barthickness : int, optional
thickness in printer points of the scale bar itself. The default is 16.
barpad : int, optional
size in printer points of the padding between the scale bar and the surrounding box. The default is 10.
draw_text : bool, optional
whether to draw the text specified in text on the image, the text is place above the scale bar if draw_bar=True. The default is True.
text : str, optional
the text to draw on the image (above the scale bar if draw_bar=True). The default is None, which gives the size and unit of the scale bar (e.g. '10 µm').
font : str, optional
filename of an installed TrueType font ('.ttf' file) to use for the text on the scalebar. The default is 'arialbd.ttf'.
fontsize : int, optional
base font size to use for the scale bar text. The default is 16. Note that this size will be re-scaled according to resolution and scale.
fontcolor : tuple of int, optional
(R,G,B) tuple where R, G and B are red, green and blue values from 0 to 255. The default is (255,255,255) giving white text.
fontbaseline : int, optional
vertical offset for the baseline of the scale bar text in from the top of the scale bar in printer points. The default is 10.
fontpad : int, optional
minimum size in printer points of the space/padding between the text and surrounding box. The default is 10.
draw_box : bool, optional
Whether to put a colored box behind the scalebar and text to enhance contrast on busy images. The default is False.
boxcolor : tuple of ints, optional
RGB color to use for the box behind/around the scalebar and text, given as a tuple of form (R,G,B) or (R,G,B,A) where R, G B and A are values between 0 and 255 for red, green and blue respectively. If no A is given, boxopacity is used. The default is (0,0,0) which gives a black box.
boxopacity : int, optional
value between 0 and 255 for the opacity/alpha of the box, useful for creating a semitransparent box. The default is 255.
boxpad : int, optional
size of the space/padding around the box (with respect to the sides of the image) in printer points. The default is 10.
save : bool, optional
whether to save the image as file. The default is True.
show_figure : bool, optional
whether to open matplotlib figure windows. The default is True.

Returns

Y×X×4 numpy.array containing the BGRA pixel data
 
def get_dimension_steps(self, dim, use_stack_indices=False)

return a list of physical values along a certain dimension, e.g. the x-coordinates or timesteps.

def get_image_metadata(self, indices=slice(None, None, None))

loads the part of the metadata containing information about the time, position etc. for each frame of the series and returns a dataframe indexes by image frame

Parameters

indices : slice object, optional
which image frames to load the metadata for. The default is all frames.

Returns

imagedata : pandas.DataFrame
the metadata for the images, indexed by frame number.
def get_metadata(self)

loads OME metadata from visitech .ome.tif file and returns xml tree object

Returns

xml.etree.ElementTree
formatted XML metadata. Can be indexed with xml_root.find('')
def get_metadata_dimensions(self)

finds the stack's dimensionality and logical shape based on the embedded metadata

Returns

shape : tuple of ints
logical sizes of the stack
dimorder : tuple of strings
order of the dimensions corresponding to the shape
def get_pixelsize(self)

shortcut to get (z,y,x) pixelsize with unit

def get_series_name(self)

Returns a name for the series based on the filename.

Returns

str
 
def load_data(self, indices=slice(None, None, None), dtype=numpy.uint16)

load images from datafile into 3D numpy array

Parameters

indices : slice object or list of ints, optional
which images from tiffstack to load. The default is slice(None,None,None).
dtype : np int datatype
data type / bit depth to rescale data to.

Returns

numpy.ndarray containing image data in dim order (im,y,x)
 
def load_stack(self, dim_range={}, dtype=numpy.uint16)

Load the data and reshape into 4D stack with the following dimension order: ('channel','time','z-axis','y-axis','x-axis') where dimensions with len 1 are omitted.

For loading only part of the total dataset, the dim_range parameter can be used to specify a range along any of the dimensions. This will be more memory efficient than loading the entire stack and then discarding part of the data. For slicing along the x or y axis this is not possible and whole (xy) images must be loaded prior to discarding data outside the specified x or y axis range.

Parameters

dim_range : dict, optional
dict, with keys corresponding to channel/dimension labels as above and slice objects as values. This allows you to only load part of the data along any of the dimensions, such as only loading two time steps or a particular z-range. An example use for only taking time steps up to 5 and z-slice 20 to 30 would be: dim_range={'time':slice(None,5), 'z-axis':slice(20,30)}. The default is {} which corresponds to the full file.
dtype : (numpy) datatype, optional
type to scale data to. The default is np.uint16.
remove_backsteps : bool
whether to discard the frames which were recorded on the backsteps downwards

Returns

data : numpy.ndarray
ndarray with the pixel values
def yield_stack(self, dim_range={}, dtype=numpy.uint16, remove_backsteps=True)

Lazy-load the data and reshape into 4D stack with the following dimension order: ('time','z-axis','y-axis','x-axis'). Returns a generator which yields a z-stack for each call, which is loaded upon calling it.

For loading only part of the total dataset, the dim_range parameter can be used to specify a range along any of the dimensions. This will be more memory efficient than loading the entire stack and then discarding part of the data. For slicing along the x or y axis this is not possible and whole (xy) images must be loaded prior to discarding data outside the specified x or y axis range. The shape of the stack can be accessed without loading data using the stack_shape attribute after creating the yield_stack object.

Parameters

dim_range : dict, optional

dict, with keys corresponding to channel/dimension labels as above and slice objects as values. This allows you to only load part of the data along any of the dimensions, such as only loading two time steps or a particular z-range. An example use for only taking time steps up to 5 and z-slice 20 to 30 would be:

dim_range={'time':slice(None,5), 'z-axis':slice(20,30)}.

The default is {} which corresponds to the full file.

dtype : (numpy) datatype, optional
type to scale data to. The default is np.uint16.
remove_backsteps : bool
whether to discard the frames which were recorded on the backsteps downwards

Returns

zstack : iterable/generator yielding numpy.ndarray
list of time steps, with for each time step a z-stack as np.ndarray with the pixel values