stainnormprogram 1.0.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.
- stainnormprogram/__about__.py +1 -0
- stainnormprogram/__init__.py +2 -0
- stainnormprogram/assessment/__init__.py +1 -0
- stainnormprogram/assessment/assessment.py +1186 -0
- stainnormprogram/assessment/background.py +211 -0
- stainnormprogram/assessment/color.py +770 -0
- stainnormprogram/assessment/contrast.py +252 -0
- stainnormprogram/assessment/gamut.py +407 -0
- stainnormprogram/assessment/palette.py +648 -0
- stainnormprogram/assessment/plot.py +759 -0
- stainnormprogram/assessment/structure.py +158 -0
- stainnormprogram/correction/__init__.py +1 -0
- stainnormprogram/correction/macenko.py +469 -0
- stainnormprogram/io/__init__.py +0 -0
- stainnormprogram/io/write_slide.py +119 -0
- stainnormprogram/library/TCGA-Manifest.txt +31 -0
- stainnormprogram/library/TCIA-Instructions.md +15 -0
- stainnormprogram/library/library.md +14 -0
- stainnormprogram/norm/__init__.py +1 -0
- stainnormprogram/norm/adjustments.py +88 -0
- stainnormprogram/norm/background.py +273 -0
- stainnormprogram/norm/normalization.py +126 -0
- stainnormprogram/norm/pipeline/__init__.py +0 -0
- stainnormprogram/norm/pipeline/macenko.py +302 -0
- stainnormprogram/norm/pipeline/pipeline.py +61 -0
- stainnormprogram/norm/style_estimation/__init__.py +0 -0
- stainnormprogram/norm/style_estimation/macenko.py +649 -0
- stainnormprogram/norm/subset.py +127 -0
- stainnormprogram/norm/translation/__init__.py +0 -0
- stainnormprogram/norm/translation/macenko.py +92 -0
- stainnormprogram/norm/utils.py +96 -0
- stainnormprogram/slide.py +1085 -0
- stainnormprogram-1.0.0.dist-info/METADATA +75 -0
- stainnormprogram-1.0.0.dist-info/RECORD +36 -0
- stainnormprogram-1.0.0.dist-info/WHEEL +4 -0
- stainnormprogram-1.0.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
from stainnormprogram.slide import SlideImage, SlideImageCollection
|
|
2
|
+
import stainnormprogram.norm.background as background
|
|
3
|
+
|
|
4
|
+
import statistics
|
|
5
|
+
import os
|
|
6
|
+
import json
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
class StructurePreservation:
|
|
11
|
+
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
reference: SlideImage | SlideImageCollection,
|
|
15
|
+
query: SlideImage | SlideImageCollection,
|
|
16
|
+
tile_size: int = 256,
|
|
17
|
+
background_method: str = "hsv_threshold",
|
|
18
|
+
accept_perc: int = 10,
|
|
19
|
+
max_pixels: int = 10_000_000
|
|
20
|
+
):
|
|
21
|
+
"""Assess the structure preservation between the original and stain normalized versions of an image.
|
|
22
|
+
|
|
23
|
+
Structure preservation is defined here as the preservation of edges as identified by Canny edge detection.
|
|
24
|
+
|
|
25
|
+
Options for ``background_method``:
|
|
26
|
+
* "hsv_threshold": Threshold using saturation and value channels in HSV color space.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
reference: The reference image.
|
|
30
|
+
query: The query image.
|
|
31
|
+
tile_size: Tile size to use.
|
|
32
|
+
background_method: Method for identifying the background/foreground.
|
|
33
|
+
accept_perc: Tiles with less than accept_perc percent of foreground are not used in the computation.
|
|
34
|
+
max_pixels: If the number of pixels used goes over max_pixels, stop the computation.
|
|
35
|
+
"""
|
|
36
|
+
self.reference = reference
|
|
37
|
+
self.query = query
|
|
38
|
+
self.background_method = background_method
|
|
39
|
+
self.accept_perc = accept_perc
|
|
40
|
+
|
|
41
|
+
# Tile size
|
|
42
|
+
if reference is not None:
|
|
43
|
+
self.reference.set_tile_size(tile_size)
|
|
44
|
+
if query is not None:
|
|
45
|
+
self.query.set_tile_size(tile_size)
|
|
46
|
+
|
|
47
|
+
self.num_pixels = 0
|
|
48
|
+
self.num_tiles = 0
|
|
49
|
+
self.max_pixels = max_pixels
|
|
50
|
+
self.tile_size = tile_size
|
|
51
|
+
|
|
52
|
+
self.diffs = []
|
|
53
|
+
self.diff_mean = None
|
|
54
|
+
self.diff_std = None
|
|
55
|
+
|
|
56
|
+
def save(self, output_dir: str):
|
|
57
|
+
"""Save metric to disk.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
output_dir: Folder path to output the metric to.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
json_output_path = os.path.join(output_dir, "structure_preservation.json")
|
|
64
|
+
with open(json_output_path, "w") as file:
|
|
65
|
+
json.dump({
|
|
66
|
+
"reference": self.reference.identifier,
|
|
67
|
+
"query": self.query.identifier,
|
|
68
|
+
"background_method": self.background_method,
|
|
69
|
+
"accept_perc": self.accept_perc,
|
|
70
|
+
"num_pixels": self.num_pixels,
|
|
71
|
+
"num_tiles": self.num_tiles,
|
|
72
|
+
"max_pixels": self.max_pixels,
|
|
73
|
+
"tile_size": self.tile_size,
|
|
74
|
+
"diff_mean": self.diff_mean,
|
|
75
|
+
"diff_std": self.diff_std,
|
|
76
|
+
}, file)
|
|
77
|
+
|
|
78
|
+
structure_output_path = os.path.join(output_dir, "structure_preservation_diffs.npz")
|
|
79
|
+
np.savez(structure_output_path, diffs=self.diffs, allow_pickle=False)
|
|
80
|
+
|
|
81
|
+
@classmethod
|
|
82
|
+
def load(cls, input_dir: str) -> StructurePreservation:
|
|
83
|
+
"""Load metric from disk.
|
|
84
|
+
|
|
85
|
+
Args:
|
|
86
|
+
input_dir: Folder path to load the metric from.
|
|
87
|
+
|
|
88
|
+
Returns:
|
|
89
|
+
A StructurePreservation.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
json_input_path = os.path.join(input_dir, "structure_preservation.json")
|
|
93
|
+
with open(json_input_path, "r") as file:
|
|
94
|
+
json_data = json.load(file)
|
|
95
|
+
|
|
96
|
+
sp = cls(json_data["reference"], json_data["query"], json_data["tile_size"], json_data["background_method"], json_data["accept_perc"], json_data["max_pixels"])
|
|
97
|
+
|
|
98
|
+
structure_input_path = os.path.join(input_dir, "structure_preservation_diffs.npz")
|
|
99
|
+
with np.load(structure_input_path, allow_pickle=False) as data:
|
|
100
|
+
sp.diffs = data["diffs"]
|
|
101
|
+
|
|
102
|
+
return sp
|
|
103
|
+
|
|
104
|
+
def compute_tile(self, ref_tile: Tile, q_tile: Tile):
|
|
105
|
+
"""Compute the structure preservation between two tiles.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
ref_tile: The reference tile.
|
|
109
|
+
q_tile: The query tile.
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
if self.background_method == "hsv_threshold":
|
|
113
|
+
fg_mask = background.hsv_threshold_foreground(ref_tile).flatten()
|
|
114
|
+
else:
|
|
115
|
+
raise Exception
|
|
116
|
+
|
|
117
|
+
n = np.sum(fg_mask).item()
|
|
118
|
+
if n / fg_mask.size * 100 < self.accept_perc:
|
|
119
|
+
return None
|
|
120
|
+
|
|
121
|
+
ref_canny = ref_tile.canny()
|
|
122
|
+
q_canny = q_tile.canny()
|
|
123
|
+
|
|
124
|
+
diff_mask = ref_canny ^ q_canny
|
|
125
|
+
diff_count = np.sum(diff_mask).item()
|
|
126
|
+
|
|
127
|
+
self.num_tiles = self.num_tiles + 1
|
|
128
|
+
self.num_pixels = self.num_pixels + n
|
|
129
|
+
|
|
130
|
+
self.diffs.append(diff_count)
|
|
131
|
+
|
|
132
|
+
def get_val(self) -> tuple[float, float]:
|
|
133
|
+
"""Get the value of the metric.
|
|
134
|
+
|
|
135
|
+
Returns:
|
|
136
|
+
A tuple containing (difference mean, difference standard deviation).
|
|
137
|
+
"""
|
|
138
|
+
return (self.diff_mean, self.diff_std)
|
|
139
|
+
|
|
140
|
+
def compute(self):
|
|
141
|
+
"""Compute the StructurePreservation.
|
|
142
|
+
"""
|
|
143
|
+
|
|
144
|
+
print(f"Computing Structure between {self.reference.identifier} and {self.query.identifier}...")
|
|
145
|
+
|
|
146
|
+
self.reference.set_mode("random")
|
|
147
|
+
for ref_tile, metadata in self.reference:
|
|
148
|
+
q_tile = self.query.get_tile_using_dict(metadata)
|
|
149
|
+
self.compute_tile(ref_tile, q_tile)
|
|
150
|
+
if self.num_pixels > self.max_pixels:
|
|
151
|
+
break
|
|
152
|
+
|
|
153
|
+
self.diff_mean = statistics.mean(self.diffs)
|
|
154
|
+
self.diff_std = statistics.stdev(self.diffs)
|
|
155
|
+
|
|
156
|
+
print("Finished computing Structure")
|
|
157
|
+
print(f"Tiles used = {self.num_tiles}")
|
|
158
|
+
print(f"Foreground pixels used = {self.num_pixels}")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .macenko import MacenkoPointCorrection
|
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
from stainnormprogram.slide import SlideImage
|
|
2
|
+
from stainnormprogram.norm.utils import nnls
|
|
3
|
+
from stainnormprogram.norm.adjustments import Adjustment
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
import plotly
|
|
9
|
+
import plotly.express as px
|
|
10
|
+
import plotly.graph_objects as go
|
|
11
|
+
from plotly.subplots import make_subplots
|
|
12
|
+
import numpy as np
|
|
13
|
+
from scipy.optimize import least_squares
|
|
14
|
+
|
|
15
|
+
class MacenkoPointCorrection:
|
|
16
|
+
|
|
17
|
+
def __init__(self):
|
|
18
|
+
"""Perform correction by selecting corresponding points between a properly normalized image and a failure case.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
self.f = None
|
|
22
|
+
|
|
23
|
+
# New matrix and maxC after correction
|
|
24
|
+
self.matrix_new = None
|
|
25
|
+
self.maxC_new = None
|
|
26
|
+
|
|
27
|
+
# Save locations
|
|
28
|
+
self.ref_y = None
|
|
29
|
+
self.ref_x = None
|
|
30
|
+
self.query_y = None
|
|
31
|
+
self.query_x = None
|
|
32
|
+
self.tile_size = None
|
|
33
|
+
|
|
34
|
+
self.before_ref_slide = None
|
|
35
|
+
self.after_ref_slide = None
|
|
36
|
+
self.ref_matrix = None
|
|
37
|
+
self.ref_maxC = None
|
|
38
|
+
self.ref_I0 = None
|
|
39
|
+
self.ref_pre_adjust = None
|
|
40
|
+
self.before_query_slide = None
|
|
41
|
+
self.after_query_slide = None
|
|
42
|
+
self.query_matrix = None
|
|
43
|
+
self.query_maxC = None
|
|
44
|
+
self.query_I0 = None
|
|
45
|
+
self.query_pre_adjust = None
|
|
46
|
+
self.query_post_adjust = None
|
|
47
|
+
self.target_matrix = None
|
|
48
|
+
self.target_maxC = None
|
|
49
|
+
self.target_I0 = None
|
|
50
|
+
|
|
51
|
+
print("""
|
|
52
|
+
DIRECTIONS:
|
|
53
|
+
|
|
54
|
+
First, call all relevant functions to set variables up properly.
|
|
55
|
+
* set_reference
|
|
56
|
+
* set_query
|
|
57
|
+
* set_styles
|
|
58
|
+
|
|
59
|
+
When ready to select points, call make_selection.
|
|
60
|
+
|
|
61
|
+
Pick a point on the reference, then a point on the query, and repeat until you have >= 10 pairs (20 is recommended).
|
|
62
|
+
For each pair, you should pick corresponding points (e.g., darkest part of a nucleus in the reference with darkest part of a nucleus in the query).
|
|
63
|
+
Among all of the pairs, vary the feature selected (e.g. for one pair you can do darkest parts of nuclei, for another pair you can do lightest parts of stroma).
|
|
64
|
+
|
|
65
|
+
Then, compute the correction using the compute function.
|
|
66
|
+
|
|
67
|
+
Finally, once computation is done, you can view the results using display_results and save using save_corrected_style.
|
|
68
|
+
""")
|
|
69
|
+
|
|
70
|
+
def __repr__(self):
|
|
71
|
+
return f"MacenkoPointCorrection(\n \
|
|
72
|
+
before_ref_slide={self.before_ref_slide}\n \
|
|
73
|
+
after_ref_slide={self.after_ref_slide}\n \
|
|
74
|
+
ref_matrix={self.ref_matrix}\n \
|
|
75
|
+
ref_maxC={self.ref_maxC}\n \
|
|
76
|
+
ref_I0={self.ref_I0}\n\n \
|
|
77
|
+
ref_pre_adjust={self.ref_pre_adjust}\n\n\
|
|
78
|
+
before_query_slide={self.before_query_slide}\n \
|
|
79
|
+
after_query_slide={self.after_query_slide}\n \
|
|
80
|
+
query_matrix={self.query_matrix}\n \
|
|
81
|
+
query_maxC={self.query_maxC}\n \
|
|
82
|
+
query_I0={self.query_I0}\n \
|
|
83
|
+
query_pre_adjust={self.query_pre_adjust}\n \
|
|
84
|
+
query_post_adjust={self.query_post_adjust}\n\n \
|
|
85
|
+
target_matrix={self.target_matrix}\n \
|
|
86
|
+
target_maxC={self.target_maxC}\n \
|
|
87
|
+
target_I0={self.target_I0}\n)"
|
|
88
|
+
|
|
89
|
+
def save_corrected_style(self, output_path: str):
|
|
90
|
+
"""Save the corrected source stain style.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
output_path: File path to output the corrected staining style to. Should end with .json.
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
if os.path.exists(output_path):
|
|
97
|
+
raise Exception("File already exists. Choose a different output_path.")
|
|
98
|
+
|
|
99
|
+
if self.matrix_new is None or self.maxC_new is None:
|
|
100
|
+
raise Exception("Run correction first.")
|
|
101
|
+
|
|
102
|
+
output_dict = {
|
|
103
|
+
"matrix": self.matrix_new.tolist(),
|
|
104
|
+
"maxC": self.maxC_new.tolist(),
|
|
105
|
+
"I0": self.query_I0.tolist(),
|
|
106
|
+
"correction": "MacenkoPointCorrection",
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
with open(output_path, "w") as file:
|
|
110
|
+
json.dump(output_dict, file, indent=4)
|
|
111
|
+
|
|
112
|
+
def set_reference(self, before_ref_slide: str | SlideImage, after_ref_slide: str | SlideImage, pre_adjustment: Adjustment | None = None):
|
|
113
|
+
"""Set the reference slide (a slide that was normalized well).
|
|
114
|
+
|
|
115
|
+
Args:
|
|
116
|
+
before_ref_slide: Either a SlideImage or str path to the image before normalization (the original).
|
|
117
|
+
after_ref_slide: Either a SlideImage or str path to the image after normalization.
|
|
118
|
+
pre_adjustment: Pre-adjustment to apply. This should be the same pre-adjustment used when you stain normalized the reference.
|
|
119
|
+
"""
|
|
120
|
+
if isinstance(before_ref_slide, SlideImage):
|
|
121
|
+
self.before_ref_slide = before_ref_slide
|
|
122
|
+
else:
|
|
123
|
+
self.before_ref_slide = SlideImage(before_ref_slide)
|
|
124
|
+
if isinstance(after_ref_slide, SlideImage):
|
|
125
|
+
self.after_ref_slide = after_ref_slide
|
|
126
|
+
else:
|
|
127
|
+
self.after_ref_slide = SlideImage(after_ref_slide)
|
|
128
|
+
|
|
129
|
+
self.before_ref_slide.set_adjustment(pre_adjustment)
|
|
130
|
+
self.after_ref_slide.set_adjustment(None)
|
|
131
|
+
|
|
132
|
+
self.ref_pre_adjust = pre_adjustment
|
|
133
|
+
|
|
134
|
+
def set_query(self, before_query_slide: str | SlideImage, after_query_slide: str | SlideImage, pre_adjustment: Adjustment | None = None, post_adjustment: Adjustment | None = None):
|
|
135
|
+
"""Set the query slide (a slide that was not normalized well).
|
|
136
|
+
|
|
137
|
+
When setting ``pre_adjustment`` and ``post_adjustment``, note that you should use these exact Adjustments when performing stain normalization after correction to ensure
|
|
138
|
+
the results you see during correction match those when normalizing the entire image. Also note that ``post_adjustment`` should be the same as the post-adjustment that was used
|
|
139
|
+
on the normalized reference.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
before_query_slide: Either a SlideImage or str path to the image before normalization (the original).
|
|
143
|
+
after_query_slide: Either a SlideImage or str path to the image after normalization.
|
|
144
|
+
pre_adjustment: Pre-adjustment to apply.
|
|
145
|
+
post_adjustment: Post-adjustment to apply.
|
|
146
|
+
"""
|
|
147
|
+
if isinstance(before_query_slide, SlideImage):
|
|
148
|
+
self.before_query_slide = before_query_slide
|
|
149
|
+
else:
|
|
150
|
+
self.before_query_slide = SlideImage(before_query_slide)
|
|
151
|
+
if isinstance(after_query_slide, SlideImage):
|
|
152
|
+
self.after_query_slide = after_query_slide
|
|
153
|
+
else:
|
|
154
|
+
self.after_query_slide = SlideImage(after_query_slide)
|
|
155
|
+
|
|
156
|
+
self.before_query_slide.set_adjustment(pre_adjustment)
|
|
157
|
+
self.after_query_slide.set_adjustment(None)
|
|
158
|
+
|
|
159
|
+
self.query_pre_adjust = pre_adjustment
|
|
160
|
+
self.query_post_adjust = post_adjustment
|
|
161
|
+
|
|
162
|
+
def load_style(self, path: str, separate: bool = False) -> dict[str, np.ndarray] | tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
163
|
+
"""Helper function for loading stain style JSONs.
|
|
164
|
+
|
|
165
|
+
Args:
|
|
166
|
+
path: Path to the JSON file.
|
|
167
|
+
separate: If True, will return a tuple of matrix, maxC, and I0 instead of a dictionary.
|
|
168
|
+
|
|
169
|
+
Returns:
|
|
170
|
+
Either a tuple or dictionary of the matrix, maxC, and I0.
|
|
171
|
+
"""
|
|
172
|
+
with open(path, "r") as file:
|
|
173
|
+
style = json.load(file)
|
|
174
|
+
style["matrix"] = np.array(style["matrix"])
|
|
175
|
+
style["maxC"] = np.array(style["maxC"])
|
|
176
|
+
style["I0"] = np.array(style["I0"])
|
|
177
|
+
if not separate:
|
|
178
|
+
return style
|
|
179
|
+
return style["matrix"], style["maxC"], style["I0"]
|
|
180
|
+
|
|
181
|
+
def set_styles(self, ref_style, query_style, target_style):
|
|
182
|
+
"""Set stain styles.
|
|
183
|
+
|
|
184
|
+
Args:
|
|
185
|
+
ref_style: Path to the reference image stain style JSON.
|
|
186
|
+
query_style: Path to the query image stain style JSON.
|
|
187
|
+
target_style: Path to the target stain style JSON.
|
|
188
|
+
"""
|
|
189
|
+
if isinstance(ref_style, str) and ref_style.endswith(".json"):
|
|
190
|
+
self.ref_matrix, self.ref_maxC, self.ref_I0 = self.load_style(ref_style, separate=True)
|
|
191
|
+
if isinstance(query_style, str) and query_style.endswith(".json"):
|
|
192
|
+
self.query_matrix, self.query_maxC, self.query_I0 = self.load_style(query_style, separate=True)
|
|
193
|
+
if isinstance(target_style, str) and target_style.endswith(".json"):
|
|
194
|
+
self.target_matrix, self.target_maxC, self.target_I0 = self.load_style(target_style, separate=True)
|
|
195
|
+
|
|
196
|
+
def make_selection(self, ref_y: int, ref_x: int, query_y: int, query_x: int, tile_size: int) -> plotly.graph_objects.Figure:
|
|
197
|
+
"""Make point selections.
|
|
198
|
+
|
|
199
|
+
Args:
|
|
200
|
+
ref_y: Upper left corner y-coordinate for the region of interest in the reference to show.
|
|
201
|
+
ref_x: Upper left corner x-coordinate for the region of interest in the reference to show.
|
|
202
|
+
query_y: Upper left corner y-coordinate for the region of interest in the query to show.
|
|
203
|
+
query_x: Upper left corner x-coordinate for the region of interest in the query to show.
|
|
204
|
+
tile_size: Pixel size of the regions of interest.
|
|
205
|
+
|
|
206
|
+
Returns:
|
|
207
|
+
A Plotly figure for making the point selection.
|
|
208
|
+
"""
|
|
209
|
+
self.ref_y = ref_y
|
|
210
|
+
self.ref_x = ref_x
|
|
211
|
+
self.query_y = query_y
|
|
212
|
+
self.query_x = query_x
|
|
213
|
+
self.tile_size = tile_size
|
|
214
|
+
|
|
215
|
+
if self.f is None:
|
|
216
|
+
return self.setup_fig(ref_y, ref_x, query_y, query_x, tile_size)
|
|
217
|
+
|
|
218
|
+
else:
|
|
219
|
+
self.clicked_ref = self.f.data[0].customdata[1]
|
|
220
|
+
self.clicked_query = self.f.data[1].customdata[1]
|
|
221
|
+
return self.setup_fig(ref_y, ref_x, query_y, query_x, tile_size, clicked_ref=self.clicked_ref, clicked_query=self.clicked_query)
|
|
222
|
+
|
|
223
|
+
def setup_fig(self, ref_y: int, ref_x: int, query_y: int, query_x: int, tile_size: int, clicked_ref: list[tuple[int, int]] = [], clicked_query: list[tuple[int, int]] = []) -> plotly.graph_objects.Figure:
|
|
224
|
+
"""Setup the Plotly point selection figure.
|
|
225
|
+
|
|
226
|
+
Args:
|
|
227
|
+
ref_y: Upper left corner y-coordinate for the region of interest in the reference to show.
|
|
228
|
+
ref_x: Upper left corner x-coordinate for the region of interest in the reference to show.
|
|
229
|
+
query_y: Upper left corner y-coordinate for the region of interest in the query to show.
|
|
230
|
+
query_x: Upper left corner x-coordinate for the region of interest in the query to show.
|
|
231
|
+
tile_size: Pixel size of the regions of interest.
|
|
232
|
+
clicked_ref: Clicked reference points (if resuming).
|
|
233
|
+
clicked_query: Clicked query points (if resuming).
|
|
234
|
+
|
|
235
|
+
Returns:
|
|
236
|
+
A Plotly figure for making the point selection.
|
|
237
|
+
"""
|
|
238
|
+
|
|
239
|
+
# Load in ref tile
|
|
240
|
+
ref_tile = self.after_ref_slide.get_tile(ref_y, ref_x, tile_size, tile_size)
|
|
241
|
+
|
|
242
|
+
# Load in query tile
|
|
243
|
+
query_tile = self.after_query_slide.get_tile(query_y, query_x, tile_size, tile_size)
|
|
244
|
+
|
|
245
|
+
# Show both in an interactive plot
|
|
246
|
+
fig = make_subplots(rows=1, cols=2, subplot_titles=("Reference", "Query"))
|
|
247
|
+
|
|
248
|
+
fig.add_trace(
|
|
249
|
+
go.Image(z=ref_tile.rgb(as_uint8=True), x0=ref_x, y0=ref_y, customdata=["Reference", clicked_ref]), row=1, col=1
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
fig.add_trace(
|
|
253
|
+
go.Image(z=query_tile.rgb(as_uint8=True), x0=query_x, y0=query_y, customdata=["Query", clicked_query]), row=1, col=2
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
fig.update_layout(title=f"Select correspondences in the Reference and Query images",
|
|
257
|
+
height=600,
|
|
258
|
+
width=1200,
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
f = go.FigureWidget(fig)
|
|
262
|
+
|
|
263
|
+
def callback(trace, points, selector):
|
|
264
|
+
|
|
265
|
+
if points.point_inds:
|
|
266
|
+
|
|
267
|
+
x = points.xs[0]
|
|
268
|
+
y = points.ys[0]
|
|
269
|
+
|
|
270
|
+
if trace.customdata[0] == "Reference":
|
|
271
|
+
trace.customdata[1].append((x,y))
|
|
272
|
+
f.layout.title.subtitle.text = f"Selected (x={x}, y={y}) on Reference"
|
|
273
|
+
elif trace.customdata[0] == "Query":
|
|
274
|
+
trace.customdata[1].append((x,y))
|
|
275
|
+
f.layout.title.subtitle.text = f"Selected (x={x}, y={y}) on Query"
|
|
276
|
+
|
|
277
|
+
f.data[0].on_click(callback)
|
|
278
|
+
f.data[1].on_click(callback)
|
|
279
|
+
|
|
280
|
+
self.f = f
|
|
281
|
+
|
|
282
|
+
return self.f
|
|
283
|
+
|
|
284
|
+
def clear_selection(self):
|
|
285
|
+
"""Clear the selection. To select again, call make_selection.
|
|
286
|
+
"""
|
|
287
|
+
self.f = None
|
|
288
|
+
|
|
289
|
+
def compute(self, c_ref: list[tuple[int]] | None = None, c_query: list[tuple[int]] | None = None, lam: float = 0.0):
|
|
290
|
+
"""Compute the correction from the selected points.
|
|
291
|
+
|
|
292
|
+
Args:
|
|
293
|
+
c_ref: Selected coordinate points on the reference image. If not given, will take from the Plotly figure automatically.
|
|
294
|
+
c_query: Selected coordinate points on the query image. If not given, will take from the Plotly figure automatically.
|
|
295
|
+
lam: Lambda coefficient to control the influence of the past stain style calculation [0.0,1.0]. 0.0 is no influence from the past.
|
|
296
|
+
"""
|
|
297
|
+
# Given: a list of corresponding points (as pairs) in overall slide coordinates
|
|
298
|
+
if c_ref is None:
|
|
299
|
+
self.clicked_ref = self.f.data[0].customdata[1]
|
|
300
|
+
else:
|
|
301
|
+
self.clicked_ref = c_ref
|
|
302
|
+
if c_query is None:
|
|
303
|
+
self.clicked_query = self.f.data[1].customdata[1]
|
|
304
|
+
else:
|
|
305
|
+
self.clicked_query = c_query
|
|
306
|
+
|
|
307
|
+
print("Reference points:", self.clicked_ref)
|
|
308
|
+
print("Query points:", self.clicked_query)
|
|
309
|
+
|
|
310
|
+
if len(self.clicked_ref) != len(self.clicked_query):
|
|
311
|
+
raise Exception("You did not click the same number of points in the reference and query.")
|
|
312
|
+
if len(self.clicked_ref) < 10:
|
|
313
|
+
raise Exception("Pick more points. You have less than 10.")
|
|
314
|
+
print("Number of correspondences:", len(self.clicked_ref))
|
|
315
|
+
|
|
316
|
+
# Extract the Y values from those points before normalization
|
|
317
|
+
# Get Y values using I0 and pre_adjust
|
|
318
|
+
Y_ref = []
|
|
319
|
+
Y_query = []
|
|
320
|
+
for ref_point in self.clicked_ref:
|
|
321
|
+
Y = self.before_ref_slide.get_tile(ref_point[1], ref_point[0], 1, 1).od(self.ref_I0).squeeze()
|
|
322
|
+
Y_ref.append(Y)
|
|
323
|
+
for query_point in self.clicked_query:
|
|
324
|
+
Y = self.before_query_slide.get_tile(query_point[1], query_point[0], 1, 1).od(self.query_I0).squeeze()
|
|
325
|
+
Y_query.append(Y)
|
|
326
|
+
|
|
327
|
+
Y_ref = np.array(Y_ref).transpose()
|
|
328
|
+
Y_query = np.array(Y_query).transpose()
|
|
329
|
+
|
|
330
|
+
# Using the ref source style (vectors and maxC), calculate the C_desired values
|
|
331
|
+
C_ref = nnls(self.ref_matrix, Y_ref) # (2,N)
|
|
332
|
+
scaling_factor = np.divide(self.target_maxC, self.ref_maxC)[:, np.newaxis] # (2,1)
|
|
333
|
+
C_desired = C_ref * scaling_factor # (2,N)
|
|
334
|
+
|
|
335
|
+
# Divide C_desired by maxC of the target
|
|
336
|
+
C_A = C_desired / self.target_maxC[:, np.newaxis] # (2,N)
|
|
337
|
+
C_A = C_A.transpose() # (N,2)
|
|
338
|
+
|
|
339
|
+
# Calculate initial guesses
|
|
340
|
+
# Use the query source style (vectors and maxC)
|
|
341
|
+
X1_0 = self.query_matrix[0,0] * self.query_maxC[0]
|
|
342
|
+
X2_0 = self.query_matrix[1,0] * self.query_maxC[0]
|
|
343
|
+
X3_0 = self.query_matrix[2,0] * self.query_maxC[0]
|
|
344
|
+
Y1_0 = self.query_matrix[0,1] * self.query_maxC[1]
|
|
345
|
+
Y2_0 = self.query_matrix[1,1] * self.query_maxC[1]
|
|
346
|
+
Y3_0 = self.query_matrix[2,1] * self.query_maxC[1]
|
|
347
|
+
|
|
348
|
+
eq1_0 = np.array([X1_0, Y1_0]) # (2,)
|
|
349
|
+
eq2_0 = np.array([X2_0, Y2_0])
|
|
350
|
+
eq3_0 = np.array([X3_0, Y3_0])
|
|
351
|
+
|
|
352
|
+
Y_query = Y_query.transpose() # (N,3)
|
|
353
|
+
y1 = Y_query[:,0] # (N,)
|
|
354
|
+
y2 = Y_query[:,1]
|
|
355
|
+
y3 = Y_query[:,2]
|
|
356
|
+
|
|
357
|
+
# Perform least squares estimate with initial estimate
|
|
358
|
+
def lstsq_fn(x, A, y, x0, lam):
|
|
359
|
+
residual = A @ x - y
|
|
360
|
+
regularized = np.sqrt(lam) * (x - x0)
|
|
361
|
+
return np.concatenate([residual, regularized])
|
|
362
|
+
|
|
363
|
+
eq1 = least_squares(lstsq_fn, eq1_0, args=(C_A, y1, eq1_0, lam))
|
|
364
|
+
eq2 = least_squares(lstsq_fn, eq2_0, args=(C_A, y2, eq2_0, lam))
|
|
365
|
+
eq3 = least_squares(lstsq_fn, eq3_0, args=(C_A, y3, eq3_0, lam))
|
|
366
|
+
|
|
367
|
+
X1 = eq1.x[0]
|
|
368
|
+
X2 = eq2.x[0]
|
|
369
|
+
X3 = eq3.x[0]
|
|
370
|
+
Y1 = eq1.x[1]
|
|
371
|
+
Y2 = eq2.x[1]
|
|
372
|
+
Y3 = eq3.x[1]
|
|
373
|
+
|
|
374
|
+
H_scaled = np.array([X1, X2, X3])
|
|
375
|
+
E_scaled = np.array([Y1, Y2, Y3])
|
|
376
|
+
|
|
377
|
+
# Compute the magnitudes of the estimates
|
|
378
|
+
maxC_H_new = np.linalg.norm(H_scaled, ord=2)
|
|
379
|
+
maxC_E_new = np.linalg.norm(E_scaled, ord=2)
|
|
380
|
+
|
|
381
|
+
H = H_scaled / maxC_H_new
|
|
382
|
+
E = E_scaled / maxC_E_new
|
|
383
|
+
|
|
384
|
+
# Store new stain matrix and maxC values
|
|
385
|
+
self.matrix_new = np.array([H, E]).transpose() # (3,2)
|
|
386
|
+
self.maxC_new = np.array([maxC_H_new, maxC_E_new]) # (2,)
|
|
387
|
+
|
|
388
|
+
print("New query source matrix:")
|
|
389
|
+
print(self.matrix_new)
|
|
390
|
+
print("New query source maxC:")
|
|
391
|
+
print(self.maxC_new)
|
|
392
|
+
print("Cost values:", eq1.cost, eq2.cost, eq3.cost)
|
|
393
|
+
|
|
394
|
+
def display_results(self, ref_y: int = None, ref_x: int = None, query_y: int = None, query_x: int = None, tile_size: int = None) -> plotly.graph_objects.Figure:
|
|
395
|
+
"""Display results of the correction.
|
|
396
|
+
|
|
397
|
+
Args:
|
|
398
|
+
ref_y: Upper left corner y-coordinate for the region of interest in the reference to show.
|
|
399
|
+
ref_x: Upper left corner x-coordinate for the region of interest in the reference to show.
|
|
400
|
+
query_y: Upper left corner y-coordinate for the region of interest in the query to show.
|
|
401
|
+
query_x: Upper left corner x-coordinate for the region of interest in the query to show.
|
|
402
|
+
tile_size: Pixel size of the regions of interest.
|
|
403
|
+
|
|
404
|
+
Returns:
|
|
405
|
+
A Plotly figure showing the results of correction.
|
|
406
|
+
"""
|
|
407
|
+
if ref_y is None:
|
|
408
|
+
ref_y = self.ref_y
|
|
409
|
+
if ref_x is None:
|
|
410
|
+
ref_x = self.ref_x
|
|
411
|
+
if query_y is None:
|
|
412
|
+
query_y = self.query_y
|
|
413
|
+
if query_x is None:
|
|
414
|
+
query_x = self.query_x
|
|
415
|
+
if tile_size is None:
|
|
416
|
+
tile_size = self.tile_size
|
|
417
|
+
if self.matrix_new is None or self.maxC_new is None:
|
|
418
|
+
raise Exception("Call compute first.")
|
|
419
|
+
|
|
420
|
+
# Find original Y values of the tile
|
|
421
|
+
query_tile_od = self.before_query_slide.get_tile(query_y, query_x, tile_size, tile_size).od(self.query_I0)
|
|
422
|
+
h, w, _ = query_tile_od.shape
|
|
423
|
+
|
|
424
|
+
# Perform stain normalization using those values
|
|
425
|
+
query_tile_od = query_tile_od.reshape(-1,3).transpose() # (3,N)
|
|
426
|
+
|
|
427
|
+
C = nnls(self.matrix_new, query_tile_od)
|
|
428
|
+
|
|
429
|
+
scaling_factor = np.divide(self.target_maxC, self.maxC_new)[:, np.newaxis]
|
|
430
|
+
C2 = C * scaling_factor
|
|
431
|
+
|
|
432
|
+
Inorm = np.exp(-self.target_matrix.dot(C2))
|
|
433
|
+
if self.query_post_adjust is not None:
|
|
434
|
+
Inorm = self.query_post_adjust.apply(Inorm)
|
|
435
|
+
Inorm = Inorm * self.target_I0[:, np.newaxis]
|
|
436
|
+
Inorm = np.clip(Inorm, 0, 255).astype(np.uint8)
|
|
437
|
+
Inorm = np.reshape(Inorm.transpose(), (h, w, 3))
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
ref_tile = self.after_ref_slide.get_tile(ref_y, ref_x, tile_size, tile_size).rgb(as_uint8=True)
|
|
441
|
+
query_tile_norm = self.after_query_slide.get_tile(query_y, query_x, tile_size, tile_size).rgb(as_uint8=True)
|
|
442
|
+
query_tile_orig = self.before_query_slide.get_tile(query_y, query_x, tile_size, tile_size).rgb(as_uint8=True)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
fig = make_subplots(rows=1, cols=4, subplot_titles=("Reference Norm", "Query Corrected Norm", "Query Initial Norm", "Query Before Norm"))
|
|
446
|
+
|
|
447
|
+
fig.add_trace(
|
|
448
|
+
go.Image(z=ref_tile, x0=ref_x, y0=ref_y), row=1, col=1
|
|
449
|
+
)
|
|
450
|
+
|
|
451
|
+
fig.add_trace(
|
|
452
|
+
go.Image(z=Inorm, x0=query_x, y0=query_y), row=1, col=2
|
|
453
|
+
)
|
|
454
|
+
|
|
455
|
+
fig.add_trace(
|
|
456
|
+
go.Image(z=query_tile_norm, x0=query_x, y0=query_y), row=1, col=3
|
|
457
|
+
)
|
|
458
|
+
|
|
459
|
+
fig.add_trace(
|
|
460
|
+
go.Image(z=query_tile_orig, x0=query_x, y0=query_y), row=1, col=4
|
|
461
|
+
)
|
|
462
|
+
|
|
463
|
+
fig.update_layout(title=f"Correction results",
|
|
464
|
+
height=600,
|
|
465
|
+
width=1200,
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
return fig
|
|
469
|
+
|
|
File without changes
|