nima.nima#

Main library module.

Contains functions for the analysis of multichannel timelapse images. It can be used to apply dark, flat correction; segment cells from bg; label cells; obtain statistics for each label; compute ratio and ratio images between channels.

Functions:

read_tiff(fp, channels)

Read multichannel TIFF timelapse image.

d_show(d_im, **kws)

Imshow for dictionary of image (d_im).

d_median(d_im)

Median filter on dictionary of image (d_im).

d_shading(d_im, dark, flat, *[, clip])

Shading correction on d_im.

d_bg(d_im, bg_params[, downscale, clip])

Bg segmentation for d_im.

d_mask_label(d_im[, min_size, channels, ...])

Label cells in d_im.

process_watershed(d_im, channels, *[, ...])

Apply watershed segmentation algorithm to a given image.

d_ratio(d_im[, name, channels, radii])

Ratio image between 2 channels in d_im.

d_meas_props(d_im[, channels, channels_cl, ...])

Calculate pH and cl ratios and labelprops.

d_plot_meas(bgs, meas, channels)

Plot meas object.

plt_img_profile(img[, title, hpix, vmin, vmax])

Summary graphics for Flat-Bias images.

plt_img_profile_2(img[, title])

Summary graphics for Flat-Bias images.

hotpixels(bias[, n_sd])

Identify hot pixels in a bias-dark frame.

correct_hotpixel(img, y, x)

Correct hot pixels in a frame.

read_tiffmd(fp, channels)

Read multichannel TIFF timelapse image.

Classes:

Channel(wavelength, attenuation, gain, ...)

Represent illumination-detection channel.

StagePosition(x, y, z)

Dataclass representing stage position.

VoxelSize(x, y, z)

Dataclass representing voxel size.

Metadata(rdr[, size_s, size_x, size_y, ...])

Dataclass representing core metadata.

Exceptions:

MultiplePositionsError(message)

Exception raised when a series contains multiple stage positions.

nima.nima.read_tiff(fp, channels)#

Read multichannel TIFF timelapse image.

Parameters:
  • fp (Path) – File (TIF format) to be opened.

  • channels (Sequence[str]) – List a name for each channel.

Return type:

tuple[dict[str, ndarray[tuple[Any, ...], dtype[float32]] | ndarray[tuple[Any, ...], dtype[int32]] | ndarray[tuple[Any, ...], dtype[uint16]] | ndarray[tuple[Any, ...], dtype[uint8]]], int, int]

Returns:

  • d_im (DIm) – Dictionary of images. Each keyword represents a channel, named according to channels string list.

  • n_channels (int) – Number of channels.

  • n_times (int) – Number of timepoints.

Raises:

ValueError – When number of channels and total length of TIFF sequence does not match.

Examples

>>> d_im, n_channels, n_times = read_tiff('tests/data/1b_c16_15.tif',             channels=['G', 'R', 'C'])
>>> n_channels, n_times
(3, 4)
nima.nima.d_show(d_im, **kws)#

Imshow for dictionary of image (d_im). Support plt.imshow kws.

Return type:

Figure

nima.nima.d_median(d_im)#

Median filter on dictionary of image (d_im).

Same to skimage.morphology.disk(1) and to median filter of Fiji/ImageJ with radius=0.5.

Parameters:

d_im (DIm) – dict of images

Returns:

dict of images preserve dtype of input

Return type:

DIm

Raises:

ValueError – When ImArray is neither a single image nor a stack.

nima.nima.d_shading(d_im, dark, flat, *, clip=True)#

Shading correction on d_im.

Subtract dark; then divide by flat.

Works either with flat or d_flat Need also dark for each channel because it can be different when using different acquisition times.

Parameters:
  • d_im (DIm) – Dictionary of images.

  • dark (DIm | ImFrame) – Dark image (either a 2D image or 2D d_im).

  • flat (DIm | ImFrame) – Flat image (either a 2D image or 2D d_im).

  • clip (bool) – Boolean for clipping values >=0.

