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
¶
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
¶
normalise(cross(stain1, stain2)) -- QuPath convention, no sign fix.
as_matrix
¶
(3, 3) matrix with the stain vectors as COLUMNS (for deconvolution).
to_json
¶
{"PSR":[r,g,b],"FG":[r,g,b],"Residual":[r,g,b]} (key order kept).
from_json
classmethod
¶
Load from a JSON string or a path to a JSON file.
angle_deg
¶
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
|
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
¶
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.
RegionSet
¶
Ordered list of :class:Region with a JSON round-trip (the review-app file).
from_json
classmethod
¶
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.
|
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 |
'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
|
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):
- QuPath's estimator runs PER enabled region.
- 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 belowmin_eigen_ratio(one stain cannot define two vectors). .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))..pooled: estimate on all enabled regions' pixels pooled -- diagnostic only..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.
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 |
variance |
{stain name: {"median", "mean", "sd", "p95", "max", "n_used"}} summary
|
of |
params, regions |
inputs, for provenance.
|
|
to_json
¶
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 |
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: |
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
¶
{"median", "mean", "sd" (population), "p95" (linear), "max", "n_used"} of angular deviations in degrees.
spherical_median
¶
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
¶
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.