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.
Files changed (36) hide show
  1. stainnormprogram/__about__.py +1 -0
  2. stainnormprogram/__init__.py +2 -0
  3. stainnormprogram/assessment/__init__.py +1 -0
  4. stainnormprogram/assessment/assessment.py +1186 -0
  5. stainnormprogram/assessment/background.py +211 -0
  6. stainnormprogram/assessment/color.py +770 -0
  7. stainnormprogram/assessment/contrast.py +252 -0
  8. stainnormprogram/assessment/gamut.py +407 -0
  9. stainnormprogram/assessment/palette.py +648 -0
  10. stainnormprogram/assessment/plot.py +759 -0
  11. stainnormprogram/assessment/structure.py +158 -0
  12. stainnormprogram/correction/__init__.py +1 -0
  13. stainnormprogram/correction/macenko.py +469 -0
  14. stainnormprogram/io/__init__.py +0 -0
  15. stainnormprogram/io/write_slide.py +119 -0
  16. stainnormprogram/library/TCGA-Manifest.txt +31 -0
  17. stainnormprogram/library/TCIA-Instructions.md +15 -0
  18. stainnormprogram/library/library.md +14 -0
  19. stainnormprogram/norm/__init__.py +1 -0
  20. stainnormprogram/norm/adjustments.py +88 -0
  21. stainnormprogram/norm/background.py +273 -0
  22. stainnormprogram/norm/normalization.py +126 -0
  23. stainnormprogram/norm/pipeline/__init__.py +0 -0
  24. stainnormprogram/norm/pipeline/macenko.py +302 -0
  25. stainnormprogram/norm/pipeline/pipeline.py +61 -0
  26. stainnormprogram/norm/style_estimation/__init__.py +0 -0
  27. stainnormprogram/norm/style_estimation/macenko.py +649 -0
  28. stainnormprogram/norm/subset.py +127 -0
  29. stainnormprogram/norm/translation/__init__.py +0 -0
  30. stainnormprogram/norm/translation/macenko.py +92 -0
  31. stainnormprogram/norm/utils.py +96 -0
  32. stainnormprogram/slide.py +1085 -0
  33. stainnormprogram-1.0.0.dist-info/METADATA +75 -0
  34. stainnormprogram-1.0.0.dist-info/RECORD +36 -0
  35. stainnormprogram-1.0.0.dist-info/WHEEL +4 -0
  36. stainnormprogram-1.0.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,648 @@
