torch_staintools.functional.stain_extraction package

Submodules

torch_staintools.functional.stain_extraction.extractor module

class torch_staintools.functional.stain_extraction.extractor.BaseExtractor

Bases: ABC, Callable

Stain Extraction by stain matrix estimation.

Regulate how a stain matrix estimation function should look like

_abc_impl = <_abc._abc_data object>
get_partial(*, luminosity_threshold: float = 0.8, num_stains: int = 2, regularizer: float = 0.1, perc: int = 1, rng: Generator | None = None, **kwargs) Callable
abstract static get_stain_matrix_from_od(od: Tensor, tissue_mask: Tensor, num_stains: int, *args, **kwargs) Tensor

Abstract function to implement: how to estimate stain matrices from optical density vectors.

Parameters:
  • od – optical density image in batch (BxCxHxW)

  • tissue_mask – tissue mask so that only pixels in tissue regions will be evaluated

  • num_stains – number of stains.

  • *args – other positional arguments

  • **kwargs – other keyword arguments.

Returns:

B x num_stain x num_input_color_channel

Return type:

output batch of stain matrices

static normalize_matrix_rows(A: Tensor) Tensor

Normalize the rows of an array. :param A: An array to normalize

Returns:

Array with rows normalized.

torch_staintools.functional.stain_extraction.factory module

torch_staintools.functional.stain_extraction.factory.build_from_name(algo: str) BaseExtractor

A factory builder to create stain extractor from name.

Parameters:

algo – support ‘macenko’ and ‘vahadane’

Returns:

torch_staintools.functional.stain_extraction.macenko module

class torch_staintools.functional.stain_extraction.macenko.MacenkoExtractor

Bases: BaseExtractor

_abc_impl = <_abc._abc_data object>
static angular_helper(t_hat)
static cov(x)

Covariance matrix for eigen decomposition. https://en.wikipedia.org/wiki/Covariance_matrix

static get_stain_matrix_from_od(od: Tensor, tissue_mask: Tensor, *, perc: int = 1, num_stains: int = 2, **kwargs)
Parameters:
  • od – Image in the Optical Density space with shape of BxCxHxW

  • tissue_mask – tissue mask so that only pixels in tissue regions will be evaluated

  • perc – Percentile number to find the minimum angular term. min angular as perc percentile max angular as 100 - perc percentile.

  • num_stains – number of stains to separate. For now only support 2 as it might be complicated to separate angular terms in a 3D or higher dimensional space.

  • **kwargs – Not used. For compatibility.

Returns:

Stain Matrices in shape of B x num_stains x num_input_color_channel. For H&E stain estimation, if the original image is RGB before converted to OD, then the stain matrix is B x 2 x 3, with the first row, i.e., stain_mat[:, 0, :] as H, and the second row, i.e., stain_mat[:, 1, :] as E.

static stain_matrix_helper(t_hat: Tensor, perc: int, eig_vecs: Tensor)

Helper function to compute the stain matrix.

Separate the projected OD vectors on singular vectors (SVD of OD in Macenko paper, which is also the eigen vector of the covariance matrix of the OD)

Parameters:
  • t_hat – projection of OD on the plane of most significant singular vectors of OD.

  • perc – perc –> min angular term, 100 - perc –> max angular term

  • eig_vecs – eigen vectors of the cov(OD), which may also be the singular vectors of OD.

Returns:

sorted stain matrix in shape of B x num_stains x num_input_color_channel. For H&E cases, the first row in dimension of num_stains is H and the second is E (only num_stains=2 supported for now).

torch_staintools.functional.stain_extraction.utils module

torch_staintools.functional.stain_extraction.utils.percentile(t: Tensor, q: float, dim: int) Tensor

Author: adapted from https://gist.github.com/spezold/42a451682422beb42bc43ad0c0967a30

Return the q-th percentile of the flattenepip d input tensor’s data.

Caution

  • Needs PyTorch >= 1.1.0, as torch.kthvalue() is used.

  • Values are not interpolated, which corresponds to numpy.percentile(..., interpolation="nearest").

Parameters:
  • t – Input tensor.

  • q – Percentile to compute, which must be between 0 and 100 inclusive.

  • dim – which dim to operate for function tensor.kthvalue.

Returns:

Resulting value (scalar).

torch_staintools.functional.stain_extraction.vahadane module

class torch_staintools.functional.stain_extraction.vahadane.VahadaneExtractor

Bases: BaseExtractor

_abc_impl = <_abc._abc_data object>
static get_stain_matrix_from_od(od: Tensor, tissue_mask: Tensor, *, regularizer: float = 0.1, lambd=0.01, num_stains: int = 2, algorithm='ista', steps=30, constrained=True, persist=True, init='ridge', verbose: bool = False, rng: Generator | None = None) Tensor

Stain matrix estimation via method of: A. Vahadane et al. ‘Structure-Preserving Color Normalization and Sparse Stain Separation for Histological Images’

Parameters:
  • od – optical density image in batch (BxCxHxW)

  • tissue_mask – tissue mask so that only pixels in tissue regions will be evaluated

  • regularizer – regularization term in ista for dictionary learning

  • lambd – lambda term for the sparse penalty in objective of dictionary learning

  • num_stains – # of stains to separate

  • algorithm – which algorithm to use, iterative-shrinkage soft thresholding algorithm ista or coordinate descent cd.

  • steps – max number of steps if still not converged

  • constrained – whether to force dictionary to be positive

  • persist – whether retain the previous z value for its update or initialize every time in the iteration.

  • init – init method of the codes a in X = D x a. Selected from ridge, zero, unif (uniformly random), or transpose. Details see torch_staintools.functional.optimization.sparse_util.initialize_code

  • verbose – whether to print progress messages.

  • rng – torch.Generator for any random initializations incurred (e.g., if init is set to be unif)

Returns:

List of HE matrix (B*2x3 - H on the 1st row in the 2nd dimension)

Module contents