Stain vectors and calibration¶
The idea in plain words¶
Light passing through a stained section is absorbed. Each stain absorbs red, green and blue light in its own proportions: for example Picrosirius Red (PSR) absorbs mostly green and blue, Fast Green (FG) mostly red. (PSR + FG is the running example on this page; other stains work the same way, see Staining protocols.) On a log scale, called optical density (OD), absorptions add up:
where \(I_c\) is a pixel's value in channel \(c\) and \(I_{0,c}\) is the value of empty glass, the background or white level. (In the code \(I_c\) is clipped to at least 1, and a negative OD, a pixel brighter than the background, is set to 0.)
A stain vector is the direction of one pure stain in this 3-D OD space, normalised to length 1. Every pixel's OD is then (approximately) "some PSR + some FG", and colour deconvolution solves for those two amounts. A third, Residual vector, perpendicular to the first two, collects whatever they cannot explain. With the OD of a pixel as a row vector \(\mathbf{OD}\), the amounts as a row vector \(\mathbf{C}\) and the three stain vectors as the rows of \(V\):
If the vectors are wrong, the solver still returns amounts, just wrong ones: some FG is counted as PSR (or the reverse), and the collagen % moves.
How QuPath estimates two vectors¶
The image used, the stain vectors found, and the result:
The stain vectors seen the way QuPath's Visual Stain Editor shows them:
10,000 stained pixels from the 12 sampled regions of the tutorial mouse lung, plotted in optical
density (each dot in its own white-corrected colour), with the calibrated PSR and FG vectors drawn
from the origin in QuPath's stain colours. Pixels made of one stain fall along its line; mixtures
fill the wedge between them. Produced by histo.stain.qc.vector_plots; histo calibrate writes
it as stain_vectors.png. Images: Dafni Gyftaki-Venieri and Nan Yang, Nanchahal Group, Kennedy Institute of Rheumatology, University of Oxford.
| Stain | Calibrated OD vector (R, G, B) | Reference psr-fg |
Angle to reference | Variance median / p95 | |
|---|---|---|---|---|---|
| PSR | 0.491, 0.715, 0.497 |
0.201, 0.853, 0.482 |
18.5° | 6.4° / 12.7° | |
| FG | 0.933, 0.192, 0.303 |
0.899, 0.250, 0.360 |
5.0° | 2.0° / 3.9° | |
| Residual | 0.182, 0.474, −0.861 |
0.226, 0.438, −0.870 |
3.3° | 2.8° / 7.2° |
Background \(I_0\) = (212, 214, 212), measured on this slide; 12 of 12 regions used.
Check the scatterplots the same way you would in QuPath (see QuPath's Separating stains → Check scatterplots): each stain's line should run along the edge of its own cloud of pixels.
pyHisto uses QuPath's own algorithm ("Estimate stain vectors", QuPath 0.7.0), ported to NumPy and checked against real QuPath:
- Convert pixels to OD with the background \(I_0\).
- Keep only stained pixels: \(\mathrm{OD}_c \ge 0.05\) in every channel and OD length \(\lVert\mathbf{OD}\rVert \le 1.0\).
- Find the plane in OD space that these pixels lie in: the eigenvectors \(\mathbf{e}_1, \mathbf{e}_2\) of the two largest eigenvalues of their OD covariance (population covariance).
-
Within that plane, measure each pixel's angle
\[ \varphi = \operatorname{atan2}\!\left(\mathbf{OD}\cdot\mathbf{e}_1,\; \mathbf{OD}\cdot\mathbf{e}_2\right) \]and sort the \(n\) pixels by \(\varphi\). With \(\alpha = 1\,\% = 0.01\) (the ignored percentage), take the pixels at the sorted positions
\[ i_1 = \max\!\big(0,\ \lfloor \alpha n + 0.5 \rfloor\big), \qquad i_2 = \min\!\big(n - 1,\ \lfloor (1 - \alpha)\, n + 0.5 \rfloor\big) \](positions count from 0). Their OD vectors, normalised to length 1, are the two stain vectors \(\mathbf{s}_1, \mathbf{s}_2\).
-
Name and order them like a reference, the staining protocol you chose (default
psr-fg: rough PSR/FG directions): the reference only decides which is which. - Residual = cross product of the two, normalised: \(\mathbf{r} = \dfrac{\mathbf{s}_1 \times \mathbf{s}_2}{\lVert \mathbf{s}_1 \times \mathbf{s}_2 \rVert}\).
QuPath-exact
The NumPy port matches real QuPath within 1° per vector on golden test
images (synthetic, and open PSR tiles; tests/test_stain_golden.py), including
QuPath's own eigen-decomposition and rounding. With QuPath's GUI smoothing
on, the tolerance is 3°. Stain estimation stays on the CPU so that this
exactness holds.
The open test tiles also carry an expert collagen mask, so the test-suite checks more than angles: estimate the vectors on a tile, deconvolve, and the PSR channel must agree with what an expert annotated as collagen.
Why one region is not enough¶
Step 4 assumes the pixels contain both stains. A region with only PSR (or only FG) lies on a line, not a plane, and the "second" vector is noise. In a synthetic test with known true vectors, real QuPath on a PSR-only quadrant gave a Fast Green vector 49° off the truth (PSR stayed within 0.6°).
So pyHisto samples many regions on many slides:
flowchart LR
S1["slide 1"] --> R1["regions<br/>#0 … #11"]
S2["slide 2"] --> R2["regions<br/>#12 … #23"]
R1 --> E["estimate per region<br/>(QuPath algorithm)"]
R2 --> E
E --> X{"two stains<br/>present?"}
X -- "no: single-stain<br/>or failed" --> N["not used<br/>(listed)"]
X -- yes --> M["robust spherical median<br/>per stain"]
M --> V["stain vectors<br/>+ variance"]
- Sampling (
propose_regions): fixed-size boxes inside the tissue of every slide, not overlapping, never touching no-data, each at leastmin_tissue_fractissue (default 80 %). Each slide's boxes do not depend on which other slides are in the set. Two strategies:- Stain-guided (
strategy="stain", thehisto calibratedefault): a coarse level of the slide is separated with the protocol's reference vectors (plain OD inverse, the slide's own \(I_0\)) into a map of the amount of stain 1 (\(c_1\)) and of stain 2 (\(c_2\)). Each candidate box scores \(\min(\bar c_1, \bar c_2) \times f_{12}\), with \(\bar c\) the box means and \(f_{12}\) the fraction of its pixels that contain both stains: boxes win where both stains are abundant and mixed. For PSR + FG that means collagen-dense areas that also carry Fast Green. A box with one stain cannot define two vectors (step 3), and a box half in single-stain tissue pulls the estimate, so both score low. The rule is symmetric, so the estimator sees the extremes of both stains. Amounts below 0.05 (noise) and near-black pixels (\(\lVert \mathrm{OD} \rVert > 1\), e.g. folds; the estimator ignores them too, while the plain inverse would give them the highest amounts) count as no stain. The best boxes are taken, spread over the tissue: first about half the side of a \(1/n\) share of the tissue apart, then one box width apart (both among boxes scoring at least half the best), then merely not overlapping. Deterministic; the seed is not used. The QC report shows the stain-1 map with the boxes (stain_density_<slide>.png). - Random (
strategy="random", the Python default; CLI--sampling random): stratified random boxes spread over the tissue; the sameseedgives the same boxes.
- Stain-guided (
- Per-region estimate: QuPath's algorithm on each box separately.
- Single-stain check: if the OD pixels of a box (filtered as in step 2
above) lie almost on a line, the box is not used (
"single-stain"). With \(\lambda_1 \ge \lambda_2 \ge \lambda_3\) the eigenvalues of their OD covariance, that is when \(\lambda_2 / \lambda_1 < 0.02\) (min_eigen_ratio). A box where the estimator fails is not used either ("failed"). This is the only reason a region is ever dropped: two vectors cannot be measured from one stain. - Robust spherical median: for each of the two stains, the "middle" direction of the per-region vectors on the unit sphere (Weiszfeld's algorithm, Fletcher et al. 2009). Unlike an average it is not pulled by a few unusual regions (it tolerates up to half of them). The Residual is recomputed as the cross product.
- Variance: how far each used region's vector is from the median, in degrees: see Stain variance.
The spherical median, exactly
For one stain, let \(\mathbf{v}_1, \dots, \mathbf{v}_k\) be the used regions' unit vectors. They are first sign-aligned to an anchor \(\mathbf{a}\) (the reference vector of that stain; without a reference, the principal axis of \(\sum_i \mathbf{v}_i \mathbf{v}_i^{\top}\), oriented to a positive component sum): \(\mathbf{v}_i \leftarrow -\mathbf{v}_i\) when \(\mathbf{v}_i \cdot \mathbf{a} < 0\). The start is the normalised mean, \(\mathbf{m} = \bar{\mathbf{v}} / \lVert \bar{\mathbf{v}} \rVert\). Each Weiszfeld step works in the tangent plane at \(\mathbf{m}\):
(then \(\mathbf{m}\) is re-normalised). Regions with \(d_i = 0\), i.e. lying exactly on the current estimate, are left out of the sums. The iteration stops when \(\lVert\boldsymbol{\delta}\rVert < 10^{-13}\) (at most 10 000 steps).
Only when no region is usable does calibration stop with an error.
Why not pool all pixels and estimate once?
It was tried. With FG-only regions mixed in, the pooled-pixel estimate went
about 37° wrong: the single-stain pixels distort the plane. The pooled
estimate is still computed and shown as a diagnostic (cal.pooled,
the "pooled pixels" row in the report), never used as the result.
The background \(I_0\)¶
"White" is not a colour of its own¶
White light is a mixture of all visible wavelengths. A camera sensor records
it as equal red, green and blue values only when its channels are balanced for
that light source: this balancing is white balance. In brightfield, "white"
is the light that passes through clean glass, mountant and coverslip, recorded
by a scanner with its own lamp spectrum, filters, sensor and white-balance
setting. So the empty glass is usually not (255, 255, 255) but a slightly
tinted grey, and it differs between scanners, lamps, slides and even days:
there are many different whites.
(255, 255, 255) strip. Liver PSR tiles: Decoding Fibrosis / CoCoMASLD
tiles — Wojciechowska M., Zenodo,
doi:10.5281/zenodo.20929332,
CC BY 4.0. Kidney trichrome:
OpenSlide test data, Zeiss-5, Venklab, Pathology, UTHSCSA (CC0). H&E: OpenSlide
test data, Aperio CMU-1-Small-Region (CC0). Mouse lung: Images: Dafni
Gyftaki-Venieri and Nan Yang, Nanchahal Group, Kennedy Institute of
Rheumatology, University of Oxford.Why OD needs the right white¶
OD is defined relative to that white, channel by channel:
so empty glass (\(I_c = I_{0,c}\)) has OD 0 and only the stains add to it. With a wrong white \(I'_{0,c}\) (for example 255 when the glass is 212), every pixel's OD is shifted by the same constant in each channel,
and the glass itself gets a non-zero OD (\(\log_{10}(255/212) \approx 0.08\)). When the shift differs between channels, i.e. the glass is tinted, it points in a colour direction of its own: the measured stain vectors tilt, the amounts of each stain change, and so does the collagen %.
The per-channel \(I_0\) is also the white-balance correction: dividing each channel by \(I_{0,c}\) maps the measured glass to \((1, 1, 1)\), whatever the scanner's white was. Measuring \(I_0\) from the slide itself therefore makes scans with different whites comparable.
How pyHisto measures it¶
QuPath's GUI takes the per-channel mode of a smoothed image, which needs a
big patch of empty glass in the crop. pyHisto instead measures \(I_0\) per
slide (histo.stain.regions.slide_background), from the slide's glass
pixels only:
- Glass candidates are pixels that are not no-data, not over-exposed (255 in all three channels: their true value is unknown), near-neutral (darkest channel ≥ 0.8 × brightest; stained tissue is coloured) and bright in all three channels (darkest channel ≥ 0.9 × its 99th percentile over the image, and ≥ 128).
- \(I_0\) is the per-channel mode of the candidates (ties go to the
brighter value, as in QuPath). In the tutorial slide it was
(212, 214, 212), noticeably darker than 255. - An absolute minimum of glass pixels is required (
min_glass_px, default 50,000; CLI--min-glass-px). pyHisto starts on a coarse pyramid level (about 1024 px long) and, if it holds fewer, reads progressively finer levels (whole level, in strips; memory stays bounded). If even level 0 has too few, calibration stops with an error naming the slide; passbackground=/--background R G Bfor it. There is no fallback to other slides' glass. - Sanity guard: a measured \(I_0\) with a channel below 100 or below 0.6 × the brightest channel is rejected with an error showing the values.
Why bright pixels only: the mode of all pixels is the glass colour only when glass is the most common colour. On a slide that is almost all tissue, a few very dark Fast Green pixels with red = 0 were the most frequent red value, and the old rule returned \(I_0\) = (0, 212, 210): every region of that slide failed. The bright-pixel rule gives (210, 212, 210) there.
- Each region is estimated with its own slide's background, so slides scanned with slightly different illumination are handled.
calibrate(..., background=(R, G, B))(CLI:--background R G B) forces one white level for all slides.- The per-slide values are stored in
calibration.json(params.background_per_slide, with the level used inparams.background_leveland the number of glass pixels inparams.background_glass_px) and reused by the QC rendering.
Use the same I₀ downstream
Deconvolution later must use a background consistent with the calibration. Vectors measured against \(I_0 = 212\) and applied with \(I_0 = 255\) are not the same vectors in practice.
See the pyHisto.stain API.

