wsi-patching 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- wsi_patching/__init__.py +38 -0
- wsi_patching/annotations/__init__.py +3 -0
- wsi_patching/annotations/add_cell_annotation_from_csv.py +152 -0
- wsi_patching/assets/models/cellvit_tissue_detector.pt +0 -0
- wsi_patching/backends/__init__.py +0 -0
- wsi_patching/backends/cupy_numpy.py +80 -0
- wsi_patching/backends/fastslide.py +243 -0
- wsi_patching/backends/torch_device.py +45 -0
- wsi_patching/core/__init__.py +4 -0
- wsi_patching/core/chunking_and_batching.py +519 -0
- wsi_patching/core/pipeline.py +566 -0
- wsi_patching/core/types/__init__.py +0 -0
- wsi_patching/core/types/types.py +145 -0
- wsi_patching/core/types/util_types.py +93 -0
- wsi_patching/core/wsi_grid.py +119 -0
- wsi_patching/custom_component/__init__.py +18 -0
- wsi_patching/encoders/__init__.py +3 -0
- wsi_patching/encoders/pngencoder.py +72 -0
- wsi_patching/filtering/__init__.py +15 -0
- wsi_patching/filtering/cellvit_tissue_classifier_filter.py +124 -0
- wsi_patching/filtering/low_contrast_background_filter.py +125 -0
- wsi_patching/filtering/otsu_filter.py +217 -0
- wsi_patching/filtering/pen_artifact_filter.py +216 -0
- wsi_patching/py.typed +0 -0
- wsi_patching/regions_of_interest/__init__.py +4 -0
- wsi_patching/regions_of_interest/attach_rois.py +59 -0
- wsi_patching/regions_of_interest/roi_providers.py +94 -0
- wsi_patching/regions_of_interest/rois.py +78 -0
- wsi_patching/transforms/__init__.py +4 -0
- wsi_patching/transforms/macenko_normalizer.py +175 -0
- wsi_patching/transforms/reinhard_normalizer.py +271 -0
- wsi_patching/utils/__init__.py +3 -0
- wsi_patching/utils/logging_config.py +13 -0
- wsi_patching/utils/meta_typing.py +94 -0
- wsi_patching/utils/profiling.py +115 -0
- wsi_patching/utils/wsi_thumbnail_visualization.py +208 -0
- wsi_patching/writers/__init__.py +10 -0
- wsi_patching/writers/materialize_writers/__init__.py +0 -0
- wsi_patching/writers/materialize_writers/materialize_writer_base.py +92 -0
- wsi_patching/writers/materialize_writers/webdataset/__init__.py +0 -0
- wsi_patching/writers/materialize_writers/webdataset/webdataset_loader.py +165 -0
- wsi_patching/writers/materialize_writers/webdataset/webdataset_writer.py +69 -0
- wsi_patching/writers/stream_writers/__init__.py +0 -0
- wsi_patching/writers/stream_writers/numpy_stream_writer.py +36 -0
- wsi_patching/writers/stream_writers/stream_writer_base.py +71 -0
- wsi_patching/writers/stream_writers/torch_stream_writer.py +67 -0
- wsi_patching-0.5.0.dist-info/METADATA +249 -0
- wsi_patching-0.5.0.dist-info/RECORD +50 -0
- wsi_patching-0.5.0.dist-info/WHEEL +4 -0
- wsi_patching-0.5.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import xml.etree.ElementTree as ET
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from typing import Dict, List, Optional, Tuple
|
|
4
|
+
|
|
5
|
+
from wsi_patching.backends.fastslide import get_level_downsamples
|
|
6
|
+
from wsi_patching.core.types.types import SlideBase
|
|
7
|
+
from wsi_patching.regions_of_interest.rois import ROI, BoxROI
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ROIProvider:
|
|
11
|
+
def for_slide(self, slide: SlideBase) -> List[ROI]:
|
|
12
|
+
raise NotImplementedError
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class RectROIProvider(ROIProvider):
|
|
17
|
+
rois: Dict[str, List[Tuple[int, int, int, int]]]
|
|
18
|
+
|
|
19
|
+
def for_slide(self, slide: SlideBase) -> List[ROI]:
|
|
20
|
+
wsi_id = slide.wsi_id
|
|
21
|
+
W, H = slide.dims
|
|
22
|
+
out: List[ROI] = []
|
|
23
|
+
for x, y, w, h in self.rois.get(wsi_id, []):
|
|
24
|
+
if x < 0 or y < 0 or (x + w) > W or (y + h) > H:
|
|
25
|
+
raise ValueError(f"ROI {(x, y, w, h)} for slide {wsi_id} lies outside {(W, H)}")
|
|
26
|
+
out.append(BoxROI(x, y, w, h))
|
|
27
|
+
return out
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class RectROIfromXMLProvider(ROIProvider):
|
|
32
|
+
rois: Dict[str, str]
|
|
33
|
+
annotation_group: str = "roi"
|
|
34
|
+
annotation_level: Optional[int] = None
|
|
35
|
+
|
|
36
|
+
def for_slide(self, slide: SlideBase) -> List[ROI]:
|
|
37
|
+
out: List[ROI] = []
|
|
38
|
+
|
|
39
|
+
xml_file = self.rois[slide.wsi_id]
|
|
40
|
+
tree = ET.parse(xml_file)
|
|
41
|
+
root = tree.getroot()
|
|
42
|
+
W, H = slide.dims
|
|
43
|
+
|
|
44
|
+
if self.annotation_level is not None and self.annotation_level != slide.level:
|
|
45
|
+
downsamples = get_level_downsamples(slide.wsi_path)
|
|
46
|
+
scale = downsamples[self.annotation_level] / downsamples[slide.level]
|
|
47
|
+
else:
|
|
48
|
+
scale = 1.0
|
|
49
|
+
|
|
50
|
+
scale /= slide.resample_factor
|
|
51
|
+
|
|
52
|
+
for ann in root.findall(f".//Annotation[@PartOfGroup='{self.annotation_group}']"):
|
|
53
|
+
ann_type = ann.get("Type")
|
|
54
|
+
if ann_type not in ("Rectangle", "Polygon"):
|
|
55
|
+
continue
|
|
56
|
+
|
|
57
|
+
coords = ann.find("Coordinates")
|
|
58
|
+
if coords is None:
|
|
59
|
+
continue
|
|
60
|
+
|
|
61
|
+
coord_elements = coords.findall("Coordinate")
|
|
62
|
+
|
|
63
|
+
if ann_type == "Polygon":
|
|
64
|
+
if len(coord_elements) != 4:
|
|
65
|
+
raise ValueError(
|
|
66
|
+
f"Polygon annotation for slide {slide.wsi_id} has {len(coord_elements)} point(s); "
|
|
67
|
+
"only 4-point polygons representing axis-aligned bounding boxes are supported"
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
xs = [float(coord.attrib["X"]) * scale for coord in coord_elements]
|
|
71
|
+
ys = [float(coord.attrib["Y"]) * scale for coord in coord_elements]
|
|
72
|
+
|
|
73
|
+
if ann_type == "Polygon":
|
|
74
|
+
if len(set(xs)) != 2 or len(set(ys)) != 2:
|
|
75
|
+
raise ValueError(
|
|
76
|
+
f"Polygon annotation for slide {slide.wsi_id} is not an axis-aligned bounding box "
|
|
77
|
+
f"(expected exactly 2 unique X values and 2 unique Y values)"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
x_min, y_min = min(xs), min(ys)
|
|
81
|
+
x_max, y_max = max(xs), max(ys)
|
|
82
|
+
if x_min < 0 or y_min < 0 or x_max > W or y_max > H:
|
|
83
|
+
raise ValueError(
|
|
84
|
+
f"ROI {(x_min, y_min, x_max - x_min, y_max - y_min)} for slide {slide.wsi_id} lies outside {(W, H)}"
|
|
85
|
+
)
|
|
86
|
+
out.append(BoxROI(int(x_min), int(y_min), int(x_max - x_min), int(y_max - y_min)))
|
|
87
|
+
|
|
88
|
+
return out
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class WholeSlideProvider(ROIProvider):
|
|
92
|
+
def for_slide(self, slide: SlideBase) -> List[ROI]:
|
|
93
|
+
W, H = slide.dims
|
|
94
|
+
return [BoxROI(0, 0, int(W), int(H))]
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from typing import List, Tuple
|
|
3
|
+
|
|
4
|
+
Box = Tuple[int, int, int, int]
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class ROI:
|
|
8
|
+
def bounds(self) -> Box:
|
|
9
|
+
raise NotImplementedError
|
|
10
|
+
|
|
11
|
+
def contains_point(self, x: float, y: float) -> bool:
|
|
12
|
+
raise NotImplementedError
|
|
13
|
+
|
|
14
|
+
def contains_patch(self, bx, by, bw, bh) -> bool:
|
|
15
|
+
return (
|
|
16
|
+
self.contains_point(bx, by)
|
|
17
|
+
and self.contains_point(bx + bw - 1, by)
|
|
18
|
+
and self.contains_point(bx, by + bh - 1)
|
|
19
|
+
and self.contains_point(bx + bw - 1, by + bh - 1)
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
def intersects_patch(self, bx, by, bw, bh) -> bool:
|
|
23
|
+
return (
|
|
24
|
+
self.contains_point(bx, by)
|
|
25
|
+
or self.contains_point(bx + bw - 1, by)
|
|
26
|
+
or self.contains_point(bx, by + bh - 1)
|
|
27
|
+
or self.contains_point(bx + bw - 1, by + bh - 1)
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class BoxROI(ROI):
|
|
33
|
+
x: int
|
|
34
|
+
y: int
|
|
35
|
+
w: int
|
|
36
|
+
h: int
|
|
37
|
+
|
|
38
|
+
def bounds(self) -> Box:
|
|
39
|
+
return (self.x, self.y, self.w, self.h)
|
|
40
|
+
|
|
41
|
+
def contains_point(self, x: float, y: float) -> bool:
|
|
42
|
+
return (self.x <= x < self.x + self.w) and (self.y <= y < self.y + self.h)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class RectAreaROI:
|
|
47
|
+
x: int
|
|
48
|
+
y: int
|
|
49
|
+
w: int
|
|
50
|
+
h: int
|
|
51
|
+
|
|
52
|
+
def as_tuple(self) -> Tuple[int, int, int, int]:
|
|
53
|
+
return (self.x, self.y, self.w, self.h)
|
|
54
|
+
|
|
55
|
+
def subdivide(self, max_size: int, tile_size: int, stride: int) -> List["RectAreaROI"]:
|
|
56
|
+
"""
|
|
57
|
+
Split this rectangle into smaller rectangles if width or height > max_size.
|
|
58
|
+
Splits are aligned to stride so that tiles stay consistent.
|
|
59
|
+
"""
|
|
60
|
+
sub_rois: List[RectAreaROI] = []
|
|
61
|
+
x_end = self.x + self.w
|
|
62
|
+
y_end = self.y + self.h
|
|
63
|
+
|
|
64
|
+
for yy in range(self.y, y_end, max_size):
|
|
65
|
+
for xx in range(self.x, x_end, max_size):
|
|
66
|
+
ww = min(max_size, x_end - xx)
|
|
67
|
+
hh = min(max_size, y_end - yy)
|
|
68
|
+
|
|
69
|
+
# Align to stride boundaries: ensure splits produce valid tile starts
|
|
70
|
+
# (optional: round ww/hh up so they cover full tiles)
|
|
71
|
+
aligned_w = (ww // stride) * stride
|
|
72
|
+
aligned_h = (hh // stride) * stride
|
|
73
|
+
if aligned_w < tile_size or aligned_h < tile_size:
|
|
74
|
+
continue
|
|
75
|
+
|
|
76
|
+
sub_rois.append(RectAreaROI(xx, yy, aligned_w, aligned_h))
|
|
77
|
+
|
|
78
|
+
return sub_rois
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
from typing import Any, Iterable, Optional, Tuple
|
|
2
|
+
|
|
3
|
+
from wsi_patching.backends.cupy_numpy import get_xp_backend
|
|
4
|
+
from wsi_patching.core.pipeline import Stage
|
|
5
|
+
from wsi_patching.core.types.types import CollatedPatchBatch
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MacenkoNormalizer(Stage):
|
|
9
|
+
"""
|
|
10
|
+
Macenko Normalization stage.
|
|
11
|
+
|
|
12
|
+
- Fits (H, max_sat) on the first batch (stays on that batch's backend)
|
|
13
|
+
- Applies to all subsequent batches without leaving the backend
|
|
14
|
+
- Adds meta_col 'macenko_normalized' (bool)
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(
|
|
18
|
+
self, alpha: float = 1.0, beta: float = 0.15, light_intensity: int = 255, pixel_limit: Optional[int] = 500_000
|
|
19
|
+
) -> None:
|
|
20
|
+
self.alpha = float(alpha)
|
|
21
|
+
self.beta = float(beta)
|
|
22
|
+
self.I0 = int(light_intensity)
|
|
23
|
+
self.pixel_limit = pixel_limit
|
|
24
|
+
|
|
25
|
+
self._fitted = False
|
|
26
|
+
self._H_mat: Any = None # xp.ndarray (3,2)
|
|
27
|
+
self._max_sat: Any = None # xp.ndarray (2,1)
|
|
28
|
+
self._xp: Any = None # module: numpy or cupy
|
|
29
|
+
|
|
30
|
+
self.log.info(
|
|
31
|
+
"MacenkoNormalizer fits on the first batch of each image. If the first batch is background-only, "
|
|
32
|
+
"fitting will likely result in unwanted behavior. Use with caution."
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
def for_slide(self, slide_path: str) -> "MacenkoNormalizer":
|
|
36
|
+
return MacenkoNormalizer(
|
|
37
|
+
alpha=self.alpha, beta=self.beta, light_intensity=self.I0, pixel_limit=self.pixel_limit
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
def validate(self):
|
|
41
|
+
self.ctx.require_key("use_gpu")
|
|
42
|
+
|
|
43
|
+
def __call__(self, it: Iterable[CollatedPatchBatch]) -> Iterable[CollatedPatchBatch]:
|
|
44
|
+
for batch in it:
|
|
45
|
+
if not self._fitted:
|
|
46
|
+
self.fit(batch)
|
|
47
|
+
|
|
48
|
+
patches = _ensure_rgb_uint8_nhwc(batch.patches, self._xp)
|
|
49
|
+
N, Hh, Ww, _ = patches.shape
|
|
50
|
+
|
|
51
|
+
flat = patches.reshape(-1, 3)
|
|
52
|
+
OD = _to_OD(flat, self.I0, self._xp) # (N*H*W, 3)
|
|
53
|
+
|
|
54
|
+
C, *_ = self._xp.linalg.lstsq(self._H_mat, OD.T, rcond=None)
|
|
55
|
+
|
|
56
|
+
denom = self._xp.clip(self._max_sat.reshape(-1, 1), 1e-6, None)
|
|
57
|
+
C_norm = self._xp.clip(C / denom, 0.0, 1.0)
|
|
58
|
+
|
|
59
|
+
OD_hat = (self._H_mat @ C_norm).T # (N*H*W, 3)
|
|
60
|
+
normalized = _from_OD(OD_hat, self.I0, self._xp).reshape(N, Hh, Ww, 3)
|
|
61
|
+
|
|
62
|
+
batch.patches = normalized
|
|
63
|
+
|
|
64
|
+
self.log.info(f"Yielded batch for wsi='{batch.wsi_id}' size={normalized.shape[0]}")
|
|
65
|
+
yield batch
|
|
66
|
+
|
|
67
|
+
def fit(self, batch: CollatedPatchBatch) -> None:
|
|
68
|
+
if self._fitted:
|
|
69
|
+
return
|
|
70
|
+
|
|
71
|
+
self._xp = get_xp_backend(self.ctx["use_gpu"])
|
|
72
|
+
|
|
73
|
+
H_mat, max_sat = self._macenko_fit_from_batch_xp(patches_u8_nhwc=batch.patches)
|
|
74
|
+
|
|
75
|
+
self._H_mat = H_mat
|
|
76
|
+
self._max_sat = max_sat
|
|
77
|
+
self._fitted = True
|
|
78
|
+
|
|
79
|
+
self.log.info(
|
|
80
|
+
f"Fitted on wsi='{batch.wsi_id}' "
|
|
81
|
+
f"(alpha={self.alpha}, beta={self.beta}, I0={self.I0}, "
|
|
82
|
+
f"pixel_limit={self.pixel_limit}"
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
def _macenko_fit_from_batch_xp(self, patches_u8_nhwc) -> Tuple:
|
|
86
|
+
"""
|
|
87
|
+
Returns (H(3,2), max_sat(2,1)) on the same xp backend as input.
|
|
88
|
+
"""
|
|
89
|
+
patches = _ensure_rgb_uint8_nhwc(patches_u8_nhwc, self._xp)
|
|
90
|
+
|
|
91
|
+
flat = patches.reshape(-1, 3) # (N*H*W, 3)
|
|
92
|
+
OD = _to_OD(flat, self.I0, self._xp) # (M, 3)
|
|
93
|
+
|
|
94
|
+
# Background mask: keep pixels where all OD >= beta
|
|
95
|
+
od_norm = self._xp.linalg.norm(OD, axis=1)
|
|
96
|
+
keep = od_norm >= self.beta
|
|
97
|
+
OD = OD[keep]
|
|
98
|
+
if OD.size == 0:
|
|
99
|
+
raise RuntimeError("Macenko fit: all pixels filtered as background.")
|
|
100
|
+
|
|
101
|
+
# Optional subsampling
|
|
102
|
+
if self.pixel_limit is not None and OD.shape[0] > self.pixel_limit:
|
|
103
|
+
idx = self._xp.random.RandomState(seed=0).choice(int(OD.shape[0]), size=self.pixel_limit, replace=False)
|
|
104
|
+
OD = OD[idx]
|
|
105
|
+
|
|
106
|
+
# Center & SVD
|
|
107
|
+
ODc = OD - self._xp.mean(OD, axis=0, keepdims=True)
|
|
108
|
+
_, _, vt = self._xp.linalg.svd(ODc, full_matrices=False)
|
|
109
|
+
eigvecs = vt.T[:, :2] # (3,2)
|
|
110
|
+
|
|
111
|
+
# Fix signs for determinism
|
|
112
|
+
sign0 = self._xp.sign(eigvecs[0, 0]) if eigvecs[0, 0] != 0 else 1.0
|
|
113
|
+
sign1 = self._xp.sign(eigvecs[0, 1]) if eigvecs[0, 1] != 0 else 1.0
|
|
114
|
+
eigvecs[:, 0] *= sign0
|
|
115
|
+
eigvecs[:, 1] *= sign1
|
|
116
|
+
|
|
117
|
+
# Project & angle extremes
|
|
118
|
+
proj = OD @ eigvecs # (M,2)
|
|
119
|
+
angles = self._xp.arctan2(proj[:, 1], proj[:, 0])
|
|
120
|
+
min_phi = self._xp.percentile(angles, self.alpha, axis=None)
|
|
121
|
+
max_phi = self._xp.percentile(angles, 100.0 - self.alpha, axis=None)
|
|
122
|
+
|
|
123
|
+
v1 = eigvecs @ self._xp.asarray([self._xp.cos(min_phi), self._xp.sin(min_phi)], dtype=self._xp.float32)
|
|
124
|
+
v2 = eigvecs @ self._xp.asarray([self._xp.cos(max_phi), self._xp.sin(max_phi)], dtype=self._xp.float32)
|
|
125
|
+
H_mat = self._xp.stack([v1, v2], axis=1).astype(self._xp.float32) # (3,2)
|
|
126
|
+
|
|
127
|
+
# Stable column order (heuristic)
|
|
128
|
+
if H_mat[0, 0] < H_mat[0, 1]:
|
|
129
|
+
H_mat = H_mat[:, [1, 0]]
|
|
130
|
+
|
|
131
|
+
# Normalize columns:
|
|
132
|
+
H_mat = H_mat / self._xp.clip(self._xp.linalg.norm(H_mat, axis=0, keepdims=True), 1e-12, None)
|
|
133
|
+
|
|
134
|
+
# Least squares for C on fit pixels to get per-stain 99th percentile
|
|
135
|
+
C, *_ = self._xp.linalg.lstsq(H_mat, OD.T, rcond=None)
|
|
136
|
+
max_sat = self._xp.percentile(C, 99.0, axis=(1,), keepdims=True).astype(self._xp.float32)
|
|
137
|
+
max_sat = self._xp.where(max_sat == 0, self._xp.asarray(1.0, dtype=self._xp.float32), max_sat)
|
|
138
|
+
|
|
139
|
+
return H_mat, max_sat
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _ensure_rgb_uint8_nhwc(x, xp):
|
|
143
|
+
if x.ndim != 4 or x.shape[-1] < 3:
|
|
144
|
+
raise ValueError(f"Expected NHWC with >=3 channels, got {x.shape}")
|
|
145
|
+
if x.dtype != xp.uint8:
|
|
146
|
+
x = x.astype(xp.uint8, copy=False)
|
|
147
|
+
return x[..., :3]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _to_OD(flat_rgb_u8, I0: int, xp):
|
|
151
|
+
"""
|
|
152
|
+
Convert flat RGB values to optical density (OD).
|
|
153
|
+
|
|
154
|
+
Args:
|
|
155
|
+
flat_rgb_u8: Array of shape (N, 3), dtype uint8 or float-like in [0, 255].
|
|
156
|
+
I0: Reference/white intensity (typically 255).
|
|
157
|
+
"""
|
|
158
|
+
rgb = flat_rgb_u8.astype(xp.float32, copy=False)
|
|
159
|
+
rgb = xp.clip(rgb, 1.0, float(I0))
|
|
160
|
+
return -xp.log(rgb / float(I0))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _from_OD(OD, I0: int, xp):
|
|
164
|
+
"""
|
|
165
|
+
Convert optical density (OD) back to RGB uint8.
|
|
166
|
+
|
|
167
|
+
Args:
|
|
168
|
+
OD: Array of shape (N, 3), optical density values.
|
|
169
|
+
I0: Reference/white intensity (typically 255).
|
|
170
|
+
"""
|
|
171
|
+
white_intensity = float(I0)
|
|
172
|
+
|
|
173
|
+
intensity_float = xp.exp(-OD) * white_intensity
|
|
174
|
+
rgb_uint8 = xp.clip(intensity_float, 0.0, 255.0).astype(xp.uint8)
|
|
175
|
+
return rgb_uint8
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
from typing import Any, Iterable, Tuple
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from wsi_patching.backends.cupy_numpy import get_xp_backend
|
|
6
|
+
from wsi_patching.core.pipeline import Stage
|
|
7
|
+
from wsi_patching.core.types.types import CollatedPatchBatch
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _rgb_to_lab(rgb_nhwc: np.ndarray, xp, rgb2xyz=None, white=None) -> np.ndarray:
|
|
11
|
+
"""
|
|
12
|
+
Convert an RGB image to Lab colorspace.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
rgb_nhwc: RGB image(s) as float32 in [0, 1]. Shape (N, H, W, 3) or (H, W, 3).
|
|
16
|
+
xp: array backend module (numpy or cupy).
|
|
17
|
+
rgb2xyz: optional pre-allocated (3, 3) RGB->XYZ matrix on the backend.
|
|
18
|
+
white: optional pre-allocated (1, 3, 1, 1) D65 white point on the backend.
|
|
19
|
+
|
|
20
|
+
Returns:
|
|
21
|
+
Lab image with same layout as input. L in [0, 100], a/b in ~[-128, 127].
|
|
22
|
+
"""
|
|
23
|
+
# Convert to NCHW for processing
|
|
24
|
+
if rgb_nhwc.ndim == 4:
|
|
25
|
+
N, H, W, C = rgb_nhwc.shape
|
|
26
|
+
rgb_nchw = rgb_nhwc.transpose(0, 3, 1, 2) # (N,3,H,W)
|
|
27
|
+
else: # single image (H,W,3)
|
|
28
|
+
rgb_nchw = rgb_nhwc.transpose(2, 0, 1)[None, ...] # (1,3,H,W)
|
|
29
|
+
|
|
30
|
+
# sRGB -> linear RGB
|
|
31
|
+
threshold = 0.04045
|
|
32
|
+
lin_rgb = xp.where(
|
|
33
|
+
rgb_nchw > threshold,
|
|
34
|
+
xp.power(((rgb_nchw + 0.055) / 1.055), 2.4),
|
|
35
|
+
rgb_nchw / 12.92,
|
|
36
|
+
) # (N,3,H,W)
|
|
37
|
+
|
|
38
|
+
# RGB -> XYZ
|
|
39
|
+
if rgb2xyz is None:
|
|
40
|
+
rgb2xyz = xp.array(
|
|
41
|
+
[[0.412453, 0.357580, 0.180423],
|
|
42
|
+
[0.212671, 0.715160, 0.072169],
|
|
43
|
+
[0.019334, 0.119193, 0.950227]], dtype=xp.float32
|
|
44
|
+
)
|
|
45
|
+
# xyz[n,i,h,w] = Σ_j rgb2xyz[i,j] * lin_rgb[n,j,h,w] == M @ rgb per pixel
|
|
46
|
+
xyz = xp.einsum('ij, njhw -> nihw', rgb2xyz, lin_rgb)
|
|
47
|
+
|
|
48
|
+
# Normalize for D65 white point
|
|
49
|
+
if white is None:
|
|
50
|
+
white = xp.array([0.95047, 1.0, 1.08883], dtype=xp.float32).reshape(1, 3, 1, 1)
|
|
51
|
+
xyz_norm = xyz / white
|
|
52
|
+
|
|
53
|
+
# Non‑linear transform to Lab
|
|
54
|
+
delta = 0.008856
|
|
55
|
+
power = xp.where(
|
|
56
|
+
xyz_norm > delta,
|
|
57
|
+
xp.power(xp.clip(xyz_norm, delta, None), 1/3.0), # clamp to avoid numerical issues
|
|
58
|
+
(7.787 * xyz_norm) + (4.0 / 29.0),
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
L = 116.0 * power[:, 1, :, :] - 16.0
|
|
62
|
+
a = 500.0 * (power[:, 0, :, :] - power[:, 1, :, :])
|
|
63
|
+
b = 200.0 * (power[:, 1, :, :] - power[:, 2, :, :])
|
|
64
|
+
|
|
65
|
+
lab_nchw = xp.stack([L, a, b], axis=1) # (N,3,H,W)
|
|
66
|
+
lab_nhwc = lab_nchw.transpose(0, 2, 3, 1) # (N,H,W,3)
|
|
67
|
+
if rgb_nhwc.ndim == 3:
|
|
68
|
+
lab_nhwc = lab_nhwc[0]
|
|
69
|
+
return lab_nhwc
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _lab_to_rgb(lab_nhwc: np.ndarray, xp, clip: bool = True, white=None) -> np.ndarray:
|
|
73
|
+
"""
|
|
74
|
+
Convert Lab to RGB. Inverse of ``_rgb_to_lab``.
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
lab_nhwc: Lab image(s). Shape (N, H, W, 3) or (H, W, 3).
|
|
78
|
+
xp: array backend module (numpy or cupy).
|
|
79
|
+
clip: if True, clamp output to [0, 1]; else out-of-gamut values are preserved.
|
|
80
|
+
white: optional pre-allocated (1, 3, 1, 1) D65 white point on the backend.
|
|
81
|
+
|
|
82
|
+
Returns:
|
|
83
|
+
RGB image with same layout as input, float32 in [0, 1] (when ``clip=True``).
|
|
84
|
+
"""
|
|
85
|
+
if lab_nhwc.ndim == 4:
|
|
86
|
+
# N, H, W, C = lab_nhwc.shape
|
|
87
|
+
lab_nchw = lab_nhwc.transpose(0, 3, 1, 2) # (N,3,H,W)
|
|
88
|
+
else:
|
|
89
|
+
lab_nchw = lab_nhwc.transpose(2, 0, 1)[None, ...]
|
|
90
|
+
# N = 1
|
|
91
|
+
|
|
92
|
+
L = lab_nchw[:, 0, :, :]
|
|
93
|
+
a = lab_nchw[:, 1, :, :]
|
|
94
|
+
b = lab_nchw[:, 2, :, :]
|
|
95
|
+
|
|
96
|
+
fy = (L + 16.0) / 116.0
|
|
97
|
+
fx = a / 500.0 + fy
|
|
98
|
+
fz = fy - b / 200.0
|
|
99
|
+
fz = xp.clip(fz, 0.0, None)
|
|
100
|
+
|
|
101
|
+
delta = 0.2068966
|
|
102
|
+
fx_ = xp.where(fx > delta, xp.power(fx, 3.0), (fx - 4.0 / 29.0) / 7.787)
|
|
103
|
+
fy_ = xp.where(fy > delta, xp.power(fy, 3.0), (fy - 4.0 / 29.0) / 7.787)
|
|
104
|
+
fz_ = xp.where(fz > delta, xp.power(fz, 3.0), (fz - 4.0 / 29.0) / 7.787)
|
|
105
|
+
|
|
106
|
+
xyz = xp.stack([fx_, fy_, fz_], axis=1) # (N,3,H,W)
|
|
107
|
+
|
|
108
|
+
# Denormalise for D65 white point
|
|
109
|
+
if white is None:
|
|
110
|
+
white = xp.array([0.95047, 1.0, 1.08883], dtype=xp.float32).reshape(1, 3, 1, 1)
|
|
111
|
+
xyz_im = xyz * white
|
|
112
|
+
|
|
113
|
+
x = xyz_im[:, 0, :, :]
|
|
114
|
+
y = xyz_im[:, 1, :, :]
|
|
115
|
+
z = xyz_im[:, 2, :, :]
|
|
116
|
+
|
|
117
|
+
# Direct linear formulas
|
|
118
|
+
r = 3.2404813432005266 * x + -1.5371515162713185 * y + -0.4985363261688878 * z
|
|
119
|
+
g = -0.9692549499965682 * x + 1.8759900014898907 * y + 0.0415559265582928 * z
|
|
120
|
+
b_lin = 0.0556466391351772 * x + -0.2040413383665112 * y + 1.0573110696453443 * z
|
|
121
|
+
lin_rgb = xp.stack([r, g, b_lin], axis=1) # (N,3,H,W)
|
|
122
|
+
|
|
123
|
+
# Linear RGB -> sRGB
|
|
124
|
+
thresh = 0.0031308
|
|
125
|
+
srgb_nchw = xp.where(
|
|
126
|
+
lin_rgb > thresh,
|
|
127
|
+
1.055 * xp.power(xp.clip(lin_rgb, thresh, None), 1/2.4) - 0.055,
|
|
128
|
+
12.92 * lin_rgb,
|
|
129
|
+
)
|
|
130
|
+
if clip:
|
|
131
|
+
srgb_nchw = xp.clip(srgb_nchw, 0.0, 1.0)
|
|
132
|
+
|
|
133
|
+
srgb_nhwc = srgb_nchw.transpose(0, 2, 3, 1)
|
|
134
|
+
if lab_nhwc.ndim == 3:
|
|
135
|
+
srgb_nhwc = srgb_nhwc[0]
|
|
136
|
+
return srgb_nhwc
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class ReinhardNormalizer(Stage):
|
|
140
|
+
"""
|
|
141
|
+
Per-patch Reinhard stain normalization in Lab space.
|
|
142
|
+
|
|
143
|
+
Each incoming patch is shifted and scaled in Lab so that its per-patch
|
|
144
|
+
(mean, std) matches a fixed target (lab_reference_mean, lab_reference_std).
|
|
145
|
+
Operates on NHWC uint8 batches and stays on the pipeline backend (NumPy/CuPy).
|
|
146
|
+
|
|
147
|
+
Reference stats define the target stain appearance and should be computed
|
|
148
|
+
from tissue-only patches. Including background biases L high and a/b
|
|
149
|
+
toward zero, which produces washed-out normalized output.
|
|
150
|
+
|
|
151
|
+
Example of computing reference stats from a list of tissue-only RGB tensors
|
|
152
|
+
of shape (3, H, W) with values in [0, 1]::
|
|
153
|
+
|
|
154
|
+
def compute_lab_mean_std(tissue_rgb: list[torch.Tensor]):
|
|
155
|
+
lab = torch.stack([rgb_to_lab(img) for img in tissue_rgb])
|
|
156
|
+
mean = lab.mean(dim=(0, 2, 3)).numpy().astype(np.float32)
|
|
157
|
+
std = lab.std(dim=(0, 2, 3)).numpy().astype(np.float32)
|
|
158
|
+
return mean, std
|
|
159
|
+
"""
|
|
160
|
+
|
|
161
|
+
def __init__(
|
|
162
|
+
self,
|
|
163
|
+
lab_reference_mean: Tuple[float, float, float] = (68.94, 29.76, -18.97),
|
|
164
|
+
lab_reference_std: Tuple[float, float, float] = (11.52, 13.42, 8.59),
|
|
165
|
+
apply_modified_reinhard: bool = False,
|
|
166
|
+
) -> None:
|
|
167
|
+
"""
|
|
168
|
+
Args:
|
|
169
|
+
lab_reference_mean: target Lab mean (L, a, b). L in [0, 100], a/b in
|
|
170
|
+
~[-128, 127]. Defaults are reasonable H&E values computed for kidney AUMC scans.
|
|
171
|
+
lab_reference_std: target Lab std (L, a, b).
|
|
172
|
+
apply_modified_reinhard: if True, scale L and shift a/b only when the
|
|
173
|
+
source patch is less saturated than the reference.
|
|
174
|
+
"""
|
|
175
|
+
self.lab_reference_mean = lab_reference_mean
|
|
176
|
+
self.lab_reference_std = lab_reference_std
|
|
177
|
+
self.apply_modified_reinhard = apply_modified_reinhard
|
|
178
|
+
|
|
179
|
+
self._xp: Any = None
|
|
180
|
+
self._ref_mean: Any = None
|
|
181
|
+
self._ref_std: Any = None
|
|
182
|
+
self._rgb2xyz: Any = None
|
|
183
|
+
self._white: Any = None
|
|
184
|
+
|
|
185
|
+
self.log.info(f"ReinhardNormalizer initialized (modified={apply_modified_reinhard})")
|
|
186
|
+
|
|
187
|
+
def validate(self) -> None:
|
|
188
|
+
self.ctx.require_key("use_gpu")
|
|
189
|
+
|
|
190
|
+
def __call__(self, it: Iterable[CollatedPatchBatch]) -> Iterable[CollatedPatchBatch]:
|
|
191
|
+
"""
|
|
192
|
+
Apply Reinhard normalization to each batch in the stream. Backend
|
|
193
|
+
constants are allocated lazily on the first batch.
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
it: stream of CollatedPatchBatch with NHWC uint8 patches.
|
|
197
|
+
|
|
198
|
+
Yields:
|
|
199
|
+
Same batches with ``batch.patches`` replaced by the normalized NHWC uint8 array.
|
|
200
|
+
"""
|
|
201
|
+
for batch in it:
|
|
202
|
+
if self._xp is None:
|
|
203
|
+
self._xp = get_xp_backend(self.ctx["use_gpu"])
|
|
204
|
+
self._ref_mean = self._xp.asarray(self.lab_reference_mean, dtype=self._xp.float32)
|
|
205
|
+
self._ref_std = self._xp.asarray(self.lab_reference_std, dtype=self._xp.float32)
|
|
206
|
+
self._rgb2xyz = self._xp.array(
|
|
207
|
+
[[0.412453, 0.357580, 0.180423],
|
|
208
|
+
[0.212671, 0.715160, 0.072169],
|
|
209
|
+
[0.019334, 0.119193, 0.950227]], dtype=self._xp.float32
|
|
210
|
+
)
|
|
211
|
+
self._white = self._xp.array(
|
|
212
|
+
[0.95047, 1.0, 1.08883], dtype=self._xp.float32
|
|
213
|
+
).reshape(1, 3, 1, 1)
|
|
214
|
+
|
|
215
|
+
patches = batch.patches # NHWC uint8
|
|
216
|
+
if patches.ndim != 4 or patches.shape[-1] != 3:
|
|
217
|
+
raise ValueError(f"Expected NHWC with 3 channels, got {patches.shape}")
|
|
218
|
+
if patches.dtype != self._xp.uint8:
|
|
219
|
+
patches = patches.astype(self._xp.uint8, copy=False)
|
|
220
|
+
|
|
221
|
+
# Convert to float [0,1] and keep NHWC
|
|
222
|
+
rgb_float = patches.astype(self._xp.float32) / 255.0 # (N, H, W, 3)
|
|
223
|
+
|
|
224
|
+
# Convert to Lab (NHWC)
|
|
225
|
+
lab = _rgb_to_lab(rgb_float, self._xp, rgb2xyz=self._rgb2xyz, white=self._white) # (N, H, W, 3)
|
|
226
|
+
|
|
227
|
+
# Compute per‑patch mean and std over spatial axes (H,W)
|
|
228
|
+
lab_flat = lab.reshape(len(lab), -1, 3)
|
|
229
|
+
mean_lab = lab_flat.mean(axis=1) # (N,3)
|
|
230
|
+
std_lab = lab_flat.std(axis=1, ddof=1) # (N,3)
|
|
231
|
+
|
|
232
|
+
if not self.apply_modified_reinhard:
|
|
233
|
+
# Standard Reinhard
|
|
234
|
+
lab_centered = lab - mean_lab[:, None, None, :]
|
|
235
|
+
lab_scaled = lab_centered / (std_lab[:, None, None, :] + 1e-8)
|
|
236
|
+
lab_transformed = (
|
|
237
|
+
lab_scaled * self._ref_std[None, None, None, :]
|
|
238
|
+
+ self._ref_mean[None, None, None, :]
|
|
239
|
+
)
|
|
240
|
+
else:
|
|
241
|
+
# Modified Reinhard (uses ddof=1 std as well)
|
|
242
|
+
q = (self._ref_std[0] - std_lab[:, 0]) / (self._ref_std[0] + 1e-8)
|
|
243
|
+
q_mul = self._xp.where(q > 0, 1.0 + q, 1.05) # (N,)
|
|
244
|
+
|
|
245
|
+
L_new = (
|
|
246
|
+
(lab[..., 0] - mean_lab[:, 0][:, None, None]) * q_mul[:, None, None]
|
|
247
|
+
+ mean_lab[:, 0][:, None, None]
|
|
248
|
+
)
|
|
249
|
+
a_new = lab[..., 1].copy()
|
|
250
|
+
b_new = lab[..., 2].copy()
|
|
251
|
+
|
|
252
|
+
mask = q <= 0
|
|
253
|
+
if self._xp.any(mask):
|
|
254
|
+
a_new[mask] = (
|
|
255
|
+
lab[mask, ..., 1] - mean_lab[mask, 1][:, None, None]
|
|
256
|
+
) + self._ref_mean[1]
|
|
257
|
+
b_new[mask] = (
|
|
258
|
+
lab[mask, ..., 2] - mean_lab[mask, 2][:, None, None]
|
|
259
|
+
) + self._ref_mean[2]
|
|
260
|
+
|
|
261
|
+
lab_transformed = self._xp.stack([L_new, a_new, b_new], axis=-1)
|
|
262
|
+
|
|
263
|
+
# Convert back to RGB (NHWC)
|
|
264
|
+
rgb_norm_float = _lab_to_rgb(lab_transformed, self._xp, clip=True, white=self._white)
|
|
265
|
+
|
|
266
|
+
# Back to uint8
|
|
267
|
+
rgb_norm_uint8 = self._xp.round(rgb_norm_float * 255.0).astype(self._xp.uint8)
|
|
268
|
+
batch.patches = rgb_norm_uint8
|
|
269
|
+
|
|
270
|
+
self.log.debug(f"Normalized batch for wsi='{batch.wsi_id}' size={len(batch)}")
|
|
271
|
+
yield batch
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import sys
|
|
3
|
+
from typing import Literal, Union
|
|
4
|
+
|
|
5
|
+
LogLevel = Union[int, Literal["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET"]]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def init_logging(verbosity_level: LogLevel) -> None:
|
|
9
|
+
logging.basicConfig(
|
|
10
|
+
level=verbosity_level,
|
|
11
|
+
format="[%(asctime)s] [%(levelname)s] [%(processName)s] [%(name)s] %(message)s",
|
|
12
|
+
handlers=[logging.StreamHandler(sys.stdout)],
|
|
13
|
+
)
|