Returns:

Corrected d_im.

Return type:

DIm

nima.nima.d_bg(d_im, bg_params, downscale=None, *, clip=True)#

Bg segmentation for d_im.

Parameters:
  • d_im (DIm) – desc

  • bg_params (BgParams) – An instance of BgParams containing the parameters for the segmentation.

  • downscale (tuple[int, int] | None) – Tupla, x, y are downscale factors for rows, cols (default=None).

  • clip (bool, optional) – Boolean (default=True) for clipping values >=0.

Return type:

tuple[dict[str, ndarray[tuple[Any, ...], dtype[float32]] | ndarray[tuple[Any, ...], dtype[int32]] | ndarray[tuple[Any, ...], dtype[uint16]] | ndarray[tuple[Any, ...], dtype[uint8]]], DataFrame, dict[str, list[list[Figure]]]]

Returns:

  • d_cor (DIm) – Dictionary of images subtracted for the estimated bg.

  • bgs (pd.DataFrame) – Median of the estimated bg; columns for channels and index for time points.

  • figs (dict[str, list[list[Figure]]]) – List of (list ?) of figures.

nima.nima.d_mask_label(d_im, min_size=640, channels=('C', 'G', 'R'), threshold_method='yen', *, wiener=False, watershed=False, clear_border=False, randomwalk=False)#

Label cells in d_im. Add two keys, mask and label.

Perform plane-by-plane (2D image): :rtype: None

  • geometric average of all channels;

  • optional wiener filter (3,3);

  • mask using threshold_method;

  • remove objects smaller than min_size;

  • binary closing;

  • optionally remove any object on borders;

  • label each ROI;

  • optionally perform watershed on labels.

Parameters:
  • d_im (DIm) – desc

  • min_size (int | None, optional) – Objects smaller than min_size (default=640 pixels) are discarded from mask.

  • channels (tuple[str, …], optional) – List a name for each channel.

  • threshold_method (str, optional) – Threshold method applied to the geometric average plane-by-plane (default=yen).

  • wiener (bool, optional) – Boolean for wiener filter (default=False).

  • watershed (bool, optional) – Boolean for watershed on labels (default=False).

  • clear_border (bool, optional) – Whether to filter out objects near the 2D image edge (default=False).

  • randomwalk (bool, optional) – Use random_walker instead of watershed post-ndimage-EDT (default=False).

Raises:

ValueError – If threshold_method is not one of [‘yen’, ‘li’].

Notes

Side effects:

Add a ‘label’ key to the d_im.

nima.nima.process_watershed(d_im, channels, *, randomwalk=False)#

Apply watershed segmentation algorithm to a given image.

This function takes a pre-processed image d_im, a sequence of channels channels to be used for the segmentation, a structuring element ga_wiener, a mask mask, a time step time, and an optional randomwalk function or string to specify the random walker method. If labels is not provided, it is initialized as an empty numpy array.

Return type:

None

nima.nima.d_ratio(d_im, name='r_cl', channels=('C', 'R'), radii=(7, 3))#

Ratio image between 2 channels in d_im.

Add masked (bg=0; fg=ratio) median-filtered ratio for 2 channels. So, d_im must (already) contain keys for mask and the two channels.

After ratio computation any -inf, nan and inf values are replaced with 0. These values should be generated (upon ratio) only in the bg. You can check: r_cl[d_im[‘labels’]==4].min()

Parameters:
  • d_im (DIm) – desc

  • name (str, optional) – Name (default=’r_cl’) for the new key.

  • channels (tuple[str, str], optional) – Names for the two channels (Numerator, Denominator) (default=(‘C’, ‘R’)).

  • radii (tuple[int, int], optional) – Each element contain a radius value for a median filter cycle (default=(7, 3)).

Return type:

None

Notes

Add a key named “name” and containing the calculated ratio to d_im.

