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,1186 @@
|
|
|
1
|
+
from stainnormprogram.slide import SlideImage, SlideImageCollection, is_valid_extension
|
|
2
|
+
|
|
3
|
+
from stainnormprogram.assessment.color import ColorSample, ColorDistribution, ColorComparison, ColorHistogramEdges
|
|
4
|
+
from stainnormprogram.assessment.palette import Palette, ReferencePalette, PaletteEvaluation, PaletteComparison
|
|
5
|
+
from stainnormprogram.assessment.structure import StructurePreservation
|
|
6
|
+
from stainnormprogram.assessment.contrast import Contrast, ContrastChange
|
|
7
|
+
from stainnormprogram.assessment.gamut import Gamut, ReferenceGamut, GamutComparison
|
|
8
|
+
from stainnormprogram.assessment.background import BackgroundEstimation, ReferenceBackground, BackgroundComparison
|
|
9
|
+
from stainnormprogram.assessment.plot import plot_labels, ScatterPlot, HistPlot
|
|
10
|
+
|
|
11
|
+
import pickle
|
|
12
|
+
import os
|
|
13
|
+
import csv
|
|
14
|
+
from typing import Any
|
|
15
|
+
import json
|
|
16
|
+
|
|
17
|
+
import plotly
|
|
18
|
+
|
|
19
|
+
class ReferenceSet:
|
|
20
|
+
def __init__(self, assessment_dir: str):
|
|
21
|
+
"""ReferenceSet keeps track of the assessment statistics computed on the reference.
|
|
22
|
+
|
|
23
|
+
The reference is what we compare each image to in the Assessment.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
assessment_dir: Path to the assessment directory.
|
|
27
|
+
"""
|
|
28
|
+
self.identifier = "reference"
|
|
29
|
+
|
|
30
|
+
self.assessment_dir = assessment_dir
|
|
31
|
+
self.reference_dir = os.path.join(self.assessment_dir, self.identifier)
|
|
32
|
+
os.makedirs(self.reference_dir, exist_ok=True)
|
|
33
|
+
|
|
34
|
+
def get_stat(self, stat_type: str, **kwargs) -> Any:
|
|
35
|
+
"""Get a particular statistic.
|
|
36
|
+
|
|
37
|
+
Options for ``stat_type``:
|
|
38
|
+
* ColorDistribution
|
|
39
|
+
* ColorComparison
|
|
40
|
+
* ReferenceBackground
|
|
41
|
+
* Contrast
|
|
42
|
+
* ReferenceGamut
|
|
43
|
+
* ReferencePalette
|
|
44
|
+
* PaletteEvaluation
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
stat_type: The name of the statistic to get.
|
|
48
|
+
kwargs: Additional keyword arguments required by the statistic.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
The requested statistic, or None if the statistic is not available.
|
|
52
|
+
"""
|
|
53
|
+
try:
|
|
54
|
+
if stat_type == "ColorDistribution":
|
|
55
|
+
edges = ColorHistogramEdges.load(self.assessment_dir)
|
|
56
|
+
return ColorDistribution.load(self.reference_dir, edges=edges)
|
|
57
|
+
elif stat_type == "ColorComparison":
|
|
58
|
+
return ColorComparison.load(self.reference_dir)
|
|
59
|
+
elif stat_type == "ReferenceBackground":
|
|
60
|
+
return ReferenceBackground.load(self.reference_dir)
|
|
61
|
+
elif stat_type == "Contrast":
|
|
62
|
+
return Contrast.load(self.reference_dir)
|
|
63
|
+
elif stat_type == "ReferenceGamut":
|
|
64
|
+
return ReferenceGamut.load(self.reference_dir)
|
|
65
|
+
elif stat_type == "ReferencePalette":
|
|
66
|
+
return ReferencePalette.load(self.reference_dir)
|
|
67
|
+
elif stat_type == "PaletteEvaluation":
|
|
68
|
+
return PaletteEvaluation.load(self.reference_dir, **kwargs)
|
|
69
|
+
else:
|
|
70
|
+
return Exception(f"{stat_type} is not a valid statistic that can be retrieved.")
|
|
71
|
+
except:
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
def save_stat(self, stat: Any):
|
|
75
|
+
"""Save the statistic to disk.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
stat: Any statistic object.
|
|
79
|
+
"""
|
|
80
|
+
if isinstance(stat, ColorDistribution):
|
|
81
|
+
stat.save(self.reference_dir, include_edges=False)
|
|
82
|
+
else:
|
|
83
|
+
stat.save(self.reference_dir)
|
|
84
|
+
|
|
85
|
+
def __repr__(self):
|
|
86
|
+
return f"ReferenceSet(identifier={self.identifier}, reference_dir={self.reference_dir})"
|
|
87
|
+
|
|
88
|
+
class Subset:
|
|
89
|
+
|
|
90
|
+
def __init__(self, assessment_dir: str, group: str | None = None, version: str | None = None, original_version: bool = False):
|
|
91
|
+
"""Subset of images for the assessment.
|
|
92
|
+
|
|
93
|
+
Assessment Subsets and Normalization Subsets are different.
|
|
94
|
+
|
|
95
|
+
Each Subset has three parameters that distinguish it from other Subsets.
|
|
96
|
+
* ``group`` is a group name. This allows you to group images in whatever way you want. One way is to group images by where they came from. For example, one group could be "Hospital A" and another group could be "Hospital B".
|
|
97
|
+
* ``version`` is a version name. This allows you to compare different versions of an image within the Assessment. For example, one Subset could be group="Hospital A" version="Original" and another Subset could be group="Hospital A" version="Normalized".
|
|
98
|
+
* ``original_version`` indicates whether this Subset represents the "Original" version of the images. "Original" means before normalization. Providing this information establishes which version is the baseline to check if morphological structures or color contrast were changed by stain normalization in the other versions.
|
|
99
|
+
|
|
100
|
+
An Assessment is thus composed of a collection of Subsets representing different groupings (image sources) and versions (original and different normalization methods to compare).
|
|
101
|
+
An Assessment also has a reference, which acts as the reference to compare all images to when computing assessment metrics/statistics. Any images in any Subset can be marked as reference.
|
|
102
|
+
|
|
103
|
+
**Note:** An image ID (filename without extension) cannot appear in more than one group. An image ID must be unique within a group. An image ID can appear in multiple versions.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
assessment_dir: Path to the assessment directory.
|
|
107
|
+
group: Group name.
|
|
108
|
+
version: Version name.
|
|
109
|
+
original_version: If True, this Subset is the original version of the images (i.e., before normalization).
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
self.assessment_dir = assessment_dir
|
|
113
|
+
if group is None and version is None:
|
|
114
|
+
self.subset_folder = self.assessment_dir
|
|
115
|
+
elif group is None:
|
|
116
|
+
self.subset_folder = os.path.join(self.assessment_dir, f"version_{version}")
|
|
117
|
+
elif version is None:
|
|
118
|
+
self.subset_folder = os.path.join(self.assessment_dir, f"group_{group}")
|
|
119
|
+
else:
|
|
120
|
+
self.subset_folder = os.path.join(self.assessment_dir, f"group_{group}", f"version_{version}")
|
|
121
|
+
os.makedirs(self.subset_folder, exist_ok=True)
|
|
122
|
+
|
|
123
|
+
subset_json_path = os.path.join(self.subset_folder, "subset.json")
|
|
124
|
+
if not os.path.exists(subset_json_path):
|
|
125
|
+
with open(subset_json_path, "w") as file:
|
|
126
|
+
json.dump({
|
|
127
|
+
"group": group,
|
|
128
|
+
"version": version,
|
|
129
|
+
"original_version": original_version,
|
|
130
|
+
}, file)
|
|
131
|
+
|
|
132
|
+
self.group = group
|
|
133
|
+
self.version = version
|
|
134
|
+
self.original_version = original_version
|
|
135
|
+
|
|
136
|
+
self.images = {}
|
|
137
|
+
self.reference_ids = []
|
|
138
|
+
|
|
139
|
+
for f in os.listdir(self.subset_folder):
|
|
140
|
+
if f.startswith("id_"):
|
|
141
|
+
self.images[f[3:]] = None
|
|
142
|
+
|
|
143
|
+
@classmethod
|
|
144
|
+
def load(cls, assessment_dir: str, subset_folder: str) -> Subset:
|
|
145
|
+
"""Load a Subset from disk.
|
|
146
|
+
|
|
147
|
+
Args:
|
|
148
|
+
assessment_dir: Path to the assessment directory.
|
|
149
|
+
subset_folder: Path to the Subset folder.
|
|
150
|
+
|
|
151
|
+
Returns:
|
|
152
|
+
A Subset.
|
|
153
|
+
"""
|
|
154
|
+
|
|
155
|
+
subset_json_path = os.path.join(subset_folder, "subset.json")
|
|
156
|
+
with open(subset_json_path, "r") as file:
|
|
157
|
+
json_data = json.load(file)
|
|
158
|
+
|
|
159
|
+
return cls(assessment_dir, group=json_data["group"], version=json_data["version"], original_version=["original_version"])
|
|
160
|
+
|
|
161
|
+
def __repr__(self):
|
|
162
|
+
return f"Subset(\n \
|
|
163
|
+
group={self.group}\n \
|
|
164
|
+
version={self.version}\n \
|
|
165
|
+
images={self.images}\n \
|
|
166
|
+
reference_ids={self.reference_ids}\n)"
|
|
167
|
+
|
|
168
|
+
def set_all_as_reference(self):
|
|
169
|
+
"""Set all images currently in the Subset as reference.
|
|
170
|
+
"""
|
|
171
|
+
self.reference_ids = self.images.keys()
|
|
172
|
+
|
|
173
|
+
def get_paths_in_folder(self, folder_path: str) -> list[str]:
|
|
174
|
+
"""Helper function for getting valid image paths in a folder.
|
|
175
|
+
|
|
176
|
+
Args:
|
|
177
|
+
folder_path: Folder path to get image paths from.
|
|
178
|
+
|
|
179
|
+
Returns:
|
|
180
|
+
A list of str paths.
|
|
181
|
+
"""
|
|
182
|
+
paths = []
|
|
183
|
+
for file in os.listdir(folder_path):
|
|
184
|
+
full_path = os.path.join(folder_path, file)
|
|
185
|
+
if os.path.isfile(full_path) and is_valid_extension(full_path):
|
|
186
|
+
paths.append(full_path)
|
|
187
|
+
return paths
|
|
188
|
+
|
|
189
|
+
def add_path_to_subset(self, path: str, slide: str | None = None, reference: list[str] | bool = False):
|
|
190
|
+
"""Add an image to the Subset.
|
|
191
|
+
|
|
192
|
+
To add images in bulk, use ``add_images`` instead.
|
|
193
|
+
|
|
194
|
+
Images can be part of a "slide." This is the case when you have multiple images associated with a single microscope slide.
|
|
195
|
+
For example, you have image tiles from a single slide, or one image per core in a tissue microarray (TMA) slide.
|
|
196
|
+
Add each path with the same slide name, and Assessment will associate those images together.
|
|
197
|
+
|
|
198
|
+
Args:
|
|
199
|
+
path: File path to the image.
|
|
200
|
+
slide: Slide name if the image is part of a slide that consists of multiple images.
|
|
201
|
+
reference: If True, this image becomes part of the reference. If list of IDs, checks if this image is in the list and becomes a reference only if in the list.
|
|
202
|
+
"""
|
|
203
|
+
|
|
204
|
+
image_id = is_valid_extension(path, split=True)[0]
|
|
205
|
+
if slide is None:
|
|
206
|
+
self.images[image_id] = SlideImage(path, identifier=image_id)
|
|
207
|
+
if (isinstance(reference, list) and image_id in reference) or (isinstance(reference, bool) and reference):
|
|
208
|
+
self.reference_ids.append(image_id)
|
|
209
|
+
else:
|
|
210
|
+
if slide in self.images:
|
|
211
|
+
self.images[slide].append(path, identifier=image_id)
|
|
212
|
+
else:
|
|
213
|
+
self.images[slide] = SlideImageCollection(slide)
|
|
214
|
+
self.images[slide].append(path, identifier=image_id)
|
|
215
|
+
if (isinstance(reference, list) and slide in reference) or (isinstance(reference, bool) and reference):
|
|
216
|
+
self.reference_ids.append(slide)
|
|
217
|
+
|
|
218
|
+
def add_images(self, images: list[str] | str, slide: str | None = None, reference: list[str] | bool = None):
|
|
219
|
+
"""Add images to the Subset.
|
|
220
|
+
|
|
221
|
+
Images can be part of a "slide." This is the case when you have multiple images associated with a single microscope slide.
|
|
222
|
+
For example, you have image tiles from a single slide, or one image per core in a tissue microarray (TMA) slide.
|
|
223
|
+
Add each path with the same slide name, and Assessment will associate those images together.
|
|
224
|
+
|
|
225
|
+
Args:
|
|
226
|
+
images: Image paths.
|
|
227
|
+
slide: Slide name to assign the paths to.
|
|
228
|
+
reference: If True, all images added become part of the reference. If list of IDs, only those images will become part of the reference.
|
|
229
|
+
"""
|
|
230
|
+
|
|
231
|
+
if isinstance(images, str):
|
|
232
|
+
images = [images]
|
|
233
|
+
|
|
234
|
+
if isinstance(images, list):
|
|
235
|
+
|
|
236
|
+
for path in images:
|
|
237
|
+
|
|
238
|
+
if not isinstance(path, str) or (not os.path.isfile(path) and not os.path.isdir(path)):
|
|
239
|
+
raise Exception(f"{path} is not a valid path.")
|
|
240
|
+
|
|
241
|
+
if os.path.isfile(path):
|
|
242
|
+
self.add_path_to_subset(path, slide=slide, reference=reference)
|
|
243
|
+
|
|
244
|
+
elif os.path.isfile(path) and is_valid_extension(path):
|
|
245
|
+
self.add_path_to_subset(path, slide=slide, reference=reference)
|
|
246
|
+
|
|
247
|
+
elif os.path.isdir(path):
|
|
248
|
+
for p in self.get_paths_in_folder(path):
|
|
249
|
+
self.add_path_to_subset(p, slide=slide, reference=reference)
|
|
250
|
+
|
|
251
|
+
def get_stat(self, identifier: str, stat_type: str, **kwargs) -> Any:
|
|
252
|
+
"""Get a statistic/metric.
|
|
253
|
+
|
|
254
|
+
Options for ``stat_type``:
|
|
255
|
+
* ColorSample
|
|
256
|
+
* ColorDistribution
|
|
257
|
+
* ColorComparison
|
|
258
|
+
* BackgroundEstimation
|
|
259
|
+
* Contrast
|
|
260
|
+
* ContrastChange
|
|
261
|
+
* Gamut
|
|
262
|
+
* GamutComparison
|
|
263
|
+
* StructurePreservation
|
|
264
|
+
* Palette
|
|
265
|
+
* PaletteEvaluation
|
|
266
|
+
* PaletteComparison
|
|
267
|
+
|
|
268
|
+
Args:
|
|
269
|
+
identifier: Image ID (filename without extension) or slide name.
|
|
270
|
+
stat_type: Name of the statistic to get.
|
|
271
|
+
kwargs: Additional keyword arguments for the statistic.
|
|
272
|
+
|
|
273
|
+
Returns:
|
|
274
|
+
The requested statistic, or None if the statistic is not available.
|
|
275
|
+
"""
|
|
276
|
+
|
|
277
|
+
if identifier not in self.images:
|
|
278
|
+
raise Exception(f"{identifier} is not a valid image or slide in this subset.")
|
|
279
|
+
|
|
280
|
+
image_stat_dir = os.path.join(self.subset_folder, f"id_{identifier}")
|
|
281
|
+
|
|
282
|
+
try:
|
|
283
|
+
if stat_type == "ColorSample":
|
|
284
|
+
return ColorSample.load(image_stat_dir, edges=ColorHistogramEdges.load(self.assessment_dir))
|
|
285
|
+
elif stat_type == "ColorDistribution":
|
|
286
|
+
return ColorDistriution.load(image_stat_dir, edges=ColorHistogramEdges.load(self.assessment_dir))
|
|
287
|
+
elif stat_type == "ColorComparison":
|
|
288
|
+
return ColorComparison.load(image_stat_dir)
|
|
289
|
+
elif stat_type == "BackgroundEstimation":
|
|
290
|
+
return BackgroundEstimation.load(image_stat_dir)
|
|
291
|
+
elif stat_type == "Contrast":
|
|
292
|
+
return Contrast.load(image_stat_dir)
|
|
293
|
+
elif stat_type == "ContrastChange":
|
|
294
|
+
return ContrastChange.load(image_stat_dir)
|
|
295
|
+
elif stat_type == "Gamut":
|
|
296
|
+
return Gamut.load(image_stat_dir)
|
|
297
|
+
elif stat_type == "GamutComparison":
|
|
298
|
+
return GamutComparison.load(image_stat_dir)
|
|
299
|
+
elif stat_type == "StructurePreservation":
|
|
300
|
+
return StructurePreservation.load(image_stat_dir)
|
|
301
|
+
elif stat_type == "Palette":
|
|
302
|
+
return Palette.load(image_stat_dir)
|
|
303
|
+
elif stat_type == "PaletteEvaluation":
|
|
304
|
+
return PaletteEvaluation.load(image_stat_dir, **kwargs)
|
|
305
|
+
elif stat_type == "PaletteComparison":
|
|
306
|
+
return PaletteComparison.load(image_stat_dir)
|
|
307
|
+
else:
|
|
308
|
+
return ValueError(f"{stat_type} is not a valid statistic.")
|
|
309
|
+
except ValueError as ve:
|
|
310
|
+
raise
|
|
311
|
+
except Exception:
|
|
312
|
+
return None
|
|
313
|
+
|
|
314
|
+
def save_stat(self, stat: Any, identifier: str):
|
|
315
|
+
"""Save the statistic to disk.
|
|
316
|
+
|
|
317
|
+
Args:
|
|
318
|
+
stat: The statistic object.
|
|
319
|
+
identifier: The ID of the image or slide name.
|
|
320
|
+
"""
|
|
321
|
+
|
|
322
|
+
if identifier not in self.images:
|
|
323
|
+
raise Exception(f"{identifier} is not a valid image or slide in this subset.")
|
|
324
|
+
|
|
325
|
+
image_stat_dir = os.path.join(self.subset_folder, f"id_{identifier}")
|
|
326
|
+
os.makedirs(image_stat_dir, exist_ok=True)
|
|
327
|
+
|
|
328
|
+
if isinstance(stat, (ColorSample, ColorDistribution)):
|
|
329
|
+
stat.save(image_stat_dir, include_edges=False)
|
|
330
|
+
else:
|
|
331
|
+
stat.save(image_stat_dir)
|
|
332
|
+
|
|
333
|
+
class Assessment:
|
|
334
|
+
|
|
335
|
+
def __init__(self, assessment_dir: str):
|
|
336
|
+
"""Stain normalization assessment.
|
|
337
|
+
|
|
338
|
+
An Assessment consists of reference and query images. A reference distribution is calculated from the reference images, and this reference distribution is used to compare all images (query and reference images) against.
|
|
339
|
+
Once you compute the assessment metrics on an image, they will be saved to the assessment_dir, which can be reloaded in a later session.
|
|
340
|
+
|
|
341
|
+
Args:
|
|
342
|
+
assessment_dir: Assessment directory.
|
|
343
|
+
"""
|
|
344
|
+
|
|
345
|
+
# Make a directory for saving assessment calculations if it doesn't exist already.
|
|
346
|
+
os.makedirs(assessment_dir, exist_ok=True)
|
|
347
|
+
self.assessment_dir = assessment_dir
|
|
348
|
+
|
|
349
|
+
# If color histogram edges exist, load that. Otherwise, make default edges.
|
|
350
|
+
self.edges = ColorHistogramEdges.load(self.assessment_dir)
|
|
351
|
+
if self.edges is None:
|
|
352
|
+
self.edges = ColorHistogramEdges()
|
|
353
|
+
self.edges.save(self.assessment_dir)
|
|
354
|
+
|
|
355
|
+
self.reference = None # ReferenceSet
|
|
356
|
+
self.reference_is_set = False
|
|
357
|
+
self.image_sets = []
|
|
358
|
+
|
|
359
|
+
# If assessment_dir has files already, load in what Subsets are available.
|
|
360
|
+
if os.path.exists(os.path.join(self.assessment_dir, "subset.json")):
|
|
361
|
+
self.image_sets.append(Subset.load(self.assessment_dir, self.assessment_dir))
|
|
362
|
+
for f in os.listdir(self.assessment_dir):
|
|
363
|
+
path = os.path.join(self.assessment_dir, f)
|
|
364
|
+
if not os.path.isdir(path):
|
|
365
|
+
continue
|
|
366
|
+
if f.startswith("group_"):
|
|
367
|
+
if os.path.exists(os.path.join(path, "subset.json")):
|
|
368
|
+
self.image_sets.append(Subset.load(self.assessment_dir, path))
|
|
369
|
+
for f2 in os.listdir(path):
|
|
370
|
+
path2 = os.path.join(path, f2)
|
|
371
|
+
if os.path.isdir(path2) and f2.startswith("version_"):
|
|
372
|
+
self.image_sets.append(Subset.load(self.assessment_dir, path2))
|
|
373
|
+
elif f == "reference":
|
|
374
|
+
self.reference = ReferenceSet(self.assessment_dir)
|
|
375
|
+
self.reference_is_set = True
|
|
376
|
+
|
|
377
|
+
# Keep track of what metrics have been computed already
|
|
378
|
+
self.computed = set()
|
|
379
|
+
|
|
380
|
+
# Plots
|
|
381
|
+
self.plots = {}
|
|
382
|
+
|
|
383
|
+
def __repr__(self):
|
|
384
|
+
return f"Assessment(\n \
|
|
385
|
+
assessment_dir={self.assessment_dir}\n \
|
|
386
|
+
reference={self.reference}\n \
|
|
387
|
+
image_sets={self.image_sets}\n \
|
|
388
|
+
computed={self.computed}\n \
|
|
389
|
+
reference_is_set={self.reference_is_set}\n)"
|
|
390
|
+
|
|
391
|
+
def add_images(
|
|
392
|
+
self,
|
|
393
|
+
images: list[str] | str,
|
|
394
|
+
slide: str | None = None,
|
|
395
|
+
group: str | None = None,
|
|
396
|
+
version: str | None = None,
|
|
397
|
+
original_version: bool = False,
|
|
398
|
+
reference: str | bool | list[str] | None = None
|
|
399
|
+
):
|
|
400
|
+
"""Add images to perform the assessment on.
|
|
401
|
+
|
|
402
|
+
How to set the parameters:
|
|
403
|
+
* If you have images which can be **grouped** in some way (e.g., time period, organ, project), then call ``add_images`` for each group and specify a group name.
|
|
404
|
+
* If you have images where each image might have multiple **versions** (e.g., original, normalized, corrected), then call ``add_images`` for each version and specify a version name.
|
|
405
|
+
* If you have separate images that you want to consider as one **slide** (e.g., tiles from a slide), then specify a slide name. Use a for loop to add images if needed.
|
|
406
|
+
* For the version that is the **original (before normalization) version**, set ``original_version=True``.
|
|
407
|
+
* To perform the assessment, we need a reference to compare all images against. Set ``reference`` to the images you want to be marked as the reference. Good references could be the target or a group of images from the past that were normalized well that you want to get your new normalized images as close to.
|
|
408
|
+
|
|
409
|
+
**Note:** If you are using the ``slide`` parameter and want this slide to be a reference, ``reference=True`` or using the slide name str will add all images in the slide as reference.
|
|
410
|
+
To set particular images within the slide as reference, do not use ``slide``; keep each image as separate entities. Using individual image ID names for images in a ``slide`` for setting the reference will not work.
|
|
411
|
+
|
|
412
|
+
Args:
|
|
413
|
+
images: Path to an image, directory of images, or list of images/directories.
|
|
414
|
+
slide: If images are crops from a larger slide image, specify a slide name.
|
|
415
|
+
group: Group name. For example, if images are from the same source, group could be the name of the source.
|
|
416
|
+
version: Version name. For example, "original" or "normalized." This allows you to have multiple versions of the same slide.
|
|
417
|
+
original_version: If True, makes this version the original. Only one version within a group can be the original.
|
|
418
|
+
reference: If True, all images being added are set as reference. Or can provide list of IDs (file names without extension) of images or slide names to use as reference. Or can provide a single ID or slide name.
|
|
419
|
+
"""
|
|
420
|
+
for image_set in self.image_sets:
|
|
421
|
+
|
|
422
|
+
if image_set.group == group and image_set.version == version:
|
|
423
|
+
image_set.add_images(images, slide=slide, reference=reference)
|
|
424
|
+
return
|
|
425
|
+
|
|
426
|
+
if original_version:
|
|
427
|
+
for image_set in self.image_sets:
|
|
428
|
+
if image_set.group == group and image_set.version != version and image_set.original_version:
|
|
429
|
+
raise Exception("Only one version in a group can be the original version.")
|
|
430
|
+
|
|
431
|
+
# No matching image sets, make a new set
|
|
432
|
+
image_set = Subset(self.assessment_dir, group=group, version=version, original_version=original_version)
|
|
433
|
+
image_set.add_images(images, slide=slide, reference=reference)
|
|
434
|
+
self.image_sets.append(image_set)
|
|
435
|
+
|
|
436
|
+
if reference:
|
|
437
|
+
self.reference_is_set = True
|
|
438
|
+
|
|
439
|
+
def get_image_set(self, group: str | None = None, version: str | None = None) -> Subset:
|
|
440
|
+
"""Get an image Subset.
|
|
441
|
+
|
|
442
|
+
Args:
|
|
443
|
+
group: Group name.
|
|
444
|
+
version: Version name.
|
|
445
|
+
|
|
446
|
+
Returns:
|
|
447
|
+
A Subset.
|
|
448
|
+
"""
|
|
449
|
+
for image_set in self.image_sets:
|
|
450
|
+
if image_set.group == group and image_set.version == version:
|
|
451
|
+
return image_set
|
|
452
|
+
raise Exception(f"Subset with group {group} and version {version} not found.")
|
|
453
|
+
|
|
454
|
+
def write_to_csv(self):
|
|
455
|
+
"""Write assessment metrics to a CSV file.
|
|
456
|
+
"""
|
|
457
|
+
csv_path = os.path.join(self.output_dir, "results.csv")
|
|
458
|
+
with open(csv_path, mode="w", newline='', encoding="utf-8") as file:
|
|
459
|
+
writer = csv.writer(file)
|
|
460
|
+
|
|
461
|
+
writer.writerow(["identifier", "reference", "group", "version", "h_dist", "s_dist", "v_dist", "rgb_dist", "oklab_dist", "palette_compare", "palette_Hdiv", "palette_Ediv", "palette_HEsep", "background", "oog_count", "ig_count", "structure_mean", "structure_std", "contrast_mean", "contrast_std"])
|
|
462
|
+
|
|
463
|
+
for image_set in self.image_sets:
|
|
464
|
+
for identifier, img in image_set.images.items():
|
|
465
|
+
version = image_set.version
|
|
466
|
+
group = image_set.group
|
|
467
|
+
is_reference = identifier in image_set.reference_ids
|
|
468
|
+
|
|
469
|
+
row = [identifier, is_reference, group, version]
|
|
470
|
+
|
|
471
|
+
cc = image_set.get_stat("ColorComparison")
|
|
472
|
+
if cc is not None:
|
|
473
|
+
row.extend([cc.get_val("h"), cc.get_val("s"), cc.get_val("v"), cc.get_val("rgb"), cc.get_val("oklab")])
|
|
474
|
+
else:
|
|
475
|
+
row.extend([None] * 5)
|
|
476
|
+
|
|
477
|
+
pc = image_set.get_stat("PaletteComparison")
|
|
478
|
+
if pc is not None:
|
|
479
|
+
row.extend([pc.get_val("compare"), pc.get_val("Hdiv"), pc.get_val("Ediv"), pc.get_val("HEsep")])
|
|
480
|
+
else:
|
|
481
|
+
row.extend([None] * 4)
|
|
482
|
+
|
|
483
|
+
bc = image_set.get_stat("BackgroundComparison")
|
|
484
|
+
if bc is not None:
|
|
485
|
+
row.extend([bc.get_val()])
|
|
486
|
+
else:
|
|
487
|
+
row.extend([None])
|
|
488
|
+
|
|
489
|
+
gc = image_set.get_stat("GamutComparison")
|
|
490
|
+
if gc is not None:
|
|
491
|
+
row.extend([gc.get_val("oog_count"), gc.get_val("ig_count")])
|
|
492
|
+
else:
|
|
493
|
+
row.extend([None] * 2)
|
|
494
|
+
|
|
495
|
+
s = image_set.get_stat("StructurePreservation")
|
|
496
|
+
if s is not None:
|
|
497
|
+
row.extend([s.get_val()[0], s.get_val()[1]])
|
|
498
|
+
else:
|
|
499
|
+
row.extend([None] * 2)
|
|
500
|
+
|
|
501
|
+
ct = image_set.get_stat("ContrastChange")
|
|
502
|
+
if ct is not None:
|
|
503
|
+
row.extend([ct.get_val()[0], ct.get_val()[1]])
|
|
504
|
+
else:
|
|
505
|
+
row.extend([None] * 2)
|
|
506
|
+
|
|
507
|
+
writer.writerow(row)
|
|
508
|
+
|
|
509
|
+
def color_distance_compute(self):
|
|
510
|
+
"""Compute the color distance assessment.
|
|
511
|
+
"""
|
|
512
|
+
|
|
513
|
+
# Get the reference color distribution if it exists
|
|
514
|
+
cd = self.reference.get_stat("ColorDistribution")
|
|
515
|
+
|
|
516
|
+
# If the reference color distribution does not exist, we will need to compute it
|
|
517
|
+
ref_color_samples = []
|
|
518
|
+
|
|
519
|
+
for image_set in self.image_sets:
|
|
520
|
+
for key, img in image_set.images.items():
|
|
521
|
+
cs = image_set.get_stat(key, "ColorSample")
|
|
522
|
+
if cs is None:
|
|
523
|
+
cs = ColorSample(img, self.edges)
|
|
524
|
+
cs.compute()
|
|
525
|
+
image_set.save_stat(cs, key)
|
|
526
|
+
if cd is None and key in image_set.reference_ids:
|
|
527
|
+
ref_color_samples.append(cs)
|
|
528
|
+
|
|
529
|
+
# Compute the reference color distribution
|
|
530
|
+
if cd is None:
|
|
531
|
+
cd = ColorDistribution(ref_color_samples, identifier=self.reference.identifier)
|
|
532
|
+
cd.compute()
|
|
533
|
+
self.reference.save_stat(cd)
|
|
534
|
+
|
|
535
|
+
# Compute the comparison between the colors samples and the reference color distribution
|
|
536
|
+
for image_set in self.image_sets:
|
|
537
|
+
for key in image_set.images.keys():
|
|
538
|
+
if image_set.get_stat(key, "ColorComparison") is None:
|
|
539
|
+
cc = ColorComparison(cd, image_set.get_stat(key, "ColorSample"))
|
|
540
|
+
cc.compute()
|
|
541
|
+
image_set.save_stat(cc, key)
|
|
542
|
+
|
|
543
|
+
def palette_compute(self):
|
|
544
|
+
"""Compute the palette assessment.
|
|
545
|
+
"""
|
|
546
|
+
|
|
547
|
+
rp = self.reference.get_stat("ReferencePalette")
|
|
548
|
+
rpe = self.reference.get_stat("PaletteEvaluation")
|
|
549
|
+
|
|
550
|
+
ref_palettes = []
|
|
551
|
+
|
|
552
|
+
for image_set in self.image_sets:
|
|
553
|
+
for key, img in image_set.images.items():
|
|
554
|
+
p = image_set.get_stat(key, "Palette")
|
|
555
|
+
if p is None:
|
|
556
|
+
p = Palette(img)
|
|
557
|
+
p.compute()
|
|
558
|
+
image_set.save_stat(p, key)
|
|
559
|
+
pe = image_set.get_stat(key, "PaletteEvaluation", palette=p)
|
|
560
|
+
if pe is None:
|
|
561
|
+
pe = PaletteEvaluation(p)
|
|
562
|
+
pe.compute()
|
|
563
|
+
image_set.save_stat(pe, key)
|
|
564
|
+
if rp is None and key in image_set.reference_ids:
|
|
565
|
+
ref_palettes.append(p)
|
|
566
|
+
|
|
567
|
+
if rp is None:
|
|
568
|
+
rp = ReferencePalette(ref_palettes, identifier=self.reference.identifier)
|
|
569
|
+
rp.compute()
|
|
570
|
+
self.reference.save_stat(rp)
|
|
571
|
+
rpe = PaletteEvaluation(rp)
|
|
572
|
+
rpe.compute()
|
|
573
|
+
self.reference.save_stat(rpe)
|
|
574
|
+
|
|
575
|
+
for image_set in self.image_sets:
|
|
576
|
+
for key in image_set.images.keys():
|
|
577
|
+
if image_set.get_stat(key, "PaletteComparison") is None:
|
|
578
|
+
p = image_set.get_stat(key, "Palette")
|
|
579
|
+
pc = PaletteComparison(rpe, image_set.get_stat(key, "PaletteEvaluation", palette=p))
|
|
580
|
+
pc.compute()
|
|
581
|
+
image_set.save_stat(pc, key)
|
|
582
|
+
|
|
583
|
+
def background_compute(self):
|
|
584
|
+
"""Compute the background assessment.
|
|
585
|
+
"""
|
|
586
|
+
|
|
587
|
+
rb = self.reference.get_stat("ReferenceBackground")
|
|
588
|
+
|
|
589
|
+
ref_backgrounds = []
|
|
590
|
+
|
|
591
|
+
for image_set in self.image_sets:
|
|
592
|
+
for key, img in image_set.images.items():
|
|
593
|
+
be = image_set.get_stat(key, "BackgroundEstimation")
|
|
594
|
+
if be is None:
|
|
595
|
+
be = BackgroundEstimation(img)
|
|
596
|
+
be.compute()
|
|
597
|
+
image_set.save_stat(be, key)
|
|
598
|
+
if rb is None and key in image_set.reference_ids:
|
|
599
|
+
ref_backgrounds.append(be)
|
|
600
|
+
|
|
601
|
+
if rb is None:
|
|
602
|
+
rb = ReferenceBackground(ref_backgrounds, identifier=self.reference.identifier)
|
|
603
|
+
rb.compute()
|
|
604
|
+
self.reference.save_stat(rb)
|
|
605
|
+
|
|
606
|
+
for image_set in self.image_sets:
|
|
607
|
+
for key in image_set.images.keys():
|
|
608
|
+
if image_set.get_stat(key, "BackgroundComparison") is None:
|
|
609
|
+
bc = BackgroundComparison(rb, image_set.get_stat(key, "BackgroundEstimation"))
|
|
610
|
+
bc.compute()
|
|
611
|
+
image_set.set_save(bc, key)
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def gamut_compute(self):
|
|
615
|
+
"""Compute the gamut assessment.
|
|
616
|
+
"""
|
|
617
|
+
|
|
618
|
+
rg = self.reference.get_stat("ReferenceGamut")
|
|
619
|
+
|
|
620
|
+
ref_gamuts = []
|
|
621
|
+
|
|
622
|
+
for image_set in self.image_sets:
|
|
623
|
+
for key, img in image_set.images.items():
|
|
624
|
+
g = image_set.get_stat(key, "Gamut")
|
|
625
|
+
if g is None:
|
|
626
|
+
g = Gamut(img)
|
|
627
|
+
g.compute()
|
|
628
|
+
image_set.save_stat(g, key)
|
|
629
|
+
if rg is None and key in image_set.reference_ids:
|
|
630
|
+
ref_gamuts.append(g)
|
|
631
|
+
|
|
632
|
+
if rg is None:
|
|
633
|
+
rg = ReferenceGamut(ref_gamuts, identifier=self.reference.identifier)
|
|
634
|
+
rg.compute()
|
|
635
|
+
self.reference.save_stat(rg)
|
|
636
|
+
|
|
637
|
+
for image_set in self.image_sets:
|
|
638
|
+
for key in image_set.images.keys():
|
|
639
|
+
if image_set.get_stat(key, "GamutComparison") is None:
|
|
640
|
+
gc = GamutComparison(rg, image_set.get_stat(key, "Gamut"))
|
|
641
|
+
gc.compute()
|
|
642
|
+
image_set.set_save(gc, key)
|
|
643
|
+
|
|
644
|
+
def structure_compute(self, image_sets_grouped: dict[str, tuple[Subset, list[Subset]]]):
|
|
645
|
+
"""Compute the structure preservation assessment.
|
|
646
|
+
|
|
647
|
+
Args:
|
|
648
|
+
image_sets_grouped: Image Subsets organized as a dictionary. The keys are the group names. Each value is a tuple of the original_version Subset and a list of all other Subsets to compare with.
|
|
649
|
+
"""
|
|
650
|
+
|
|
651
|
+
for group, (original_version, other_versions) in image_sets_grouped.items():
|
|
652
|
+
|
|
653
|
+
if original_version is None or len(other_versions) == 0:
|
|
654
|
+
continue
|
|
655
|
+
|
|
656
|
+
for other_version in other_versions:
|
|
657
|
+
for key, img in other_version.images.items():
|
|
658
|
+
sp = other_version.get_stat(key, "StructurePreservation")
|
|
659
|
+
if sp is None and key in original_version.images:
|
|
660
|
+
sp = StructurePreservation(original_version.images[key], img)
|
|
661
|
+
sp.compute()
|
|
662
|
+
other_version.save_stat(sp, key)
|
|
663
|
+
|
|
664
|
+
def contrast_compute(self, image_sets_grouped):
|
|
665
|
+
"""Compute the contrast assessment.
|
|
666
|
+
|
|
667
|
+
Args:
|
|
668
|
+
image_sets_grouped: Image Subsets organized as a dictionary. The keys are the group names. Each value is a tuple of the original_version Subset and a list of all other Subsets to compare with.
|
|
669
|
+
"""
|
|
670
|
+
|
|
671
|
+
for group, (original_version, other_versions) in image_sets_grouped.items():
|
|
672
|
+
|
|
673
|
+
if original_version is None or len(other_versions) == 0:
|
|
674
|
+
continue
|
|
675
|
+
|
|
676
|
+
for other_version in other_versions:
|
|
677
|
+
for key, img in other_version.images.items():
|
|
678
|
+
original_contrast = original_version.get_stat(key, "Contrast")
|
|
679
|
+
if original_contrast is None and key in original_version.images:
|
|
680
|
+
original_contrast = Contrast(original_version.images[key])
|
|
681
|
+
original_contrast.compute()
|
|
682
|
+
original_version.save_stat(original_contrast, key)
|
|
683
|
+
other_contrast = other_version.get_stat(key, "Contrast")
|
|
684
|
+
if other_contrast is None:
|
|
685
|
+
other_contrast = Contrast(img, tile_locs=original_contrast.tile_locs)
|
|
686
|
+
other_contrast.compute()
|
|
687
|
+
other_version.save_stat(other_contrast, key)
|
|
688
|
+
cc = other_version.get_stat(key, "ContrastChange")
|
|
689
|
+
if cc is None and other_contrast is not None and original_contrast is not None:
|
|
690
|
+
cc = ContrastChange(original_contrast, other_contrast)
|
|
691
|
+
cc.compute()
|
|
692
|
+
other_version.save_stat(cc, key)
|
|
693
|
+
|
|
694
|
+
def create_traces(self, stat_type: str, plot_type: str) -> dict[str | None, list[tuple[str, str, float | tuple[float, float]]]]:
|
|
695
|
+
"""Create traces for graphing.
|
|
696
|
+
|
|
697
|
+
Args:
|
|
698
|
+
stat_type: Statistic name.
|
|
699
|
+
plot_type: Plot name (within the statistic).
|
|
700
|
+
|
|
701
|
+
Returns:
|
|
702
|
+
Traces as a dictionary with each key being a version (one trace) and value being a list of data points. Each data point is a tuple consisting of (identifier, group, value). Value can be a float or a tuple of two floats (mean, std).
|
|
703
|
+
"""
|
|
704
|
+
|
|
705
|
+
traces = {}
|
|
706
|
+
for image_set in self.image_sets:
|
|
707
|
+
for identifier in image_set.images.keys():
|
|
708
|
+
version = image_set.version
|
|
709
|
+
group = image_set.group
|
|
710
|
+
stat = image_set.get_stat(identifier, stat_type)
|
|
711
|
+
if stat is None:
|
|
712
|
+
continue
|
|
713
|
+
value = stat.get_val(plot_type)
|
|
714
|
+
entry = (identifier, group, value)
|
|
715
|
+
if version not in traces:
|
|
716
|
+
traces[version] = [entry]
|
|
717
|
+
else:
|
|
718
|
+
traces[version].append(entry)
|
|
719
|
+
|
|
720
|
+
return traces
|
|
721
|
+
|
|
722
|
+
def color_distance(
|
|
723
|
+
self,
|
|
724
|
+
plot_type: str = "h",
|
|
725
|
+
threshold: float | None = None,
|
|
726
|
+
sort: bool = True,
|
|
727
|
+
sort_by: str | None = None,
|
|
728
|
+
clip_ids: bool = False,
|
|
729
|
+
hide_ids: bool = False,
|
|
730
|
+
save_path: str | None = None,
|
|
731
|
+
) -> plotly.graph_objects.Figure:
|
|
732
|
+
"""Create a color distance plot.
|
|
733
|
+
|
|
734
|
+
Args:
|
|
735
|
+
plot_type: Color distance plot type ("h", "s", "v", "rgb", "oklab").
|
|
736
|
+
threshold: Value for a horizontal threshold line drawn on the graph.
|
|
737
|
+
sort: Sort points. If True, set sort_by.
|
|
738
|
+
sort_by: Version name to sort by. If None and sort=True, the None version is used.
|
|
739
|
+
clip_ids: Clip IDs if they are too long.
|
|
740
|
+
hide_ids: Hide IDs.
|
|
741
|
+
save_path: Path to save the figure.
|
|
742
|
+
|
|
743
|
+
Returns:
|
|
744
|
+
The requested Plotly figure.
|
|
745
|
+
"""
|
|
746
|
+
|
|
747
|
+
if "color_dist" not in self.computed:
|
|
748
|
+
raise Exception("Call compute(criteria=\"color_dist\") first.")
|
|
749
|
+
|
|
750
|
+
plot_name = "color_dist_" + plot_type
|
|
751
|
+
|
|
752
|
+
if plot_name not in self.plots:
|
|
753
|
+
traces = self.create_traces("ColorComparison", plot_type)
|
|
754
|
+
scatter = ScatterPlot(traces, yaxis_title=plot_labels[plot_name][0], title=plot_labels[plot_name][1])
|
|
755
|
+
self.plots[plot_name] = scatter
|
|
756
|
+
|
|
757
|
+
if save_path is not None:
|
|
758
|
+
self.plots[plot_name].save_plot(save_path=save_path, threshold=threshold, sort=sort, sort_by=sort_by, clip_ids=clip_ids, hide_ids=hide_ids)
|
|
759
|
+
|
|
760
|
+
return self.plots[plot_name].make_plot(threshold=threshold, sort=sort, sort_by=sort_by, clip_ids=clip_ids, hide_ids=hide_ids)
|
|
761
|
+
|
|
762
|
+
def color_hist(
|
|
763
|
+
self,
|
|
764
|
+
ids: str | list [str],
|
|
765
|
+
plot_type: str = "h",
|
|
766
|
+
groups: str | list[str] | None = None,
|
|
767
|
+
versions: list[str] | str | None = None,
|
|
768
|
+
reference: bool = False,
|
|
769
|
+
density: bool = True,
|
|
770
|
+
color: list[str] | str | None = None,
|
|
771
|
+
hide_axes: bool = False,
|
|
772
|
+
) -> plotly.graph_objects.Figure :
|
|
773
|
+
"""Create a color histogram for a single slide or multiple slides.
|
|
774
|
+
|
|
775
|
+
If you have used group and version names in the Assessment, you should specify the ``groups`` and ``versions`` parameters so it is unambiguous which images you are referring to.
|
|
776
|
+
If you want to refer to an image that has no group name or no version name, its group name or version name is ``None`` (NoneType).
|
|
777
|
+
|
|
778
|
+
Args:
|
|
779
|
+
ids: One or more IDs (or slide names) of the images to be represented in the color histogram.
|
|
780
|
+
plot_type: Histogram plot type to show ("h", "s", "v", "rgb", "oklab", "uv").
|
|
781
|
+
groups: A group name (if ids is set to only one image) or a list of group names corresponding to the list of ids provided.
|
|
782
|
+
versions: A version name (if ids is set to only one image) or a list of version names corresponding to the list of ids provided.
|
|
783
|
+
reference: If True, includes the reference distribution in the plot.
|
|
784
|
+
density: If True, plot as a density. Otherwise, plots as counts.
|
|
785
|
+
color: A color (if ids is set to only one image) or a list of colors corresponding to the list of ids provided. These colors will be used for the plot. Only for ``plot_type="uv"``.
|
|
786
|
+
hide_axes: Hide axes. Only for ``plot_type="uv"``.
|
|
787
|
+
|
|
788
|
+
Returns:
|
|
789
|
+
The requested Plotly figure.
|
|
790
|
+
"""
|
|
791
|
+
|
|
792
|
+
cs_cd = []
|
|
793
|
+
|
|
794
|
+
if not isinstance(ids, list):
|
|
795
|
+
ids = [ids]
|
|
796
|
+
if not isinstance(groups, list):
|
|
797
|
+
groups = [groups]
|
|
798
|
+
if not isinstance(versions, list):
|
|
799
|
+
versions = [versions]
|
|
800
|
+
|
|
801
|
+
if groups is None:
|
|
802
|
+
groups = [None] * len(ids)
|
|
803
|
+
if versions is None:
|
|
804
|
+
versions = [None] * len(ids)
|
|
805
|
+
|
|
806
|
+
for i, img_id in enumerate(ids):
|
|
807
|
+
cs = self.get_image_set(group=groups[i], version=versions[i]).get_stat(img_id, "ColorSample", edges=self.edges)
|
|
808
|
+
cs_cd.append(cs)
|
|
809
|
+
|
|
810
|
+
if reference:
|
|
811
|
+
cd = self.reference.get_stat("ColorDistribution", edges=self.edges)
|
|
812
|
+
cs_cd.append(cd)
|
|
813
|
+
|
|
814
|
+
if len(cs_cd) == 1:
|
|
815
|
+
color_hist_plot = HistPlot(cs_cd[0])
|
|
816
|
+
|
|
817
|
+
if plot_type == "h":
|
|
818
|
+
return color_hist_plot.h_hist_plot(density=density)
|
|
819
|
+
elif plot_type == "s":
|
|
820
|
+
return color_hist_plot.s_hist_plot(density=density)
|
|
821
|
+
elif plot_type == "v":
|
|
822
|
+
return color_hist_plot.v_hist_plot(density=density)
|
|
823
|
+
elif plot_type == "rgb":
|
|
824
|
+
return color_hist_plot.rgb_hist_plot(density=density)
|
|
825
|
+
elif plot_type == "oklab":
|
|
826
|
+
return color_hist_plot.oklab_hist_plot(density=density)
|
|
827
|
+
elif plot_type == "uv":
|
|
828
|
+
return color_hist_plot.uv_hist(color=color, density=density, hide_axes=hide_axes)
|
|
829
|
+
else:
|
|
830
|
+
raise Exception(f"{plot_type} is not a valid plot_type.")
|
|
831
|
+
|
|
832
|
+
else:
|
|
833
|
+
trace_labels = []
|
|
834
|
+
for i, img_id in enumerate(ids):
|
|
835
|
+
trace_label = img_id
|
|
836
|
+
if versions[i] is not None:
|
|
837
|
+
trace_label += f" {versions[i]}"
|
|
838
|
+
trace_labels.append(trace_label)
|
|
839
|
+
if reference:
|
|
840
|
+
trace_labels.append(self.reference.identifier)
|
|
841
|
+
|
|
842
|
+
color_hist_plot = HistPlot(cs_cd, trace_labels=trace_labels)
|
|
843
|
+
|
|
844
|
+
if plot_type == "h":
|
|
845
|
+
return color_hist_plot.h_hist_compare(density=density)
|
|
846
|
+
elif plot_type == "s":
|
|
847
|
+
return color_hist_plot.s_hist_compare(density=density)
|
|
848
|
+
elif plot_type == "v":
|
|
849
|
+
return color_hist_plot.v_hist_compare(density=density)
|
|
850
|
+
elif plot_type == "uv":
|
|
851
|
+
return color_hist_plot.uv_hist(color=color, density=density, hide_axes=hide_axes)
|
|
852
|
+
else:
|
|
853
|
+
raise Exception(f"{plot_type} is not a valid plot_type.")
|
|
854
|
+
|
|
855
|
+
def palette(
|
|
856
|
+
self,
|
|
857
|
+
plot_type: str = "compare",
|
|
858
|
+
threshold: float | None = None,
|
|
859
|
+
sort: bool = True,
|
|
860
|
+
sort_by: str | None = None,
|
|
861
|
+
clip_ids: bool = False,
|
|
862
|
+
hide_ids: bool = False,
|
|
863
|
+
save_path: str | None = None
|
|
864
|
+
) -> plotly.graph_objects.Figure:
|
|
865
|
+
"""Create palette plot.
|
|
866
|
+
|
|
867
|
+
Options for ``plot_type``:
|
|
868
|
+
* "compare": Comparison between each query palette with the reference distribution's palette.
|
|
869
|
+
* "Hdiv": Hematoxylin diversity within each query palette.
|
|
870
|
+
* "Ediv": Eosin diversity within each query palette.
|
|
871
|
+
* "HEsep": Separability (difference) between the hematoxylin and eosin colors within each query palette.
|
|
872
|
+
|
|
873
|
+
Args:
|
|
874
|
+
plot_type: Palette plot type ("compare", "Hdiv", "Ediv", or "HEsep").
|
|
875
|
+
threshold: Value for a horizontal threshold line drawn on the graph.
|
|
876
|
+
sort: Sort points. If True, set sort_by.
|
|
877
|
+
sort_by: Version name to sort by. If None and sort=True, the None version is used.
|
|
878
|
+
clip_ids: Clip IDs if they are too long.
|
|
879
|
+
hide_ids: Hide IDs.
|
|
880
|
+
save_path: Path to save the figure.
|
|
881
|
+
|
|
882
|
+
Returns:
|
|
883
|
+
The requested Plotly figure.
|
|
884
|
+
"""
|
|
885
|
+
|
|
886
|
+
if "palette" not in self.computed:
|
|
887
|
+
raise Exception("Call compute(criteria=\"palette\") first.")
|
|
888
|
+
|
|
889
|
+
plot_name = "palette_" + plot_type
|
|
890
|
+
|
|
891
|
+
if plot_name not in self.plots:
|
|
892
|
+
traces = self.create_traces("PaletteComparison", plot_type)
|
|
893
|
+
scatter = ScatterPlot(traces, yaxis_title=plot_labels[plot_name][0], title=plot_labels[plot_name][1])
|
|
894
|
+
self.plots[plot_name] = scatter
|
|
895
|
+
|
|
896
|
+
if save_path is not None:
|
|
897
|
+
self.plots[plot_name].save_plot(save_path=save_path, threshold=threshold, sort=sort, sort_by=sort_by, clip_ids=clip_ids, hide_ids=hide_ids)
|
|
898
|
+
|
|
899
|
+
return self.plots[plot_name].make_plot(threshold=threshold, sort=sort, sort_by=sort_by, clip_ids=clip_ids, hide_ids=hide_ids)
|
|
900
|
+
|
|
901
|
+
|
|
902
|
+
def display_palette(self, ids: str | list[str], groups: str | list[str] | None = None, versions: str | list[str] | None = None, reference: bool = False):
|
|
903
|
+
"""Display palettes.
|
|
904
|
+
|
|
905
|
+
Args:
|
|
906
|
+
ids: One or more IDs (or slide names) of the images to show the palette of.
|
|
907
|
+
groups: A group name (if ids is set to only one image) or a list of group names corresponding to the list of ids provided.
|
|
908
|
+
versions: A version name (if ids is set to only one image) or a list of version names corresponding to the list of ids provided.
|
|
909
|
+
reference: If True, includes the reference distribution palette.
|
|
910
|
+
"""
|
|
911
|
+
|
|
912
|
+
palettes = []
|
|
913
|
+
|
|
914
|
+
if not isinstance(ids, list):
|
|
915
|
+
ids = [ids]
|
|
916
|
+
|
|
917
|
+
if groups is None:
|
|
918
|
+
groups = [None] * len(ids)
|
|
919
|
+
if versions is None:
|
|
920
|
+
versions = [None] * len(ids)
|
|
921
|
+
|
|
922
|
+
if not isinstance(groups, list):
|
|
923
|
+
groups = [groups]
|
|
924
|
+
if not isinstance(versions, list):
|
|
925
|
+
versions = [versions]
|
|
926
|
+
|
|
927
|
+
for i, img_id in enumerate(ids):
|
|
928
|
+
p = self.get_image_set(group=groups[i], version=versions[i]).get_stat(img_id, "Palette")
|
|
929
|
+
palettes.append(p)
|
|
930
|
+
|
|
931
|
+
if reference:
|
|
932
|
+
p = self.reference.get_stat("Palette")
|
|
933
|
+
palettes.append(p)
|
|
934
|
+
|
|
935
|
+
for p in palettes:
|
|
936
|
+
print(p.identifier)
|
|
937
|
+
p.display()
|
|
938
|
+
|
|
939
|
+
def gamut(
|
|
940
|
+
self,
|
|
941
|
+
plot_type: str = "oog_count",
|
|
942
|
+
threshold: float | None = None,
|
|
943
|
+
sort: bool = True,
|
|
944
|
+
sort_by: str | None = None,
|
|
945
|
+
clip_ids: bool = False,
|
|
946
|
+
hide_ids: bool = False,
|
|
947
|
+
save_path: str = None
|
|
948
|
+
) -> plotly.graph_objects.Figure:
|
|
949
|
+
"""Create gamut plot.
|
|
950
|
+
|
|
951
|
+
Options for ``plot_type``:
|
|
952
|
+
* "oog_count": Out-of-gamut color count.
|
|
953
|
+
* "ig_count": In-gamut color count.
|
|
954
|
+
|
|
955
|
+
Args:
|
|
956
|
+
plot_type: Gamut plot type ("oog_count", "ig_count").
|
|
957
|
+
threshold: Value for a horizontal threshold line drawn on the graph.
|
|
958
|
+
sort: Sort points. If True, set sort_by.
|
|
959
|
+
sort_by: Version name to sort by. If None and sort=True, the None version is used.
|
|
960
|
+
clip_ids: Clip IDs if they are too long.
|
|
961
|
+
hide_ids: Hide IDs.
|
|
962
|
+
save_path: Path to save the figure.
|
|
963
|
+
|
|
964
|
+
Returns:
|
|
965
|
+
The requested Plotly figure.
|
|
966
|
+
"""
|
|
967
|
+
|
|
968
|
+
if "gamut" not in self.computed:
|
|
969
|
+
raise Exception("Call compute(criteria=\"gamut\") first.")
|
|
970
|
+
|
|
971
|
+
plot_name = "gamut_" + plot_type
|
|
972
|
+
|
|
973
|
+
if plot_name not in self.plots:
|
|
974
|
+
traces = self.create_traces("GamutComparison", plot_type)
|
|
975
|
+
scatter = ScatterPlot(traces, yaxis_title=plot_labels[plot_name][0], title=plot_labels[plot_name][1])
|
|
976
|
+
self.plots[plot_name] = scatter
|
|
977
|
+
|
|
978
|
+
if save_path is not None:
|
|
979
|
+
self.plots[plot_name].save_plot(save_path=save_path, threshold=threshold, sort=sort, sort_by=sort_by, clip_ids=clip_ids, hide_ids=hide_ids)
|
|
980
|
+
|
|
981
|
+
return self.plots[plot_name].make_plot(threshold=threshold, sort=sort, sort_by=sort_by, clip_ids=clip_ids, hide_ids=hide_ids)
|
|
982
|
+
|
|
983
|
+
def background(
|
|
984
|
+
self,
|
|
985
|
+
threshold: float | None = None,
|
|
986
|
+
sort: bool = True,
|
|
987
|
+
sort_by: str | None = None,
|
|
988
|
+
clip_ids: bool = False,
|
|
989
|
+
hide_ids: bool = False,
|
|
990
|
+
save_path: str = None
|
|
991
|
+
) -> plotly.graph_objects.Figure:
|
|
992
|
+
"""Create background plot.
|
|
993
|
+
|
|
994
|
+
Args:
|
|
995
|
+
threshold: Value for a horizontal threshold line drawn on the graph.
|
|
996
|
+
sort: Sort points. If True, set sort_by.
|
|
997
|
+
sort_by: Version name to sort by. If None and sort=True, the None version is used.
|
|
998
|
+
clip_ids: Clip IDs if they are too long.
|
|
999
|
+
hide_ids: Hide IDs.
|
|
1000
|
+
save_path: Path to save the figure.
|
|
1001
|
+
|
|
1002
|
+
Returns:
|
|
1003
|
+
The requested Plotly figure.
|
|
1004
|
+
"""
|
|
1005
|
+
|
|
1006
|
+
if "background" not in self.computed:
|
|
1007
|
+
raise Exception("Call compute(criteria=\"background\") first.")
|
|
1008
|
+
|
|
1009
|
+
plot_name = "background"
|
|
1010
|
+
|
|
1011
|
+
if plot_name not in self.plots:
|
|
1012
|
+
traces = self.create_traces("BackgroundComparison", "dist")
|
|
1013
|
+
scatter = ScatterPlot(traces, yaxis_title=plot_labels[plot_name][0], title=plot_labels[plot_name][1])
|
|
1014
|
+
self.plots[plot_name] = scatter
|
|
1015
|
+
|
|
1016
|
+
if save_path is not None:
|
|
1017
|
+
self.plots[plot_name].save_plot(save_path=save_path, threshold=threshold, sort=sort, sort_by=sort_by, clip_ids=clip_ids, hide_ids=hide_ids)
|
|
1018
|
+
|
|
1019
|
+
return self.plots[plot_name].make_plot(threshold=threshold, sort=sort, sort_by=sort_by, clip_ids=clip_ids, hide_ids=hide_ids)
|
|
1020
|
+
|
|
1021
|
+
def contrast(
|
|
1022
|
+
self,
|
|
1023
|
+
threshold: float | None = None,
|
|
1024
|
+
sort: bool = True,
|
|
1025
|
+
sort_by: str | None = None,
|
|
1026
|
+
clip_ids: bool = False,
|
|
1027
|
+
hide_ids: bool = False,
|
|
1028
|
+
save_path: str = None
|
|
1029
|
+
) -> plotly.graph_objects.Figure:
|
|
1030
|
+
"""Create contrast change plot.
|
|
1031
|
+
|
|
1032
|
+
Args:
|
|
1033
|
+
threshold: Value for a horizontal threshold line drawn on the graph.
|
|
1034
|
+
sort: Sort points. If True, set sort_by.
|
|
1035
|
+
sort_by: Version name to sort by. If None and sort=True, the None version is used.
|
|
1036
|
+
clip_ids: Clip IDs if they are too long.
|
|
1037
|
+
hide_ids: Hide IDs.
|
|
1038
|
+
save_path: Path to save the figure.
|
|
1039
|
+
|
|
1040
|
+
Returns:
|
|
1041
|
+
The requested Plotly figure.
|
|
1042
|
+
"""
|
|
1043
|
+
|
|
1044
|
+
if "contrast" not in self.computed:
|
|
1045
|
+
raise Exception("Call compute(criteria=\"contrast\") first.")
|
|
1046
|
+
|
|
1047
|
+
plot_name = "contrast"
|
|
1048
|
+
|
|
1049
|
+
if plot_name not in self.plots:
|
|
1050
|
+
traces = self.create_traces("ContrastChange", "dist")
|
|
1051
|
+
scatter = ScatterPlot(traces, yaxis_title=plot_labels[plot_name][0], title=plot_labels[plot_name][1])
|
|
1052
|
+
self.plots[plot_name] = scatter
|
|
1053
|
+
|
|
1054
|
+
if save_path is not None:
|
|
1055
|
+
self.plots[plot_name].save_plot(save_path=save_path, threshold=threshold, sort=sort, sort_by=sort_by, clip_ids=clip_ids, hide_ids=hide_ids)
|
|
1056
|
+
|
|
1057
|
+
return self.plots[plot_name].make_plot(threshold=threshold, sort=sort, sort_by=sort_by, clip_ids=clip_ids, hide_ids=hide_ids)
|
|
1058
|
+
|
|
1059
|
+
def structure(
|
|
1060
|
+
self,
|
|
1061
|
+
threshold: float | None = None,
|
|
1062
|
+
sort: bool = True,
|
|
1063
|
+
sort_by: str | None = None,
|
|
1064
|
+
clip_ids: bool = False,
|
|
1065
|
+
hide_ids: bool = False,
|
|
1066
|
+
save_path: str = None
|
|
1067
|
+
) -> plotly.graph_objects.Figure:
|
|
1068
|
+
"""Create structure preservation plot.
|
|
1069
|
+
|
|
1070
|
+
Args:
|
|
1071
|
+
threshold: Value for a horizontal threshold line drawn on the graph.
|
|
1072
|
+
sort: Sort points. If True, set sort_by.
|
|
1073
|
+
sort_by: Version name to sort by. If None and sort=True, the None version is used.
|
|
1074
|
+
clip_ids: Clip IDs if they are too long.
|
|
1075
|
+
hide_ids: Hide IDs.
|
|
1076
|
+
save_path: Path to save the figure.
|
|
1077
|
+
|
|
1078
|
+
Returns:
|
|
1079
|
+
The requested Plotly figure.
|
|
1080
|
+
"""
|
|
1081
|
+
|
|
1082
|
+
if "structure" not in self.computed:
|
|
1083
|
+
raise Exception("Call compute(criteria=\"structure\") first.")
|
|
1084
|
+
|
|
1085
|
+
plot_name = "structure"
|
|
1086
|
+
|
|
1087
|
+
if plot_name not in self.plots:
|
|
1088
|
+
traces = self.create_traces("StructurePreservation", "dist")
|
|
1089
|
+
scatter = ScatterPlot(traces, yaxis_title=plot_labels[plot_name][0], title=plot_labels[plot_name][1])
|
|
1090
|
+
self.plots[plot_name] = scatter
|
|
1091
|
+
|
|
1092
|
+
if save_path is not None:
|
|
1093
|
+
self.plots[plot_name].save_plot(save_path=save_path, threshold=threshold, sort=sort, sort_by=sort_by, clip_ids=clip_ids, hide_ids=hide_ids)
|
|
1094
|
+
|
|
1095
|
+
return self.plots[plot_name].make_plot(threshold=threshold, sort=sort, sort_by=sort_by, clip_ids=clip_ids, hide_ids=hide_ids)
|
|
1096
|
+
|
|
1097
|
+
def original_version_check(self) -> dict[str, tuple[Subset, list[Subset]]]:
|
|
1098
|
+
"""Group image Subsets by version and check if each group has an original_version.
|
|
1099
|
+
|
|
1100
|
+
This check is needed for the contrast change and structure preservation assessments since both compare the stain normalized versions with the original_version.
|
|
1101
|
+
In the case of contrast change, we are interested in whether we had a contrast gain/loss compared to the original_version. In the case of structure preservation,
|
|
1102
|
+
we are interested in whether the stain normalized versions changed the morphology of the tissue compared to the original_version.
|
|
1103
|
+
|
|
1104
|
+
The check does not raise an Exception. It only prints a warning message.
|
|
1105
|
+
|
|
1106
|
+
Returns:
|
|
1107
|
+
Image Subsets organized as a dictionary. The keys are the group names. Each value is a tuple of the original_version Subset and a list of all other Subsets to compare with.
|
|
1108
|
+
"""
|
|
1109
|
+
|
|
1110
|
+
image_sets_grouped = {}
|
|
1111
|
+
|
|
1112
|
+
for image_set in self.image_sets:
|
|
1113
|
+
group = image_set.group
|
|
1114
|
+
original_version = image_set.original_version
|
|
1115
|
+
if group not in image_sets_grouped:
|
|
1116
|
+
image_sets_grouped[group] = (None, [])
|
|
1117
|
+
if original_version:
|
|
1118
|
+
image_sets_grouped[group][0] = image_set
|
|
1119
|
+
else:
|
|
1120
|
+
image_sets_grouped[group][1].append(image_set)
|
|
1121
|
+
|
|
1122
|
+
warning = []
|
|
1123
|
+
for group, (original_version, other_versions) in image_sets_grouped.items():
|
|
1124
|
+
if original_version is None and len(other_versions) > 1:
|
|
1125
|
+
warning.append(group)
|
|
1126
|
+
if len(warning) > 0:
|
|
1127
|
+
print("WARNING: You have one or more groups where a version hasn't been marked as original. When using add_images, one version should have original_version=True.")
|
|
1128
|
+
print(f"The groups without a version marked as original are: {warning}")
|
|
1129
|
+
print("Criteria that depend on an original version being marked will be skipped for the above groups.")
|
|
1130
|
+
|
|
1131
|
+
return image_sets_grouped
|
|
1132
|
+
|
|
1133
|
+
|
|
1134
|
+
def compute(self, criteria: list[str] | str = ["color_dist", "palette", "gamut", "background", "structure", "contrast"]):
|
|
1135
|
+
"""Compute the assessment on one or more criteria.
|
|
1136
|
+
|
|
1137
|
+
``criteria`` that can be computed:
|
|
1138
|
+
* "color_dist": Distance between color distributions.
|
|
1139
|
+
* "palette": Metrics on the color palettes.
|
|
1140
|
+
* "gamut": Counts of out-of-gamut and in-gamut colors.
|
|
1141
|
+
* "background": Distance between background colors.
|
|
1142
|
+
* "structure": Analysis of structural changes (e.g., morphology changes due to normalization).
|
|
1143
|
+
* "constrast": Analysis of color contrast changes.
|
|
1144
|
+
|
|
1145
|
+
Args:
|
|
1146
|
+
criteria: Criterion/critiera to compute. Can be a single str for one criterion or a list of str for multiple.
|
|
1147
|
+
"""
|
|
1148
|
+
|
|
1149
|
+
if isinstance(criteria, str):
|
|
1150
|
+
criteria = [criteria]
|
|
1151
|
+
|
|
1152
|
+
if self.reference is None:
|
|
1153
|
+
self.reference = ReferenceSet(self.assessment_dir)
|
|
1154
|
+
|
|
1155
|
+
if not self.reference_is_set:
|
|
1156
|
+
for image_set in self.image_sets:
|
|
1157
|
+
image_set.set_all_as_reference()
|
|
1158
|
+
self.reference_is_set = True
|
|
1159
|
+
|
|
1160
|
+
if "color_dist" in criteria:
|
|
1161
|
+
self.color_distance_compute()
|
|
1162
|
+
self.computed.add("color_dist")
|
|
1163
|
+
|
|
1164
|
+
if "palette" in criteria:
|
|
1165
|
+
self.palette_compute()
|
|
1166
|
+
self.computed.add("palette")
|
|
1167
|
+
|
|
1168
|
+
if "gamut" in criteria:
|
|
1169
|
+
self.gamut_compute()
|
|
1170
|
+
self.computed.add("gamut")
|
|
1171
|
+
|
|
1172
|
+
if "background" in criteria:
|
|
1173
|
+
self.background_compute()
|
|
1174
|
+
self.computed.add("background")
|
|
1175
|
+
|
|
1176
|
+
if "structure" in criteria:
|
|
1177
|
+
image_sets_grouped = self.original_version_check()
|
|
1178
|
+
self.structure_compute(image_sets_grouped)
|
|
1179
|
+
self.computed.add("structure")
|
|
1180
|
+
|
|
1181
|
+
if "contrast" in criteria:
|
|
1182
|
+
image_sets_grouped = self.original_version_check()
|
|
1183
|
+
self.contrast_compute(image_sets_grouped)
|
|
1184
|
+
self.computed.add("contrast")
|
|
1185
|
+
|
|
1186
|
+
print("Finished Assessment computation.")
|