par_segmentation package

Module contents

class par_segmentation.ImageQuant(img: Union[ndarray, list], roi: Union[ndarray, list], sigma: float = 3.5, periodic: bool = True, thickness: int = 50, rol_ave: int = 5, rotate: bool = False, nfits: Optional[int] = 100, iterations: int = 2, lr: float = 0.01, descent_steps: int = 400, adaptive_sigma: bool = False, batch_norm: bool = False, freedom: float = 25, roi_knots: int = 20, fit_outer: bool = True, save_training: bool = False, save_sims: bool = False, method: str = 'GD', itp: int = 10, parallel: bool = False, zerocap: bool = False, cores: Optional[float] = None, bg_subtract: bool = False, interp: str = 'cubic', verbose: bool = True)

Bases: object

Main class to perform image segmentation

Instructions:

  1. (Optional) Perform SAIBR on image

  2. Specify rough manual ROI

  3. Initialise class

  4. run()

  5. New ROI coordinates will be found at self.roi

  6. Save quantification results using compile_res() - returns a pandas dataframe

Parameters
  • img – numpy array of image or list of numpy arrays

  • roi – coordinates defining the cortex (two column numpy array of x and y coordinates at 1-pixel width intervals), or a list of arrays

  • roi_knots – number of knots in cubic-spline fit ROI

  • freedom – amount by which the roi can move (pixel units)

  • sigma – gaussian/error function width (pixels units)

  • periodic – True if coordinates form a closed loop

  • thickness – thickness of cross section over which to perform quantification (pixel units)

  • rol_ave – width of rolling average to apply to images prior to fitting (pixel units)

  • rotate – if True, will automatically rotate ROI so that the first/last points are at the end of the long axis

  • nfits – performs this many fits at regular intervals around ROI. If none, will fit at pixel-width intervals

  • iterations – if >1, adjusts ROI and re-fits

  • batch_norm – if True, images will be globally, rather than internally, normalised. Shouldn’t affect quantification but is recommended during model optimisation

  • fit_outer – if True, will fit the outer portion of each profile to a nonzero value

  • method – ‘GD’ for gradient descent or ‘DE’ for differential evolution. The former is highly recommended, the latter works but is much slower and no longer maintained

  • zerocap – if True, limits output concentrations to positive (or very weakly negative) values

  • interp – interpolation type, ‘cubic’ or ‘linear’

  • lr – learning rate

  • descent_steps – number of gradient descent steps

  • adaptive_sigma – if True, sigma will be trained by gradient descent

  • verbose – False suppresses onscreen output while model is running (e.g. progress bar)

  • parallel – LEGACY (for DE method). If True will run in parallel on number of cores specified. NB Very buggy

  • cores – LEGACY (for DE method). Number of cores to use if parallel is True

  • itp – LEGACY (for DE method). Amount of interpolation - allows for subpixel alignment

compile_res()

Compile results to a pandas dataframe

Returns

A pandas dataframe containing quantification results

plot_fits()

Opens an interactive widget to plot actual vs fit profiles

plot_losses(log: bool = False)

Plot loss curves (one line for each image)

Parameters

log – if True, plot the logarithm of losses

plot_quantification()

Opens an interactive widget to plot membrane quantification results

plot_segmentation()

Opens an interactive widget to plot segmentation results

run()

Performs segmentation/quantification and saves results

save(save_path: str, i: Optional[int] = None)

Save results for a single image to save_path as a series of txt files and tifs I’d recommend using compile_res() instead as this will create a single pandas dataframe with all the results

Parameters
  • save_path – path to save full results

  • i – index of the image to save (if quantifying multiple images in batch)

view_frames()

Opens an interactive widget to view image(s)

par_segmentation.asi(mems: ndarray, size: float) float

Calculates asymmetry index based on membrane concentration profile

Parameters
  • mems – numpy array of membrane concentration values. Periodic array starting from extreme posterior

  • size – size of region to average over when calculating anterior and posterior concentrations (from 0 to 1, where 1 indicates the whole embryo)

Returns

asymmetry index

par_segmentation.bg_subtraction(img: ndarray, roi: ndarray, band: tuple = (25, 75)) ndarray

Subtracts background intensity from an image of a cell. Background intensity calculated as the mean intensity within a band surronding the cell (specified by ROI)

Parameters
  • img – numpy array of image to subtract background from

  • roi – two column numpy array specifying coordinates of the cell boundary

  • band – inner and outer distance of the band from the roi

Returns

numpy array of image with background subtracted

par_segmentation.bounded_mean_1d(array: ndarray, bounds: tuple, weights: Optional[ndarray] = None) float

Averages 1D array over region specified by bounds Array and weights should be same length Todo: Should add interpolation step first? Todo: combine with 2d function

