Skip to content

pyHisto.stain

Stain vectors, QuPath-compatible estimation, region sampling and calibration. Importing it loads NumPy only (no histomicstk, no QuPath).

Everything below is importable directly from pyHisto.stain (for example histo.stain.calibrate, histo.stain.RegionSet), except variance_summary, spherical_median and eigen_ratio, which live in pyHisto.stain.calibrate. The headings show the defining module.

Stain vectors

Named, unit-normalised RGB optical-density stain vectors.

StainMatrix

StainMatrix(names, vectors)

Three named stain vectors (rows), each unit-normalised.

Given two stains, a third "Residual" = normalise(cross(s1, s2)) is appended (QuPath convention, no sign fix). Given three, the third is kept as is (including a hand-edited sign).

RESIDUAL_NAME class-attribute instance-attribute

RESIDUAL_NAME = 'Residual'

names property

names

vectors property

vectors: ndarray

(3, 3) array, one unit stain vector per row.

residual

residual() -> np.ndarray

normalise(cross(stain1, stain2)) -- QuPath convention, no sign fix.

as_matrix

as_matrix() -> np.ndarray

(3, 3) matrix with the stain vectors as COLUMNS (for deconvolution).

to_dict

to_dict() -> dict

to_json

to_json(indent=4) -> str

{"PSR":[r,g,b],"FG":[r,g,b],"Residual":[r,g,b]} (key order kept).

from_dict classmethod

from_dict(d: dict) -> 'StainMatrix'

from_json classmethod

from_json(src) -> 'StainMatrix'

Load from a JSON string or a path to a JSON file.

angle_deg

angle_deg(u, v) -> float

Angle between two vectors in degrees (no sign folding, 0..180).

Estimation

estimate() and the stain-estimation backend registry.

estimate

estimate(rgb_pixels, *, method='numpy', background=None, reference=None, smooth=False, min_stain=0.05, max_stain=1.0, ignore_percentage=1.0, **params) -> StainMatrix

Estimate two stain vectors (+ residual) with QuPath's algorithm.

Parameters:

Name Type Description Default
rgb_pixels uint8 array, (H, W, 3) image or (N, 3) pixel list (true RGB).
required
method backend name, see :func:`available_methods`.
'numpy'
background (R, G, B) white level; ``None`` = per-channel mode of the

(possibly smoothed) pixels, ties -> higher value (QuPath GUI).

None
reference StainMatrix whose first two stains name and order the result