nima.nima.d_meas_props(d_im, channels=('C', 'G', 'R'), channels_cl=('C', 'R'), channels_ph=('G', 'C'), radii=None, *, ratios_from_image=True)#

Calculate pH and cl ratios and labelprops.

Parameters:
  • d_im (DIm) – desc

  • channels (Sequence[str], optional) – All d_im channels (default=(‘C’, ‘G’, ‘R’)).

  • channels_cl (tuple[str, str], optional) – Numerator and denominator channels for cl ratio (default=(‘C’, ‘R’)).

  • channels_ph (tuple[str, str], optional) – Numerator and denominator channels for pH ratio (default=(‘G’, ‘C’)).

  • radii (tuple[int, int] | None, optional) – Radii of the optional median average performed on ratio images (default=None).

  • ratios_from_image (bool, optional) – Boolean for executing d_ratio i.e. compute ratio images (default=True).

Return type:

tuple[dict[int, DataFrame], dict[str, list[list[Any]]]]

Returns:

  • meas (dict[int, pd.DataFrame]) – For each label in labels: {‘label’: df}. DataFrame columns are: mean intensity of all channels, ‘equivalent_diameter’, ‘eccentricity’, ‘area’, ratios from the mean intensities and optionally ratios from ratio-image.

  • pr (dict[str, list[list[Any]]]) – For each channel: {‘channel’: [props]} i.e. {‘channel’: [time][label]}.

nima.nima.d_plot_meas(bgs, meas, channels)#

Plot meas object.

Plot r_pH, r_cl, mean intensity for each channel and estimated bg over timepoints for each label (color coded).

Parameters:
  • bgs (pd.DataFrame) – Estimated bg returned from d_bg()

  • meas (dict[int, pd.DataFrame]) – meas object returned from d_meas_props().

  • channels (Sequence[str]) – All bgs and meas channels (default=[‘C’, ‘G’, ‘R’]).

Returns:

Figure.

Return type:

Figure

nima.nima.plt_img_profile(img, title=None, hpix=None, vmin=None, vmax=None)#

Summary graphics for Flat-Bias images.

Parameters:
  • img (ImFrame) – Image of Flat or Bias.

  • title (str | None, optional) – Title of the figure (default=None).

  • hpix (pd.DataFrame | None, optional) – Identified hot pixels (as empty or not empty df) (default=None).

  • vmin (float | None, optional) – Minimum value (default=None).

  • vmax (float | None, optional) – Maximum value (default=None).

Returns:

Profile plot.

Return type:

Figure

nima.nima.plt_img_profile_2(img, title=None)#

Summary graphics for Flat-Bias images.

Parameters:
  • img (ImFrame) – Image of Flat or Bias.

  • title (str | None, optional) – Title of the figure (default=None).

Returns:

Profile plot.

Return type:

Figure

nima.nima.hotpixels(bias, n_sd=20)#

Identify hot pixels in a bias-dark frame.

After identification of first outliers recompute masked average and std until convergence.

Parameters:
  • bias (ImFrame) – Usually the median over a stack of 100 frames.

  • n_sd (int) – Number of SD above mean (masked out of hot pixels) value.

Returns:

y, x positions and values of hot pixels.

Return type:

pd.DataFrame

nima.nima.correct_hotpixel(img, y, x)#

Correct hot pixels in a frame.

Substitute indicated position y, x with the median value of the 4 neighbor pixels.

Parameters:
  • img (ImFrame) – Frame (2D) image.

  • y (int | NDArray[np.int_]) – y-coordinate(s).

  • x (int | NDArray[np.int_]) – x-coordinate(s).

Return type:

None

class nima.nima.Channel(wavelength, attenuation, gain, binning, filters)#

Represent illumination-detection channel.

Variables:
  • wavelength (int) – Illumination wavelength.

  • attenuation (float) – Illumination attenuation.

  • gain (float) – Detector gain.

  • binning (str) – Detector binning.

  • filters (list[str]) – List of filters.