Parameters
  • array – one dimensional numpy array

  • bounds – specifies window to average over. (min, max) from 0 to 1 specifying start and end of the array

  • weights – if weights are specified a weighted average will be performed

Returns

single number corresponding to mean value over the bounds specified

par_segmentation.bounded_mean_2d(array: ndarray, bounds: tuple) ndarray

Averages 2D array in y dimension over region specified by bounds Todo: Should add axis parameter Todo: Should add interpolation step first

Parameters
  • array – two dimensional numpy array

  • bounds – specifies window to average over. (min, max) from 0 to 1 specifying start and end of the array

Returns

one dimensional numpy array of length array.shape[0], corresponding to mean value over the bounds specified

par_segmentation.direcslist(dest: str, levels: int = 0, exclude: Optional[tuple] = ('!',), exclusive: Optional[tuple] = None) list

Gives a list of directories within a given directory (full path) Todo: os.walk

Parameters
  • dest – path of parent directory

  • levels – number of levels to go down. E.g. if 0, only return folders within the parent folder; if 1, return

  • folder (folders within folders within the parent) –

  • exclude – exclude directories containing any strings within this tuple

  • exclusive – exclude directories that don’t contain all the strings within this tuple

Returns

list of directories

par_segmentation.dosage(img: ndarray, roi: ndarray, expand: float) ndarray

One way of calculating protein dosage from an image

Parameters
  • img – image 2D numpy array

  • roi – roi representing cell edge (two-column numpy array)

  • expand – expand the ROI by this many pixels before calculating the dosage

Returns

dosage

par_segmentation.error_func(x: ndarray, centre: float, width: float) ndarray

Create error function with centre and width specified

Parameters
  • x – array of input x values

  • centre – centre of the error function curve (in x units)

  • width – width of the error function curve (in x units)

Returns

error function curve

par_segmentation.gaus(x: ndarray, centre: float, width: float) ndarray

Create Gaussian curve with centre and width specified

Parameters
  • x – array of input x values

  • centre – centre of the Gaussian curve (in x units)

  • width – width of the gaussian curve (in x units)

Returns

Gaussian curve

par_segmentation.in_notebook()

Tests whether python is being run within a notebook

https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook

par_segmentation.interp_1d_array(array: ndarray, n: int, method: str = 'cubic') ndarray

Interpolates a one dimensional array into n points

Parameters
  • array – one dimensional numpy array

  • n – number of points to evaluate. Will evaluate this many points at evenly space intervals along the length of

  • array

  • method – ‘linear’ or ‘cubic’

Returns

interpolated array (one dimensional array of length n)

par_segmentation.interp_2d_array(array: ndarray, n: int, ax: int = 0, method: str = 'cubic') ndarray

Interpolates a two dimensional array along one axis into n points

Parameters
  • array – two dimensional numpy array

  • n – number of points to evaluate along the specified axis

  • ax – 0 or 1, specifies the axis to interpolate along. 0 corresponds to the rows and 1 corresponds to the columns.

  • method – ‘linear’ or ‘cubic’

Returns

