squidpy.experimental.im.fit_stain_reference

squidpy.experimental.im.fit_stain_reference(sdata, image_key, *, method='macenko', scale='auto', method_params=None, white_point=None, tissue_mask_key=None, max_angle_deg=45.0, canonical_reference=None)[source]

Fit a stain reference from an image in a SpatialData object.

Parameters:
  • sdata (SpatialData) – SpatialData object containing the image.

  • image_key (str) – Key of the RGB image in sdata.images to fit on.

  • method (Literal['macenko', 'vahadane', 'reinhard']) – Fitting method: "macenko" (default) or "vahadane" (physical stain-matrix decomposition, usable by both normalize_stains() and decompose_stains()), or "reinhard" (faster statistical colour transfer, no stain separation). Macenko is the default because its one documented weakness - artifact pixels contaminating the fit - is removed by the mandatory tissue mask.

  • scale (Union[str, Literal['auto']]) – Scale level to fit on. "auto" (default) uses the coarsest level, which is cheap and sufficient for colour statistics.

  • method_params (ReinhardParams | MacenkoParams | VahadaneParams | Mapping[str, Any] | None) – A ReinhardParams/MacenkoParams/VahadaneParams instance, a mapping of its fields, or None for defaults. Must match method.

  • white_point (ndarray | None) – Per-channel white point I_0 (3,) for the decomposition methods. If None, a fixed full-white [255, 255, 255] is used (the HistomicsTK/Macenko convention), so unstained pixels round-trip to white. Pass estimate_white_point() only for slides with a known non-white background. Ignored by Reinhard.

  • tissue_mask_key (str | None) – Key of a tissue-label element in sdata.labels (as produced by detect_tissue()) restricting the fit to tissue pixels. If None, f"{image_key}_tissue" is used. A tissue mask is required: if neither exists, a KeyError asks you to run detect_tissue() first.

  • max_angle_deg (float) – Tolerance of the H/E sanity gate for the decomposition methods: the fit raises StainFittingError if either recovered stain vector deviates more than this many degrees from its canonical reference. Default 45. Ignored by Reinhard.

  • canonical_reference (Mapping[str, ndarray] | None) – Canonical H/E reference for the decomposition methods, a mapping with "hematoxylin" and "eosin" keys to (3,) RGB optical-density unit vectors. Drives both the H/E column ordering and the deviation gate. If None, the Ruifrok H&E vectors are used. Ignored by Reinhard.

Return type:

StainReference

Returns:

The fitted StainReference. Nothing is written to sdata.