(QuPath's swap rule); None -> "Stain 1"/"Stain 2".

None
smooth apply QuPath GUI's 2x 3x3 mean filter first (image input only).
False
min_stain QuPath "Auto" defaults.
0.05
max_stain QuPath "Auto" defaults.
0.05
ignore_percentage QuPath "Auto" defaults.
0.05

available_methods

available_methods() -> list[str]

Names of the backends usable right now (QuPath probed on every call).

register_backend

register_backend(name: str, load: Callable[[], Callable], available: Callable[[], bool] = lambda: True) -> None

Register (or replace) a backend: load() returns the estimator.

Regions

Sampling regions for stain calibration: Region, RegionSet, propose_regions.

propose_regions places fixed-size, non-overlapping boxes inside tissue, stratified over the tissue area of every slide, deterministically per seed.

Memory is bounded: the tissue mask is computed on a coarse pyramid level read in row strips (and stride-subsampled to at most _COARSE_MAX_PX on the long side); only the candidate boxes themselves are read at the sampling level, for an exact no-data / tissue-fraction check. A full-resolution level is never materialised (unless it is the coarse level, i.e. the slide is tiny).

Region dataclass

Region(slide_id: str, level: int, x: int, y: int, w: int, h: int, source: str = 'auto', enabled: bool = True)

A box (x, y, w, h) in pixel coordinates of pyramid level of a slide.

slide_id instance-attribute

slide_id: str

level instance-attribute

level: int

x instance-attribute

x: int

y instance-attribute

y: int

w instance-attribute

w: int

h instance-attribute

h: int

source class-attribute instance-attribute

source: str = 'auto'

enabled class-attribute instance-attribute

enabled: bool = True

to_dict

to_dict() -> dict

from_dict classmethod

from_dict(d: Mapping) -> 'Region'

RegionSet

RegionSet(regions: Iterable[Region] = ())

Ordered list of :class:Region with a JSON round-trip (the review-app file).

FORMAT_VERSION class-attribute instance-attribute

FORMAT_VERSION = 1

enabled

enabled() -> list

The enabled regions, in order.

to_list

to_list() -> list

to_json

to_json(indent=2) -> str

from_json classmethod

from_json(src) -> 'RegionSet'

Load from a JSON string or a path (str / PathLike) to a JSON file.

propose_regions

propose_regions(slides, *, n_per_slide: int = 10, size_px: int = 512, level: int = 0, seed: int = 0, min_tissue_frac: float = 0.8, tissue_level: int | None = None, max_tries_per_box: int = 20, strategy: str = 'random', reference=None, background=None, min_glass_px: int = MIN_GLASS_PX) -> RegionSet

Non-overlapping size_px boxes inside tissue on every slide.

Parameters:

Name Type Description Default
slides ``{slide_id: Slide}``, an iterable of Slides or one Slide.
required
n_per_slide boxes wanted per slide; fewer (with a ``UserWarning``) when

the tissue cannot hold that many non-overlapping qualifying boxes.

10
size_px box side in pixels of ``level``.
512
level pyramid level the box coordinates refer to.
0
seed RNG seed (``"random"``); each slide gets its own stream derived from

(seed, slide_id), so a slide's boxes do not depend on the other slides. "stain" is deterministic and does not use it.

0
min_tissue_frac minimum tissue fraction of a box (checked exactly at ``level``).
0.8
tissue_level level for the coarse tissue / stain maps (default: coarsest

level on which a box still spans >= 8 pixels).

None
strategy ``"random"`` (stratified random, the default) or ``"stain"``

(stain-guided, needs reference).

'random'
reference StainMatrix whose first two stains define the amount maps (``"stain"``).
None
background glass colour (R, G, B) for all slides, or ``{slide_id: (R, G, B)}``;

None -> "random": glass colour of the coarse tissue image (:func:background_rgb); "stain": :func:slide_background with min_glass_px.

None
Notes

A box never contains a no-data pixel (all channels 0). Tissue = any channel <= 0.9 x background.

"random": qualifying candidate positions (stride size/4, random offset) are ordered boustrophedon in bands of one box height and cut into n_per_slide contiguous strata; one box is drawn per stratum in turn, rejecting overlaps.

"stain": the coarse image is deconvolved with reference (plain OD inverse, the slide's background as I0) into per-pixel amounts c1, c2 of stain 1 and stain 2. Amounts below 0.05 (noise, cross-talk; the estimator's default min_stain) count as 0, and so do pixels with ||OD|| > 1 (near-black folds, which the estimator ignores; the plain inverse would give them the largest amounts of both stains). Every candidate box (stride size/4) scores

min(mean c1, mean c2) x (fraction of its pixels with both c1 and c2 > 0)

i.e. high where BOTH stains are abundant and mixed: a box with one stain cannot define two vectors (calibrate would not use it), and boxes half in single-stain tissue bias the estimate, so both are penalised. The score is symmetric in the two stains (dense stain 1 counts only together with stain 2 and vice versa), so the estimator sees both stains' extremes. Boxes are taken best score first (ties: top-left first; deterministic), skipping boxes too close to a chosen one; boxes with score 0 are never chosen. Spread: pass 1 keeps a gap of at least max(size, 0.5 * sqrt(tissue area / n_per_slide)) between boxes, pass 2 a gap of one box width -- both only among boxes scoring >= 0.5 x the best box -- and pass 3 fills up with the best boxes that merely do not overlap.

Calibration

calibrate(): dataset-wide stain vectors from many regions on many slides.

Aggregation (spec item 5, decided 2026-11-30):

  1. QuPath's estimator runs PER enabled region.
  2. A region is not used as "failed" when the estimator raises (e.g. no stained pixel), or as "single-stain" when the eigenvalue ratio lambda2/lambda1 of the covariance of its OD pixels -- filtered exactly like the estimator does -- is below min_eigen_ratio (one stain cannot define two vectors).
  3. .stains: per stain, the robust spherical (geodesic) median of the used per-region vectors -- Weiszfeld's algorithm on the unit sphere (Fletcher, Venkatasubramanian & Joshi 2009), vectors sign-aligned to the reference first. Residual = normalise(cross(stain1, stain2)).
  4. .pooled: estimate on all enabled regions' pixels pooled -- diagnostic only.
  5. .deviations/.variance: angular deviation (deg) of each used region's vector from .stains, and its per-stain summary. This is a MEASUREMENT of stain variance (spec item 5b), never a pass/fail gate.

DEFAULT_MIN_EIGEN_RATIO module-attribute

DEFAULT_MIN_EIGEN_RATIO = 0.02

Calibration

Calibration(*, stains, pooled, per_region, eigen_ratios, excluded, deviations, variance, params, regions)

Result of :func:calibrate.

Attributes:

Name Type Description
stains StainMatrix -- robust spherical median per stain (the result).
pooled StainMatrix or None -- pooled-pixel estimate (diagnostic only).
per_region list[StainMatrix | None] aligned with ``regions.enabled()``.
eigen_ratios list[float] aligned likewise (nan when not computable).
excluded {enabled-region index: "single-stain" | "failed"} -- regions not used.
deviations list aligned with ``regions.enabled()``: {stain name: deg} angular

deviation of the region's vector from stains for used regions, None otherwise.

variance {stain name: {"median", "mean", "sd", "p95", "max", "n_used"}} summary

of deviations over used regions -- a measurement, not a judgement.

params, regions inputs, for provenance.

stains instance-attribute

stains = stains

pooled instance-attribute

pooled = pooled

per_region instance-attribute

per_region = per_region

eigen_ratios instance-attribute

eigen_ratios = eigen_ratios

excluded instance-attribute

excluded = excluded

deviations instance-attribute

deviations = deviations

variance instance-attribute

variance = variance

params instance-attribute

params = params

regions instance-attribute

regions = regions

to_dict

to_dict() -> dict

to_json

to_json(indent=2) -> str

Deterministic JSON (no timestamps): same inputs => identical text.

calibrate

calibrate(slides, regions, *, method='numpy', reference=None, background=None, min_eigen_ratio=DEFAULT_MIN_EIGEN_RATIO, min_glass_px=MIN_GLASS_PX, **params) -> Calibration

Calibrate stain vectors over the enabled regions of slides.

Parameters:

Name Type Description Default
slides ``{slide_id: Slide}``, an iterable of Slides or one Slide.
required
regions RegionSet (only enabled regions are used; indices in the result

refer to positions in regions.enabled()).

required
method estimator backend (see ``available_methods()``).
'numpy'
reference StainMatrix naming/ordering the stains and anchoring vector signs.
None
background (R, G, B) white level for every slide; ``None`` -> measured per

slide by :func:pyHisto.stain.regions.slide_background: per-channel mode of the bright, near-neutral, non-saturated glass pixels, from the coarse level or a finer one until min_glass_px glass pixels are found (ValueError naming the slide otherwise -- no fallback to other slides). The pooled diagnostic uses the mode of all slides' glass histograms.

None
min_glass_px absolute minimum number of glass pixels per slide (default 50,000).
MIN_GLASS_PX
min_eigen_ratio regions whose OD eigenvalue ratio is below this are not

used ("single-stain"); 0 disables the check.

DEFAULT_MIN_EIGEN_RATIO
**params passed to :func:`estimate` (min_stain, max_stain, ignore_percentage, smooth).
{}
Notes

Pixels are read region by region via Slide.read_region; memory is bounded by the regions' total pixels (kept once for the pooled diagnostic).

variance_summary

variance_summary(devs) -> dict

{"median", "mean", "sd" (population), "p95" (linear), "max", "n_used"} of angular deviations in degrees.

spherical_median

spherical_median(vectors, *, anchor=None, tol=1e-13, max_iter=10000) -> np.ndarray

Geodesic (spherical) median of unit vectors, by Weiszfeld iteration in the tangent space (Fletcher et al. 2009).

Vectors are first sign-aligned to anchor (default: the principal axis of their scatter matrix, oriented to a positive component sum). Start = the normalised mean; data points coinciding with the current estimate are skipped in the weights (Vardi-Zhang style guard). Order-independent up to float round-off; robust to a minority of outliers (breakdown point 50%).

eigen_ratio

eigen_ratio(rgb, background, *, min_stain=0.05, max_stain=1.0) -> float

lambda2 / lambda1 of the OD covariance of the pixels QuPath's estimator keeps.

~0 for a single-stain region (OD points on a line), large for two stains. Returns nan when fewer than two pixels survive the filter.