Interpolated array. 2D array of shape [array.shape[0], n] if ax==1, or [n, array.shape[1] if ax==0

par_segmentation.interp_roi(roi: ndarray, periodic: bool = True, npoints: Optional[int] = None, gap: int = 1) ndarray

Interpolates coordinates to one pixel distances (or as close as possible to one pixel). Linear interpolation

Parameters
  • roi – two column array containing x and y coordinates. e.g. roi = np.loadtxt(filename)

  • periodic – set to True if the ROI is periodic

  • npoints – number of points to interpolate to

  • gap – alternatively, specify the desired gap between succesive coordinates in pixel units

Returns

interpolated ROI (numpy array)

par_segmentation.load_image(filename: str) ndarray

Given the filename of a TIFF, creates numpy array with pixel intensities

Parameters

filename – full path to the file to import (including extension)

Returns

A numpy array of the image

par_segmentation.make_mask(shape: tuple, roi: ndarray) ndarray

Create a mask for an image based on an ROI

Parameters
  • shape – shape of the binary mask

  • roi – roi of the mask region

Returns

binary mask

par_segmentation.norm_roi(roi: ndarray)

Aligns coordinates to their long axis

Parameters

roi – two column numpy array of coordinates to normalise

Returns

numpy array of same shape as roi with normalised coordinates

par_segmentation.offset_coordinates(roi: ndarray, offsets: Union[ndarray, float], periodic: bool = True) ndarray

Reads in coordinates, adjusts according to offsets

Parameters
  • roi – two column array containing x and y coordinates. e.g. roi = np.loadtxt(filename)

  • offsets – array the same length as coors. Direction?

  • periodic – set to True if the ROI is periodic

Returns

array in same format as coors containing new coordinates.

To save this in a fiji readable format: np.savetxt(filename, newcoors, fmt=’%.4f’, delimiter=’ ‘)

par_segmentation.organise_by_nd(path: str)

Organises images in a folder using the nd files

Parameters

path – path to folder containing nd files

par_segmentation.polycrop(img: ndarray, polyline: ndarray, enlarge: float) ndarray

Crops image according to polyline coordinates by setting values not contained within the coordinates to zero

Parameters
  • img – numpy array of image

  • polyline – roi specifying the bounding region (two columns specifying x and y coordinates)

  • enlarge – amount by which to expand or contract the ROI (pixel units)

Returns

numpy array of same shape img, with regions outside of polyline set to zero

par_segmentation.readnd(path: str) dict

Read an nd file

Parameters

path – directory to embryo folder containing nd file

Returns

dictionary containing data from nd file

par_segmentation.rolling_ave_1d(array: ndarray, window: int, periodic: bool = True) ndarray

Performs a rolling window average along a one dimensional array

Parameters
  • array – one dimensional array

  • window – rolling average window size. The function will compute the average of window consecutive elements at a time.

  • periodic – specifies if array is periodic. If true, averaging rolls over at ends. If false, the function will not average over the elements at the ends of the array.

Returns

numpy array same size as input array, containing the rolling average of the input array.

par_segmentation.rolling_ave_2d(array: ndarray, window: int, periodic: bool = True) ndarray

Returns rolling average across the x axis of a 2D array

Parameters
  • array – two dimensional array

  • window – rolling average window size

  • periodic – specifies if array is periodic. If true, averaging rolls over at ends

Returns

numpy array same size as input array

par_segmentation.rotate_roi(roi: ndarray) ndarray

Rotates coordinate array so that most posterior point is at the beginning

Parameters

roi – two column numpy array of coordinates to rotate

Returns

numpy array of same shape as roi with rotated coordinates

par_segmentation.rotated_embryo(img: ndarray, roi: ndarray, l: int, h: int, order: int = 1, return_roi: bool = False) Union[ndarray, Tuple[array, array]]

Takes an image and rotates according to coordinates so that anterior is on left, posterior on right Todo: some of the returned coordinates are anticlockwise

Parameters
  • img – numpy array of image to rotate

  • roi – roi of cell boundary (two columns specifying x and y coordinates)

  • l – length of output image (pixel units)

  • h – height of output image (pixel units)

  • order – interpolation order. 1 or 3 for linear or cubic interpolation

  • return_roi – if True, will return roi corresponding to the cell edge in the new image

Returns

numpy array of rotated image with dimensions [h, l] if return_roi is True, will also return roi corresponding to the cell edge in the new image

par_segmentation.save_img(img: ndarray, direc: str)

Saves 2D array as .tif file

Parameters
  • img – numpy array of the image to save

  • direc – file path to save to (including ‘.tif’ extension)

par_segmentation.save_img_jpeg(img: ndarray, direc: str, cmin: Optional[float] = None, cmax: Optional[float] = None, cmap: str = 'gray')

Saves 2D array as jpeg, according to min and max pixel intensities

Parameters
  • img – numpy array of the image to save

  • direc – file path to save to (including ‘.jpeg’ extension)

  • cmin – optional, sets intensity scaling (along with cmax)

  • cmax – optional, sets intensity scaling (along with cmin)

  • cmap – colour map (use string corresponding to matplotlib colormap)

par_segmentation.spline_roi(roi: ndarray, periodic: bool = True, s: float = 0.0, k: int = 3) ndarray

Fits a spline to points specifying the coordinates of the cortex, then interpolates to pixel distances

Parameters
  • roi – two column array containing x and y coordinates. e.g. roi = np.loadtxt(filename)

  • periodic – set to True if the ROI is periodic

  • s – splprep s parameter

  • k – splprep k parameter (spline order)

Returns

spline ROI (numpy array)

par_segmentation.straighten(img: ndarray, roi: ndarray, thickness: int, periodic: bool = True, interp: str = 'cubic', ninterp: Optional[int] = None) ndarray

Creates straightened image based on coordinates Todo: Doesn’t work properly for non-periodic rois

Parameters
  • img – numpy array of image to straighten

  • roi – coordinates of roi (two column array with x and y coordinates), should be 1 pixel length apart in a loop

  • thickness – thickness (pixel units) of the region surrounding the ROI to straighten

  • periodic – set to True is the ROI is periodic (a full loop)

  • interp – interpolation type, ‘cubic’ or ‘linear

  • ninterp – optional. If specified, interpolation along the y axis of the straight image will be at this many

  • specified (evenly spaced points. If not) –

  • distances. (interpolation will be performed at pixel-width) –

Returns

Straightened image as 2D numpy array. Will have dimensions [thickness, roi.shape[0]] unless ninterp is specified, in which case [ninterp, roi.shape[0]]