1
+ from stainnormprogram.slide import SlideImage, SlideImageCollection
2
+ import stainnormprogram.norm.background as background
3
+
4
+ import itertools
5
+ import statistics
6
+ from typing import Union
7
+ import os
8
+ import json
9
+
10
+ import fast_colorthief
11
+ import colour
12
+ import numpy as np
13
+ from sklearn.cluster import KMeans
14
+ import matplotlib
15
+
16
+ class Palette:
17
+
18
+ def __init__(
19
+ self,
20
+ slide: SlideImage | SlideImageCollection,
21
+ identifier: str | None = None,
22
+ tile_size: int = 32,
23
+ background_method: str = "hsv_threshold",
24
+ accept_perc: int = 10,
25
+ max_pixels: int = 1_000_000,
26
+ color_count: int = 10
27
+ ):
28
+ """Generate a color palette using fast_colorthief (Modified Median Cut Quantization).
29
+
30
+ Options for ``background_method``:
31
+ * "hsv_threshold": Threshold using saturation and value channels in HSV color space.
32
+
33
+ Args:
34
+ slide: The slide to compute the palette of.
35
+ identifier: An ID for this Palette. If None, the identifier of the slide will be used.
36
+ tile_size: Tile size to use.
37
+ background_method: Method for identifying the background/foreground.
38
+ accept_perc: Tiles with less than accept_perc percent of foreground are not used in the computation.
39
+ max_pixels: If the number of pixels used goes over max_pixels, stop the computation.
40
+ color_count: Number of colors for the palette.
41
+ """
42
+
43
+ self.slide = slide
44
+ self.identifier = identifier if identifier is not None else self.slide.identifier
45
+ self.background_method = background_method
46
+ self.accept_perc = accept_perc
47
+ self.color_count = color_count
48
+
49
+ # Tile size
50
+ if self.slide is not None:
51
+ self.slide.set_tile_size(tile_size)
52
+
53
+ self.num_pixels = 0
54
+ self.num_tiles = 0
55
+ self.max_pixels = max_pixels
56
+ self.tile_size = tile_size
57
+
58
+ self.palette = None
59
+
60
+ def save(self, output_dir: str):
61
+ """Save metric to disk.
62
+
63
+ Args:
64
+ output_dir: Folder path to output the metric to.
65
+ """
66
+
67
+ json_output_path = os.path.join(output_dir, "palette.json")
68
+ with open(json_output_path, "w") as file:
69
+ json.dump({
70
+ "identifier": self.identifier,
71
+ "background_method": self.background_method,
72
+ "accept_perc": self.accept_perc,
73
+ "color_count": self.color_count,
74
+ "tile_size": self.tile_size,
75
+ "num_pixels": self.num_pixels,
76
+ "num_tiles": self.num_tiles,
77
+ "max_pixels": self.max_pixels,
78
+ }, file)
79
+
80
+ palette_output_path = os.path.join(output_dir, "palette.npz")
81
+ np.savez(palette_output_path, palette=self.palette, allow_pickle=False)
82
+
83
+ @classmethod
84
+ def load(cls, input_dir: str) -> Palette:
85
+ """Load metric from disk.
86
+
87
+ Args:
88
+ input_dir: Folder path to load the metric from.
89
+
90
+ Returns:
91
+ A Palette.
92
+ """
93
+
94
+ json_input_path = os.path.join(input_dir, "palette.json")
95
+ with open(json_input_path, "r") as file:
96
+ json_data = json.load(file)
97
+
98
+ pl = cls(None, identifier=json_data["identifier"], tile_size=json_data["tile_size"], background_method=json_data["background_method"], accept_perc=json_data["accept_perc"], max_pixels=json_data["max_pixels"], color_count=json_data["color_count"])
99
+
100
+ palette_input_path = os.path.join(input_dir, "palette.npz")
101
+ with np.load(palette_input_path, allow_pickle=False) as data:
102
+ pl.palette = data["palette"]
103
+
104
+ return pl
105
+
106
+ def extract_pixels(self, tile: Tile):
107
+ """Extract foreground pixels from a tile for palette computation.
108
+
109
+ Args:
110
+ tile: The tile to extract pixels from.
111
+
112
+ Returns:
113
+ A (N,3) RGB np.uint8 array containing foreground pixels, or None if the tile was rejected for having less than accept_perc percent of foreground.
114
+ """
115
+
116
+ if self.background_method == "hsv_threshold":
117
+ fg_mask = background.hsv_threshold_foreground(tile).flatten()
118
+ else:
119
+ raise Exception(f"{self.background_method} is not a valid background method.")
120
+
121
+ n = np.sum(fg_mask).item()
122
+ if n / fg_mask.size * 100 < self.accept_perc:
123
+ return None
124
+
125
+ if self.num_tiles % 100 == 0:
126
+ print(f"Processed {self.num_tiles} tiles so far...")
127
+
128
+ rgb_tile = tile.rgb(as_uint8=True).reshape((-1,3))
129
+ rgb = rgb_tile[fg_mask, :]
130
+
131
+ return rgb # (N,3)
132
+
133
+ def compute(self):
134
+ """Compute the Palette.
135
+ """
136
+
137
+ print(f"Computing Palette for {self.identifier}...")
138
+
139
+ samples = []
140
+
141
+ self.slide.set_mode("random")
142
+ for tile, _ in self.slide:
143
+ pixels = self.extract_pixels(tile)
144
+ if pixels is not None:
145
+ samples.append(pixels)
146
+ self.num_tiles += 1
147
+ self.num_pixels += pixels.shape[0]
148
+ if self.num_pixels > self.max_pixels:
149
+ break
150
+
151
+ samples = np.concatenate(samples, axis=0) # (N,3)
152
+
153
+ # Make into a square image
154
+ img_dim = int(samples.shape[0] ** 0.5)
155
+ samples = samples[:img_dim*img_dim, :]
156
+ samples = samples.reshape((img_dim, img_dim, 3))
157
+ alpha = np.ones((img_dim, img_dim, 1)) * 255
158
+ samples = np.concatenate([samples, alpha], axis=-1)
159
+ samples = samples.astype(np.uint8)
160
+
161
+ print(f"Using {samples.shape[0]*samples.shape[1]} pixels to compute palette")
162
+
163
+ self.palette = fast_colorthief.get_palette(samples, color_count=self.color_count+1, quality=1)
164
+ self.palette = np.array(self.palette)
165
+
166
+ assert self.palette.shape == (self.color_count, 3), self.palette.shape
167
+
168
+ print("Finished computing Palette")
169
+
170
+ def display(self) -> tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]:
171
+ """Display the palette.
172
+
173
+ Returns:
174
+ A palette matplotlib figure.
175
+ """
176
+ return colour.plotting.plot_multi_colour_swatches(self.palette / 255.)
177
+
178
+ def get_palette(self, normalized: bool = False) -> np.ndarray:
179
+ """Get the palette as a np.ndarray.
180
+
181
+ Args:
182
+ normalized: If True, will divide by 255.
183
+
184
+ Returns:
185
+ A np.ndarray (np.uint8 RGB) representing the palette with shape (color_count, 3).
186
+ """
187
+ if normalized:
188
+ return self.palette / 255
189
+ return self.palette
190
+
191
+ class ReferencePalette:
192
+
193
+ def __init__(self, palettes: Palette | list[Palette], identifier: str | None = None, color_count: int = 10):
194
+ """A palette for the reference (which may represent multiple reference images).
195
+
196
+ Args:
197
+ palettes: One or more Palettes from the reference image(s).
198
+ identifier: An ID for this ReferencePalette. If None, only one Palette must be in palettes, and the ID from this Palette will be used.
199
+ color_count: Number of colors for the ReferencePalette.
200
+ """
201
+ self.palettes = palettes
202
+ self.color_count = color_count
203
+ if identifier is not None:
204
+ self.identifier = identifier
205
+ elif isinstance(palettes, Palette):
206
+ self.identifier = palettes.identifier
207
+ elif isinstance(palettes, list) and len(palettes) == 1:
208
+ self.identifier = palettes[0].identifier
209
+ else:
210
+ raise Exception
211
+
212
+ self.palette = None
213
+
214
+ def save(self, output_dir: str):
215
+ """Save metric to disk.
216
+
217
+ Args:
218
+ output_dir: Folder path to output the metric to.
219
+ """
220
+
221
+ palette_identifiers = []
222
+ for p in self.palettes:
223
+ palette_identifiers.append(p.identifier)
224
+
225
+ json_output_path = os.path.join(output_dir, "reference_palette.json")
226
+ with open(json_output_path, "w") as file:
227
+ json.dump({
228
+ "identifier": self.identifier,
229
+ "palette_identifiers": palette_identifiers,
230
+ "color_count": self.color_count,
231
+ }, file)
232
+
233
+ palette_output_path = os.path.join(output_dir, "reference_palette.npz")
234
+ np.savez(palette_output_path, palette=self.palette, allow_pickle=False)
235
+
236
+ @classmethod
237
+ def load(cls, input_dir: str) -> ReferencePalette:
238
+ """Load metric from disk.
239
+
240
+ Args:
241
+ input_dir: Folder path to load the metric from.
242
+
243
+ Returns:
244
+ A ReferencePalette.
245
+ """
246
+
247
+ json_input_path = os.path.join(input_dir, "reference_palette.json")
248
+ with open(json_input_path, "r") as file:
249
+ json_data = json.load(file)
250
+
251
+ rp = cls(json_data["palette_identifiers"], identifier=json_data["identifiers"], color_count=json_data["color_count"])
252
+
253
+ rp_input_path = os.path.join(input_dir, "reference_palette.npz")
254
+ with np.load(rp_input_path, allow_pickle=False) as data:
255
+ rp.palette = data["palette"]
256
+
257
+ return rp
258
+
259
+ def display(self) -> tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]:
260
+ """Display the palette.
261
+
262
+ Returns:
263
+ A palette matplotlib figure.
264
+ """
265
+ return colour.plotting.plot_multi_colour_swatches(self.palette / 255.)
266
+
267
+ def get_palette(self, normalized: bool = False) -> np.ndarray:
268
+ """Get the palette as a np.ndarray.
269
+
270
+ Args:
271
+ normalized: If True, will divide by 255.
272
+
273
+ Returns:
274
+ A np.ndarray (np.uint8 RGB) representing the palette with shape (color_count, 3).
275
+ """
276
+ if normalized:
277
+ return self.palette / 255
278
+ return self.palette
279
+
280
+ def compute(self):
281
+
282
+ if isinstance(self.palettes, Palette):
283
+ self.palette = self.palettes.get_palette()
284
+ return
285
+
286
+ if not isinstance(self.palettes, list):
287
+ raise Exception
288
+
289
+ # Accumulate all palette colors into array
290
+ all_colors = []
291
+ for pal in self.palettes:
292
+ all_colors.append(pal.get_palette(normalized=True))
293
+ all_colors = np.concatenate(all_colors, axis=0) # (N,3)
294
+
295
+ # Kmeans
296
+ km = KMeans(n_clusters=self.color_count)
297
+ km.fit(all_colors)
298
+
299
+ centers = km.cluster_centers_ # (color_count,3)
300
+ centers = np.clip(centers * 255, 0, 255).astype(np.uint8)
301
+
302
+ self.palette = centers
303
+
304
+ class PaletteEvaluation:
305
+
306
+ def __init__(self, palette: np.ndarray | Palette | ReferencePalette, stain: str = "HE", identifier: str | None = None):
307
+ """Evaluate a single palette.
308
+
309
+ This evaluation calculates the following metrics:
310
+ * Palette diversity (attribute: ``diversity``): Calculates the delta E between all pairs of colors. This is independent of the stain type.
311
+ * HE metrics
312
+ * H&E separability (HEsep; attribute ``pink_purple_separation``): How different the pinks are from the purples.
313
+ * Eosin diversity (Ediv; attribute ``pink_diversity``): How diverse the pink colors are.
314
+ * Hematoxylin diversity (Hdiv; atribute ``purple_diversity``): How diverse the purple colors are.
315
+
316
+ Other relevant attributes:
317
+ * ``pinks_idx``: The indices of the pink colors in the palette array.
318
+ * ``purples_idx``: The indices of the purple colors in the palette array.
319
+ * ``others_idx``: The indices of the other colors not identified as pink nor purple in the palette array.
320
+ * ``palette_colors_names``: The names of the colors in the palette array. Names supported can be found by calling ``get_reference_colors``.
321
+
322
+ Options for ``stain``:
323
+ * "HE": Hematoxylin and eosin.
324
+
325
+ Args:
326
+ palette: Array of RGB values (np.uint8) representing a color palette; shape should be (N,3). Or a Palette/ReferencePalette.
327
+ stain: The stain type.
328
+ identifier: The ID for this PaletteEvaluation. If None, the ID from the Palette or ReferencePalette is taken.
329
+ """
330
+ if identifier is not None:
331
+ self.identifier = identifier
332
+ elif isinstance(palette, (Palette, ReferencePalette)):
333
+ self.identifier = palette.identifier
334
+ else:
335
+ Exception("Set an identifier.")
336
+
337
+ if isinstance(palette, np.ndarray):
338
+ self.palette_sRGB = palette / 255
339
+ elif isinstance(palette, (Palette, ReferencePalette)):
340
+ self.palette_sRGB = palette.get_palette(normalized=True)
341
+ else:
342
+ raise Exception("palette must be a np.ndarray, Palette, or ReferencePalette.")
343
+
344
+ self.palette_Lab = self.sRGB_to_Lab(self.palette_sRGB)
345
+ self.reference_colors, self.reference_colors_names = self.get_reference_colors()
346
+ self.stain = stain
347
+ self.pink_purple_separation = None
348
+ self.pink_diversity = None
349
+ self.purple_diversity = None
350
+ self.pinks_idx = None
351
+ self.purples_idx = None
352
+ self.others_idx = None
353
+ self.palette_colors_names = None
354
+ self.diversity = None
355
+
356
+ def save(self, output_dir: str):
357
+ """Save metric to disk.
358
+
359
+ Args:
360
+ output_dir: Folder path to output the metric to.
361
+ """
362
+
363
+ json_output_path = os.path.join(output_dir, "palette_evaluation.json")
364
+ with open(json_output_path, "w") as file:
365
+ json.dump({
366
+ "identifier": self.identifier,
367
+ "stain": self.stain,
368
+ "pink_purple_separation": self.pink_purple_separation,
369
+ "pink_diversity": self.pink_diversity,
370
+ "purple_diversity": self.purple_diversity,
371
+ "pinks_idx": self.pinks_idx,
372
+ "purples_idx": self.purples_idx,
373
+ "others_idx": self.others_idx,
374
+ "palette_colors_names": self.palette_colors_names,
375
+ "diversity": self.diversity,
376
+ }, file)
377
+
378
+ @classmethod
379
+ def load(cls, input_dir: str, palette: np.ndarray | Palette | ReferencePalette | None) -> PaletteEvaluation:
380
+ """Load metric from disk.
381
+
382
+ Args:
383
+ input_dir: Folder path to load the metric from.
384
+ palette: The palette. Can be None if computing the PaletteEvaluation in the future is not desired and the object is just being used to store the already computed metrics.
385
+
386
+ Returns:
387
+ A PaletteEvaluation.
388
+ """
389
+
390
+ json_input_path = os.path.join(input_dir, "palette_evaluation.json")
391
+ with open(json_input_path, "r") as file:
392
+ json_data = json.load(file)
393
+
394
+ pe = cls(palette, stain=json_data["stain"], identifier=json_data["identifier"])
395
+ pe.pink_purple_separation = json_data["pink_purple_separation"]
396
+ pe.pink_diversity = json_data["pink_diversity"]
397
+ pe.purple_diversity = json_data["purple_diversity"]
398
+ pe.pinks_idx = json_data["pinks_idx"]
399
+ pe.purples_idx = json_data["purples_idx"]
400
+ pe.others_idx = json_data["others_idx"]
401
+ pe.palette_colors_names = json_data["palette_colors_names"]
402
+ pe.diversity = json_data["diversity"]
403
+
404
+ return pe
405
+
406
+ def get_reference_colors(self) -> tuple[np.ndarray, list[str]]:
407
+ """Get the reference colors used to identify the "names" of the colors in the palette.
408
+
409
+ Returns:
410
+ A tuple containing (the reference color RGB values as a np.ndarray normalized by 255., the reference color names as a list of str).
411
+ """
412
+ reference_colors = np.array([
413
+ [255, 0, 0], # red
414
+ [255, 192, 203], # pink
415
+ [128, 0, 128], # purple
416
+ [0, 0, 255], # blue
417
+ [255, 125, 0], # orange
418
+ [0, 255, 255], # aqua
419
+ [0, 0, 0] # black
420
+ ]) / 255.
421
+ reference_colors_names = [
422
+ "red",
423
+ "pink",
424
+ "purple",
425
+ "blue",
426
+ "orange",
427
+ "aqua",
428
+ "black"
429
+ ]
430
+ return self.sRGB_to_Lab(reference_colors), reference_colors_names
431
+
432
+ def sRGB_to_Lab(self, sRGB: np.ndarray) -> np.ndarray:
433
+ """Convert sRGB values into CIELAB.
434
+
435
+ Args:
436
+ sRGB: An array of sRGB values.
437
+
438
+ Returns:
439
+ A np.ndarray of the colors converted to CIELAB.
440
+ """
441
+ return colour.XYZ_to_Lab(colour.sRGB_to_XYZ(sRGB))
442
+
443
+ def palette_diversity(self):
444
+ """Compute palette diversity. Calculates the delta E between all pairs of colors.
445
+ """
446
+ delta_Es = []
447
+ for c1, c2 in itertools.combinations(self.palette_Lab, 2):
448
+
449
+ dE = colour.delta_E(c1, c2, method="CIE 2000")
450
+ delta_Es.append(dE)
451
+
452
+ self.diversity = statistics.mean(delta_Es)
453
+
454
+ def palette_he(self):
455
+ """Compute palette "HE-ness."
456
+ """
457
+
458
+ # Sort palette into purples, pinks, and others
459
+ palette_colors_names = []
460
+ for i in range(self.palette_Lab.shape[0]):
461
+ deltas_with_references = colour.delta_E(self.reference_colors, self.palette_Lab[i], method="CIE 2000")
462
+ color_name = self.reference_colors_names[np.argmin(deltas_with_references)]
463
+ palette_colors_names.append(color_name)
464
+
465
+ pinks_idx = []
466
+ purples_idx = []
467
+ others_idx = []
468
+ for i, color_name in enumerate(palette_colors_names):
469
+ if color_name in ["purple", "blue"]:
470
+ purples_idx.append(i)
471
+ elif color_name in ["pink", "red"]:
472
+ pinks_idx.append(i)
473
+ else:
474
+ others_idx.append(i)
475
+
476
+ dEs = []
477
+ for pink_idx, purple_idx in itertools.product(pinks_idx, purples_idx):
478
+ dE = colour.delta_E(self.palette_Lab[pink_idx], self.palette_Lab[purple_idx], method="CIE 2000")
479
+ dEs.append(dE)
480
+
481
+ if len(dEs) == 0:
482
+ pink_purple_separation = 0
483
+ else:
484
+ pink_purple_separation = statistics.mean(dEs)
485
+
486
+ dEs = []
487
+ for idx1, idx2 in itertools.combinations(pinks_idx, 2):
488
+ dE = colour.delta_E(self.palette_Lab[idx1], self.palette_Lab[idx2], method="CIE 2000")
489
+ dEs.append(dE)
490
+
491
+ if len(dEs) == 0:
492
+ pink_diversity = 0
493
+ else:
494
+ pink_diversity = statistics.mean(dEs)
495
+
496
+ dEs = []
497
+ for idx1, idx2 in itertools.combinations(purples_idx, 2):
498
+ dE = colour.delta_E(self.palette_Lab[idx1], self.palette_Lab[idx2], method="CIE 2000")
499
+ dEs.append(dE)
500
+
501
+ if len(dEs) == 0:
502
+ purple_diversity = 0
503
+ else:
504
+ purple_diversity = statistics.mean(dEs)
505
+
506
+ self.pink_purple_separation, self.pink_diversity, self.purple_diversity, self.pinks_idx, self.purples_idx, self.others_idx, self.palette_colors_names = pink_purple_separation, pink_diversity, purple_diversity, pinks_idx, purples_idx, others_idx, palette_colors_names
507
+
508
+ def compute(self):
509
+ """Compute the PaletteEvaluation.
510
+ """
511
+
512
+ self.palette_diversity()
513
+ if self.stain == "HE":
514
+ self.palette_he()
515
+
516
+ class PaletteComparison:
517
+
518
+ def __init__(self, reference: PaletteEvaluation, query: PaletteEvaluation, method: str = "pairwise"):
519
+ """Compare two palettes.
520
+
521
+ Options for ``method``:
522
+ * "pairwise": Compare the two palettes using pairwise comparison.
523
+ * "dominant_he": Compare the two palettes using only their dominant pink color and dominant purple color. Assumes that the palettes are ordered such that the more dominant colors have lower index values.
524
+
525
+ Args:
526
+ reference: Reference PaletteEvaluation.
527
+ query: Query PaletteEvaluation.
528
+ method: Method of palette comparison.
529
+ """
530
+ self.query = query
531
+ self.reference = reference
532
+ self.method = method
533
+
534
+ if len(self.query.palette_Lab) != len(self.reference.palette_Lab):
535
+ raise Exception("The number of colors are different between the query and reference palettes.")
536
+
537
+ self.pairwise_score = None
538
+
539
+ # HE
540
+ self.pink_dE = None
541
+ self.purple_dE = None
542
+
543
+ def save(self, output_dir: str):
544
+ """Save metric to disk.
545
+
546
+ Args:
547
+ output_dir: Folder path to output the metric to.
548
+ """
549
+
550
+ json_output_path = os.path.join(output_dir, "palette_comparison.json")
551
+ with open(json_output_path, "w") as file:
552
+ json.dump({
553
+ "reference": self.reference.identifier,
554
+ "query": self.query.identifier,
555
+ "method": self.method,
556
+ "pairwise_score": self.pairwise_score,
557
+ "pink_dE": self.pink_dE,
558
+ "purple_dE": self.purple_dE,
559
+ }, file)
560
+
561
+ @classmethod
562
+ def load(cls, input_dir: str) -> PaletteComparison:
563
+ """Load metric from disk.
564
+
565
+ Args:
566
+ input_dir: Folder path to load the metric from.
567
+
568
+ Returns:
569
+ A PaletteComparison.
570
+ """
571
+
572
+ json_input_path = os.path.join(input_dir, "palette_comparison.json")
573
+ with open(json_input_path, "r") as file:
574
+ json_data = json.load(file)
575
+
576
+ pc = cls(json_data["reference"], json_data["query"])
577
+ pc.dist = json_data["dist"]
578
+
579
+ return pc
580
+
581
+ def pairwise(self):
582
+ """Compute a pairwise comparison between the query and reference palettes.
583
+ """
584
+
585
+ num_colors = len(self.query.palette_Lab)
586
+ prods = list(itertools.product(list(range(num_colors)), list(range(num_colors))))
587
+
588
+ min_dEs = []
589
+ for i in range(0, num_colors * num_colors, num_colors):
590
+ min_dE = 1000
591
+ for q_idx, r_idx in prods[i:i+num_colors]:
592
+ dE = colour.delta_E(self.query.palette_Lab[q_idx], self.reference.palette_Lab[r_idx], method="CIE 2000")
593
+ if dE < min_dE:
594
+ min_dE = dE
595
+ min_dEs.append(min_dE)
596
+
597
+ self.pairwise_score = statistics.mean(min_dEs)
598
+
599
+ def get_val(self, val_type: str) -> float:
600
+ """Get a metric/statistic.
601
+
602
+ Options for ``val_type``:
603
+ * "compare": Pairwise comparison, independent of the stain type.
604
+ * "Hdiv": Hematoxylin diversity.
605
+ * "Ediv": Eosin diversity.
606
+ * "HEsep": Hematoxylin and eosin separability.
607
+
608
+ Args:
609
+ val_type: The name of the metric/statistic to get.
610
+
611
+ Returns:
612
+ The requested metric/statistic.
613
+ """
614
+ if val_type == "compare":
615
+ return self.pairwise_score
616
+ elif val_type == "Hdiv":
617
+ return self.query.purple_diversity
618
+ elif val_type == "Ediv":
619
+ return self.query.pink_diversity
620
+ elif val_type == "HEsep":
621
+ return self.query.pink_purple_separation
622
+ else:
623
+ raise Exception(f"{val_type} is not a valid metric.")
624
+
625
+ def dominant_he(self):
626
+ """Compute the difference between the query and reference palettes by comparing their dominant pink color with each other and their dominant purple color with each other.
627
+ """
628
+
629
+ purple_0_idx = self.query.purples_idx[0]
630
+ purple_1_idx = self.reference.purples_idx[1]
631
+
632
+ pink_0_idx = self.query.pinks_idx[0]
633
+ pink_1_idx = self.reference.pinks_idx[1]
634
+
635
+ self.pink_dE = colour.delta_E(self.query.palette_Lab[pink_0_idx], self.reference.palette_Lab[pink_1_idx])
636
+ self.purple_dE = colour.delta_E(self.query.palette_Lab[purple_0_idx], self.reference.palette_Lab[purple_1_idx])
637
+
638
+ def compute(self):
639
+ """Compute the PaletteComparison.
640
+ """
641
+
642
+ if self.method == "pairwise":
643
+ self.pairwise()
644
+ elif self.method == "dominant_he":
645
+ self.dominant_he()
646
+ else:
647
+ raise Exception(f"{self.method} is not a valid method for computing the PaletteComparison.")
648
+