Attributes:

Methods:

__repr__()

Represent most relevant metadata.

wavelength: int#
attenuation: float#
gain: float#
binning: str#
filters: list[str]#
__repr__()#

Represent most relevant metadata.

Return type:

str

class nima.nima.StagePosition(x, y, z)#

Dataclass representing stage position.

Variables:
  • x (float | None) – Position in the X dimension.

  • y (float | None) – Position in the Y dimension.

  • z (float | None) – Position in the Z dimension.

Attributes:

x

y

z

Methods:

__hash__()

Generate a hash value for the object based on its attributes.

__repr__()

Represent most relevant metadata.

x: float | None#
y: float | None#
z: float | None#
__hash__()#

Generate a hash value for the object based on its attributes.

Return type:

int

__repr__()#

Represent most relevant metadata.

Return type:

str

class nima.nima.VoxelSize(x, y, z)#

Dataclass representing voxel size.

Variables:
  • x (float | None) – Size in the X dimension.

  • y (float | None) – Size in the Y dimension.

  • z (float | None) – Size in the Z dimension.

Attributes:

x

y

z

Methods:

__hash__()

Generate a hash value for the object based on its attributes.

x: float | None#
y: float | None#
z: float | None#
__hash__()#

Generate a hash value for the object based on its attributes.

Return type:

int

exception nima.nima.MultiplePositionsError(message)#

Exception raised when a series contains multiple stage positions.

class nima.nima.Metadata(rdr, size_s=1, size_x=<factory>, size_y=<factory>, size_z=<factory>, size_c=<factory>, size_t=<factory>, dimension_order=<factory>, bits=<factory>, objective=<factory>, name=<factory>, date=<factory>, stage_position=<factory>, voxel_size=<factory>, channels=<factory>, tcz_deltat=<factory>)#

Dataclass representing core metadata.

Variables:
  • rdr (InitVar[TiffReader]) – TiffReader parameter to initialize class.

  • size_s (int) – Number of series (size in the S dimension).

  • size_x (list[int]) – List of sizes in the X dimension.

  • size_y (list[int]) – List of sizes in the Y dimension.

  • size_z (list[int]) – List of sizes in the Z dimension.

  • size_c (list[int]) – List of sizes in the C dimension.

  • size_t (list[int]) – List of sizes in the T dimension.

  • dimension_order (list[str]) – List of dimension order for each pixels.

  • bits (list[int]) – List of bits per pixel.

  • objective (list[str]) – List of objectives.

  • name (list[str]) – List of series names.

  • date (list[str]) – List of acquisition dates.

  • stage_position (list[dict[StagePosition, tuple[int, int, int]]]) – List of {StagePosition: (T,C,Z)} for each S.

  • voxel_size (list[VoxelSize]) – List of voxel sizes.

  • channels (list[list[Channel]]) – Channels settings.

  • tcz_deltat (list[list[tuple[int, int, int, float]]]) – Delta time for each T C Z.

Attributes:

Methods:

__repr__()

Represent most relevant metadata.

__post_init__(rdr)

Consolidate all core metadata.

rdr: InitVar#
size_s: int = 1#
size_x: list[int]#
size_y: list[int]#
size_z: list[int]#
size_c: list[int]#
size_t: list[int]#
dimension_order: list[str]#
bits: list[int]#
objective: list[str]#
name: list[str]#
date: list[str]#
stage_position: list[dict[StagePosition, tuple[int, int, int]]]#
voxel_size: list[VoxelSize]#
channels: list[list[Channel]]#
tcz_deltat: list[list[tuple[int, int, int, float]]]#
__repr__()#

Represent most relevant metadata.

Return type:

str

__post_init__(rdr)#

Consolidate all core metadata.

Return type:

None

nima.nima.read_tiffmd(fp, channels)#

Read multichannel TIFF timelapse image.

Return type:

tuple[Array, Metadata]