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,770 @@
1
+ import stainnormprogram.norm.background as background
2
+ from stainnormprogram.slide import SlideImage, SlideImageCollection
3
+
4
+ import json
5
+ import os
6
+
7
+ import numpy as np
8
+ from scipy.ndimage import gaussian_filter
9
+
10
+ class ColorHistogramEdges:
11
+
12
+ def __init__(self,
13
+ rgb_bins: tuple[int, int, int] = (51,51,51),
14
+ h_bins: int = 200,
15
+ s_bins: int = 100,
16
+ v_bins: int = 100,
17
+ oklab_bins: tuple[int, int, int] = (200,160,160),
18
+ oklab_a_range: tuple[float, float] = (-0.4,0.4),
19
+ oklab_b_range: tuple[float, float] = (-0.4,0.4),
20
+ uv_bins: tuple[int, int] = (100,100),
21
+ uv_u_range: tuple[float, float] = (0.0,0.6),
22
+ uv_v_range: tuple[float, float] = (0.0,0.6),
23
+ ):
24
+ """Shared store for bins and edges of color histograms.
25
+
26
+ Args:
27
+ rgb_bins: (red, green, blue) bin count.
28
+ h_bins: Number of hue (HSV) bins.
29
+ s_bins: Number of saturation (HSV) bins.
30
+ v_bins: Number of value/brightness (HSV) bins.
31
+ oklab_bins: OKLAB (l, a, b) bin count.
32
+ oklab_a_range: OKLAB a range.
33
+ oklab_b_range: OKLAB b range.
34
+ uv_bins: Number of CIE 1976 UCS chromaticity u'v' bins as (u' bins, v' bins).
35
+ uv_u_range: u'v' u range.
36
+ uv_v_range: u'v' v range.
37
+ """
38
+
39
+ self.rgb_bins = rgb_bins
40
+ self.h_bins = h_bins
41
+ self.s_bins = s_bins
42
+ self.v_bins = v_bins
43
+ self.oklab_bins = oklab_bins
44
+ self.oklab_a_range = oklab_a_range
45
+ self.oklab_b_range = oklab_b_range
46
+ self.uv_bins = uv_bins
47
+ self.uv_u_range = uv_u_range
48
+ self.uv_v_range = uv_v_range
49
+
50
+ self.hsv_h_hist_edges = np.linspace(0, 1, num=self.h_bins+1)
51
+ self.hsv_s_hist_edges = np.linspace(0, 1, num=self.s_bins+1)
52
+ self.hsv_v_hist_edges = np.linspace(0, 1, num=self.v_bins+1)
53
+ self.rgb_r_hist_edges = np.linspace(0, 255, num=self.rgb_bins[0]+1)
54
+ self.rgb_g_hist_edges = np.linspace(0, 255, num=self.rgb_bins[1]+1)
55
+ self.rgb_b_hist_edges = np.linspace(0, 255, num=self.rgb_bins[2]+1)
56
+ self.oklab_l_hist_edges = np.linspace(0, 1, num=self.oklab_bins[0]+1)
57
+ self.oklab_a_hist_edges = np.linspace(self.oklab_a_range[0], self.oklab_a_range[1], num=self.oklab_bins[1]+1)
58
+ self.oklab_b_hist_edges = np.linspace(self.oklab_b_range[0], self.oklab_b_range[1], num=self.oklab_bins[2]+1)
59
+ self.uv_u_hist_edges = np.linspace(self.uv_u_range[0], self.uv_u_range[1], num=self.uv_bins[0]+1)
60
+ self.uv_v_hist_edges = np.linspace(self.uv_v_range[0], self.uv_v_range[1], num=self.uv_bins[1]+1)
61
+
62
+ def __eq__(self, other: ColorHistogramEdges) -> bool:
63
+ """Compare the equality between this and other ColorHistogramEdges objects.
64
+
65
+ Args:
66
+ other: The other ColorHistogramEdges object to compare with.
67
+
68
+ Returns:
69
+ A bool indicating whether the two objects have the same edges or not.
70
+ """
71
+
72
+ return self.rgb_bins == other.rgb_bins and self.h_bins == other.h_bins \
73
+ and self.s_bins == other.s_bins and self.v_bins == other.v_bins \
74
+ and self.oklab_bins == other.oklab_bins and self.oklab_a_range == other.oklab_a_range \
75
+ and self.oklab_b_range == other.oklab_b_range and self.uv_bins == other.uv_bins \
76
+ and self.uv_u_range == other.uv_u_range and self.uv_v_range == other.uv_v_range \
77
+ and np.array_equal(self.hsv_h_hist_edges, other.hsv_h_hist_edges) and np.array_equal(self.hsv_s_hist_edges, other.hsv_s_hist_edges) \
78
+ and np.array_equal(self.hsv_v_hist_edges, other.hsv_v_hist_edges) and np.array_equal(self.rgb_r_hist_edges, other.rgb_r_hist_edges) \
79
+ and np.array_equal(self.rgb_g_hist_edges, other.rgb_g_hist_edges) and np.array_equal(self.rgb_b_hist_edges, other.rgb_b_hist_edges) \
80
+ and np.array_equal(self.oklab_l_hist_edges, other.oklab_l_hist_edges) and np.array_equal(self.oklab_a_hist_edges, other.oklab_a_hist_edges) \
81
+ and np.array_equal(self.oklab_b_hist_edges, other.oklab_b_hist_edges) and np.array_equal(self.uv_u_hist_edges, other.uv_u_hist_edges) \
82
+ and np.array_equal(self.uv_v_hist_edges, other.uv_v_hist_edges)
83
+
84
+ def save(self, output_dir: str):
85
+ """Save metric to disk.
86
+
87
+ Args:
88
+ output_dir: Folder path to output the metric to.
89
+ """
90
+
91
+ edges_output_path = os.path.join(output_dir, "color_histogram_edges.npz")
92
+ np.savez(edges_output_path, hsv_h_hist_edges=self.hsv_h_hist_edges,
93
+ hsv_s_hist_edges=self.hsv_s_hist_edges, hsv_v_hist_edges=self.hsv_v_hist_edges, rgb_r_hist_edges=self.rgb_r_hist_edges,
94
+ rgb_g_hist_edges=self.rgb_g_hist_edges, rgb_b_hist_edges=self.rgb_b_hist_edges, oklab_l_hist_edges=self.oklab_l_hist_edges,
95
+ oklab_a_hist_edges=self.oklab_a_hist_edges, oklab_b_hist_edges=self.oklab_b_hist_edges, uv_u_hist_edges=self.uv_u_hist_edges,
96
+ uv_v_hist_edges=self.uv_v_hist_edges, allow_pickle=False
97
+ )
98
+
99
+ json_output_path = os.path.join(output_dir, "color_histogram_edges.json")
100
+ with open(json_output_path, "w") as file:
101
+ json.dump({
102
+ "rgb_bins": self.rgb_bins,
103
+ "h_bins": self.h_bins,
104
+ "s_bins": self.s_bins,
105
+ "v_bins": self.v_bins,
106
+ "oklab_bins": self.oklab_bins,
107
+ "oklab_a_range": self.oklab_a_range,
108
+ "oklab_b_range": self.oklab_b_range,
109
+ "uv_bins": self.uv_bins,
110
+ "uv_u_range": self.uv_u_range,
111
+ "uv_v_range": self.uv_v_range,
112
+ }, file)
113
+
114
+ @classmethod
115
+ def load(cls, input_dir: str) -> ColorHistogramEdges:
116
+ """Load metric from disk.
117
+
118
+ Args:
119
+ input_dir: Folder path to load the metric from.
120
+
121
+ Returns:
122
+ A ColorHistogramEdges.
123
+ """
124
+
125
+ json_input_path = os.path.join(input_dir, "color_histogram_edges.json")
126
+ if not os.path.exists(json_input_path):
127
+ return None
128
+ with open(json_input_path, "r") as file:
129
+ json_data = json.load(file)
130
+
131
+ edges = cls(rgb_bins=json_data["rgb_bins"],
132
+ h_bins=json_data["h_bins"],
133
+ s_bins=json_data["s_bins"],
134
+ v_bins=json_data["v_bins"],
135
+ oklab_bins=json_data["oklab_bins"],
136
+ oklab_a_range=json_data["oklab_a_range"],
137
+ oklab_b_range=json_data["oklab_b_range"],
138
+ uv_bins=json_data["uv_bins"],
139
+ uv_u_range=json_data["uv_u_range"],
140
+ uv_v_range=json_data["uv_v_range"]
141
+ )
142
+
143
+ edges_input_path = os.path.join(input_dir, "color_histogram_edges.npz")
144
+ if not os.path.exists(edges_input_path):
145
+ return None
146
+ with np.load(edges_input_path, allow_pickle=False) as data:
147
+ edges.hsv_h_hist_edges, edges.hsv_s_hist_edges, edges.hsv_v_hist_edges, edges.rgb_r_hist_edges, edges.rgb_g_hist_edges, edges.rgb_b_hist_edges, edges.oklab_l_hist_edges, edges.oklab_a_hist_edges, edges.oklab_b_hist_edges, edges.uv_u_hist_edges, edges.uv_v_hist_edges = \
148
+ data["hsv_h_hist_edges"], data["hsv_s_hist_edges"], data["hsv_v_hist_edges"], data["rgb_r_hist_edges"], data["rgb_g_hist_edges"], data["rgb_b_hist_edges"], data["oklab_l_hist_edges"], data["oklab_a_hist_edges"], data["oklab_b_hist_edges"], data["uv_u_hist_edges"], data["uv_v_hist_edges"]
149
+
150
+ return edges
151
+
152
+ class ColorSample:
153
+
154
+ def __init__(self,
155
+ slide: SlideImage | SlideImageCollection,
156
+ edges: ColorHistogramEdges,
157
+ background_method: str = "hsv_threshold",
158
+ sampling_method: str = "random",
159
+ max_pixels: int = 10_000_000,
160
+ tile_size: int = 256,
161
+ identifier: int | None = None,
162
+ ):
163
+ """ColorSample creates color histograms of the slide.
164
+
165
+ Options for ``background_method``:
166
+ * "hsv_threshold": Threshold using saturation and value channels in HSV color space.
167
+
168
+ Options for ``sampling_method``:
169
+ * "sequential": Row major order.
170
+ * "random": Random selection from a grid.
171
+ * "custom": Custom order. You should specify this custom order by calling set_custom_iter_locs on your slide before constructing the ColorSample.
172
+
173
+ Args:
174
+ slide: The slide to compute the ColorSample of.
175
+ edges: Histogram edges.
176
+ background_method: Method for identifying the background/foreground.
177
+ sampling_method: Method for sampling tiles from the image.
178
+ max_pixels: If the number of pixels used goes over max_pixels, stop the computation.
179
+ tile_size: Tile size to use.
180
+ identifier: An ID for this ColorSample. If None, the identifier of the slide will be used.
181
+ """
182
+
183
+ self.slide = slide
184
+ self.edges = edges
185
+ self.background_method = background_method
186
+ self.sampling_method = sampling_method
187
+ self.max_pixels = max_pixels
188
+ self.identifier = identifier if identifier is not None else self.slide.identifier
189
+ self.tile_size = tile_size
190
+
191
+ # Setup histograms
192
+ self.rgb_hist = np.zeros(self.edges.rgb_bins, dtype=np.uint64)
193
+ self.h_hist = np.zeros((self.edges.h_bins,), dtype=np.uint64)
194
+ self.s_hist = np.zeros((self.edges.s_bins,), dtype=np.uint64)
195
+ self.v_hist = np.zeros((self.edges.v_bins,), dtype=np.uint64)
196
+ self.oklab_hist = np.zeros(self.edges.oklab_bins, dtype=np.uint64)
197
+ self.uv_hist = np.zeros(self.edges.uv_bins, dtype=np.uint64)
198
+
199
+ # Counters
200
+ self.num_tiles = 0
201
+ self.num_pixels = 0
202
+
203
+ # Tile size
204
+ if slide is not None:
205
+ self.slide.set_tile_size(self.tile_size)
206
+
207
+ def save(self, output_dir: str, include_edges: bool = True):
208
+ """Save metric to disk.
209
+
210
+ Args:
211
+ output_dir: Folder path to output the metric to.
212
+ include_edges: Save the histogram edges as well (I recommend you set this to False if you already have the edges saved somewhere else to avoid wasting disk memory).
213
+ """
214
+
215
+ json_output_path = os.path.join(output_dir, "color_sample.json")
216
+ with open(json_output_path, "w") as file:
217
+ json.dump({
218
+ "background_method": self.background_method,
219
+ "sampling_method": self.sampling_method,
220
+ "max_pixels": self.max_pixels,
221
+ "identifier": self.identifier,
222
+ "num_tiles": self.num_tiles,
223
+ "num_pixels": self.num_pixels,
224
+ "tile_size": self.tile_size,
225
+ }, file)
226
+
227
+ hist_output_path = os.path.join(output_dir, "color_sample_histograms.npz")
228
+ np.savez(hist_output_path, rgb_hist=self.rgb_hist, h_hist=self.h_hist, s_hist=self.s_hist, v_hist=self.v_hist, oklab_hist=self.oklab_hist, uv_hist=self.uv_hist, allow_pickle=False)
229
+
230
+ if include_edges:
231
+ self.edges.save(output_dir)
232
+
233
+ @classmethod
234
+ def load(cls, input_dir: str, edges: ColorHistogramEdges | None = None) -> ColorSample:
235
+ """Load metric from disk.
236
+
237
+ Args:
238
+ input_dir: Folder path to load the metric from.
239
+ edges: Color histogram edges. If None, the edges will be loaded from input_dir.
240
+
241
+ Returns:
242
+ A ColorSample.
243
+ """
244
+
245
+ json_input_path = os.path.join(input_dir, "color_sample.json")
246
+ with open(json_input_path, "r") as file:
247
+ json_data = json.load(file)
248
+
249
+ if edges is None:
250
+ edges = ColorHistogramEdges.load(input_dir)
251
+
252
+ cs = cls(None, edges, background_method=json_data["background_method"], sampling_method=json_data["sampling_method"], max_pixels=json_data["max_pixels"], tile_size=json_data["tile_size"], identifier=json_data["identifier"])
253
+
254
+ hist_input_path = os.path.join(input_dir, "color_sample_histograms.npz")
255
+ with np.load(hist_input_path, allow_pickle=False) as data:
256
+ cs.rgb_hist, cs.h_hist, cs.s_hist, cs.v_hist, cs.oklab_hist, cs.uv_hist = data["rgb_hist"], data["h_hist"], data["s_hist"], data["v_hist"], data["oklab_hist"], data["uv_hist"]
257
+
258
+ cs.num_tiles = json_data["num_tiles"]
259
+ cs.num_pixels = json_data["num_pixels"]
260
+
261
+ return cs
262
+
263
+ def get_h_hist(self, density: bool = False) -> np.ndarray:
264
+ """Get the hue (HSV) histogram.
265
+
266
+ Args:
267
+ density: Return as a density.
268
+
269
+ Returns:
270
+ A np.ndarray for the histogram.
271
+ """
272
+ if density:
273
+ out = self.h_hist / np.sum(self.h_hist)
274
+ return out
275
+ return self.h_hist
276
+
277
+ def get_s_hist(self, density: bool = False) -> np.ndarray:
278
+ """Get the saturation (HSV) histogram.
279
+
280
+ Args:
281
+ density: Return as a density.
282
+
283
+ Returns:
284
+ A np.ndarray for the histogram.
285
+ """
286
+ if density:
287
+ out = self.s_hist / np.sum(self.s_hist)
288
+ return out
289
+ return self.s_hist
290
+
291
+ def get_v_hist(self, density: bool = False) -> np.ndarray:
292
+ """Get the value (HSV) histogram.
293
+
294
+ Args:
295
+ density: Return as a density.
296
+
297
+ Returns:
298
+ A np.ndarray for the histogram.
299
+ """
300
+ if density:
301
+ out = self.v_hist / np.sum(self.v_hist)
302
+ return out
303
+ return self.v_hist
304
+
305
+ def get_rgb_hist(self, density: bool = False) -> np.ndarray:
306
+ """Get the RGB histogram.
307
+
308
+ Args:
309
+ density: Return as a density.
310
+
311
+ Returns:
312
+ A np.ndarray for the histogram.
313
+ """
314
+ if density:
315
+ out = self.rgb_hist / np.sum(self.rgb_hist)
316
+ return out
317
+ return self.rgb_hist
318
+
319
+ def get_oklab_hist(self, density: bool = False) -> np.ndarray:
320
+ """Get the OKLAB histogram.
321
+
322
+ Args:
323
+ density: Return as a density.
324
+
325
+ Returns:
326
+ A np.ndarray for the histogram.
327
+ """
328
+ if density:
329
+ out = self.oklab_hist / np.sum(self.oklab_hist)
330
+ return out
331
+ return self.oklab_hist
332
+
333
+ def get_uv_hist(self, density: bool = False) -> np.ndarray:
334
+ """Get the u'v' histogram.
335
+
336
+ Args:
337
+ density: Return as a density.
338
+
339
+ Returns:
340
+ A np.ndarray for the histogram.
341
+ """
342
+ if density:
343
+ out = self.uv_hist / np.sum(self.uv_hist)
344
+ return out
345
+ return self.uv_hist
346
+
347
+ def compute_tile(self, tile: Tile):
348
+ """Compute the histogram bar counts from a tile.
349
+
350
+ Args:
351
+ tile: The tile to compute counts from.
352
+ """
353
+
354
+ if self.background_method == "hsv_threshold":
355
+ fg_mask = background.hsv_threshold_foreground(tile).flatten()
356
+ else:
357
+ raise Exception(f"Background method {self.background_method} not supported.")
358
+
359
+ n = np.sum(fg_mask).item()
360
+ if n == 0:
361
+ return
362
+
363
+ if self.num_tiles % 10 == 0:
364
+ print(f"Processed {self.num_tiles} tiles so far...")
365
+
366
+ rgb_tile = tile.rgb(as_uint8=True).reshape((-1,3))
367
+ hsv_tile = tile.hsv().reshape((-1,3))
368
+ oklab_tile = tile.oklab().reshape((-1,3))
369
+ uv_u_tile, uv_v_tile = tile.u_prime_v_prime()
370
+ uv_u_tile = uv_u_tile.flatten()
371
+ uv_v_tile = uv_v_tile.flatten()
372
+
373
+ rgb = rgb_tile[fg_mask, :]
374
+ hsv_h = hsv_tile[:,0][fg_mask]
375
+ hsv_s = hsv_tile[:,1][fg_mask]
376
+ hsv_v = hsv_tile[:,2][fg_mask]
377
+ oklab = oklab_tile[fg_mask, :]
378
+ uv_u = uv_u_tile[fg_mask]
379
+ uv_v = uv_v_tile[fg_mask]
380
+ uv_not_nan = ~(np.isnan(uv_u) | np.isnan(uv_v))
381
+ uv_u = uv_u[uv_not_nan]
382
+ uv_v = uv_v[uv_not_nan]
383
+
384
+ self.h_hist += np.histogram(hsv_h, bins=self.edges.hsv_h_hist_edges)[0].astype(np.uint64)
385
+ self.s_hist += np.histogram(hsv_s, bins=self.edges.hsv_s_hist_edges)[0].astype(np.uint64)
386
+ self.v_hist += np.histogram(hsv_v, bins=self.edges.hsv_v_hist_edges)[0].astype(np.uint64)
387
+
388
+ r_idx = (rgb[:,0] / 255 * (self.edges.rgb_bins[0] - 1)).astype(int)
389
+ g_idx = (rgb[:,1] / 255 * (self.edges.rgb_bins[1] - 1)).astype(int)
390
+ b_idx = (rgb[:,2] / 255 * (self.edges.rgb_bins[2] - 1)).astype(int)
391
+
392
+ np.add.at(self.rgb_hist, (r_idx, g_idx, b_idx), 1)
393
+
394
+ l_idx = (oklab[:,0] * (self.edges.oklab_bins[0] - 1)).astype(int)
395
+ a_idx = ((oklab[:,1] - self.edges.oklab_a_range[0]) / (self.edges.oklab_a_range[1] - self.edges.oklab_a_range[0]) * (self.edges.oklab_bins[1] - 1)).astype(int)
396
+ b_idx = ((oklab[:,2] - self.edges.oklab_b_range[0]) / (self.edges.oklab_b_range[1] - self.edges.oklab_b_range[0]) * (self.edges.oklab_bins[2] - 1)).astype(int)
397
+
398
+ np.add.at(self.oklab_hist, (l_idx, a_idx, b_idx), 1)
399
+
400
+ u_idx = ((uv_u - self.edges.uv_u_range[0]) / (self.edges.uv_u_range[1] - self.edges.uv_u_range[0]) * (self.edges.uv_bins[0] - 1)).astype(int)
401
+ v_idx = ((uv_v - self.edges.uv_v_range[0]) / (self.edges.uv_v_range[1] - self.edges.uv_v_range[0]) * (self.edges.uv_bins[1] - 1)).astype(int)
402
+
403
+ np.add.at(self.uv_hist, (u_idx, v_idx), 1)
404
+
405
+ self.num_tiles = self.num_tiles + 1
406
+ self.num_pixels = self.num_pixels + n
407
+
408
+ def compute(self):
409
+ """Compute the ColorSample.
410
+ """
411
+
412
+ print(f"Computing ColorSample for {self.identifier}...")
413
+
414
+ self.slide.set_mode(self.sampling_method)
415
+ for tile, _ in self.slide:
416
+ self.compute_tile(tile)
417
+ if self.num_pixels > self.max_pixels:
418
+ break
419
+
420
+ print("Finished computing ColorSample")
421
+
422
+
423
+ class ColorDistribution:
424
+
425
+ def __init__(self, samples: ColorSample | list[ColorSample], identifier: str | None = None, equally_weighted: bool = False):
426
+ """Color distribution is a Gaussian smoothed version of one or more ColorSamples to represent a color distribution.
427
+
428
+ Args:
429
+ samples: One or more ColorSamples.
430
+ identifier: An ID for the ColorDistribution. If None, only one ColorSample should be given in samples, and the ID will be taken from that ColorSample.
431
+ equally_weighted: Equally weight each ColorSample in the distribution.
432
+ """
433
+
434
+ self.samples = samples
435
+ if identifier is not None:
436
+ self.identifier = identifier
437
+ elif isinstance(samples, ColorSample):
438
+ self.identifier = samples.identifier
439
+ elif (isinstance(samples, list) and len(samples) == 1):
440
+ self.identifier = samples[0].identifier
441
+ else:
442
+ raise Exception("Specify an identifier for this ColorDistribution.")
443
+ self.equally_weighted = equally_weighted
444
+
445
+ if samples is not None:
446
+ self.set_edges(samples)
447
+
448
+ # Setup histograms
449
+ hist_dtype = np.float64 if self.equally_weighted else np.uint64
450
+ self.rgb_hist = np.zeros(self.edges.rgb_bins, dtype=hist_dtype)
451
+ self.h_hist = np.zeros((self.edges.h_bins,), dtype=hist_dtype)
452
+ self.s_hist = np.zeros((self.edges.s_bins,), dtype=hist_dtype)
453
+ self.v_hist = np.zeros((self.edges.v_bins,), dtype=hist_dtype)
454
+ self.oklab_hist = np.zeros(self.edges.oklab_bins, dtype=hist_dtype)
455
+ self.uv_hist = np.zeros(self.edges.uv_bins, dtype=hist_dtype)
456
+
457
+ def set_edges(self, samples: ColorSample | list[ColorSample]):
458
+ """Set the edges of this ColorDistribution from one or more ColorSamples.
459
+
460
+ If multiple ColorSamples are given, this function will check that all ColorSamples have the same edges.
461
+
462
+ Args:
463
+ samples: One or more ColorSamples.
464
+ """
465
+
466
+ if isinstance(samples, list):
467
+ init_sample = samples[0]
468
+ if isinstance(samples, ColorSample):
469
+ init_sample = samples
470
+
471
+ self.edges = init_sample.edges
472
+
473
+ if isinstance(samples, list):
474
+ for sample in samples:
475
+ if self.edges != sample.edges:
476
+ raise Exception("The bin counts and ranges must match for all ColorSamples.")
477
+
478
+ def save(self, output_dir: str, include_edges: bool = True):
479
+ """Save metric to disk.
480
+
481
+ Args:
482
+ output_dir: Folder path to output the metric to.
483
+ include_edges: Save the histogram edges as well (I recommend you set this to False if you already have the edges saved somewhere else to avoid wasting disk memory).
484
+ """
485
+
486
+ sample_identifiers = []
487
+ if isinstance(self.samples, ColorSample):
488
+ sample_identifiers.append(self.samples.identifier)
489
+ else:
490
+ for sample in self.samples:
491
+ sample_identifiers.append(sample.identifier)
492
+
493
+ if include_edges:
494
+ self.edges.save(output_dir)
495
+
496
+ json_output_path = os.path.join(output_dir, "color_distribution.json")
497
+ with open(json_output_path, "w") as file:
498
+ json.dump({
499
+ "identifier": self.identifier,
500
+ "equally_weighted": self.equally_weighted,
501
+ "sample_identifiers": sample_identifiers,
502
+ }, file)
503
+
504
+ hist_output_path = os.path.join(output_dir, "color_distribution_histograms.npz")
505
+ np.savez(hist_output_path, rgb_hist=self.rgb_hist, h_hist=self.h_hist, v_hist=self.v_hist, oklab_hist=self.oklab_hist, uv_hist=self.uv_hist, allow_pickle=False)
506
+
507
+ @classmethod
508
+ def load(cls, input_dir: str, edges: ColorHistogramEdges | None = None):
509
+ """Load metric from disk.
510
+
511
+ Args:
512
+ input_dir: Folder path to load the metric from.
513
+ edges: Color histogram edges. If None, the edges will be loaded from input_dir.
514
+
515
+ Returns:
516
+ A ColorDistribution.
517
+ """
518
+
519
+ if edges is None:
520
+ edges = ColorHistogramEdges.load(input_dir)
521
+
522
+ json_input_path = os.path.join(input_dir, "color_distribution.json")
523
+ with open(json_input_path, "r") as file:
524
+ json_data = json.load(file)
525
+
526
+ cd = cls(None, identifier=json_data["identifier"], equally_weighted=json_data["equally_weighted"])
527
+ cd.edges = edges
528
+
529
+ hist_input_path = os.path.join(input_dir, "color_distribution_histograms.npz")
530
+ with np.load(hist_input_path, allow_pickle=False) as data:
531
+ cd.rgb_hist, cd.h_hist, cd.s_hist, cd.v_hist, cd.oklab_hist, cd.uv_hist = data["rgb_hist"], data["h_hist"], data["v_hist"], data["oklab_hist"], data["uv_hist"]
532
+
533
+ return cd
534
+
535
+ def get_h_hist(self) -> np.ndarray:
536
+ """Get the hue (HSV) histogram.
537
+
538
+ Returns:
539
+ A np.ndarray histogram (returns as a density instead of counts).
540
+ """
541
+ return self.h_hist
542
+
543
+ def get_s_hist(self) -> np.ndarray:
544
+ """Get the saturation (HSV) histogram.
545
+
546
+ Returns:
547
+ A np.ndarray histogram (returns as a density instead of counts).
548
+ """
549
+ return self.s_hist
550
+
551
+ def get_v_hist(self) -> np.ndarray:
552
+ """Get the value (HSV) histogram.
553
+
554
+ Returns:
555
+ A np.ndarray histogram (returns as a density instead of counts).
556
+ """
557
+ return self.v_hist
558
+
559
+ def get_rgb_hist(self) -> np.ndarray:
560
+ """Get the RGB histogram.
561
+
562
+ Returns:
563
+ A np.ndarray histogram (returns as a density instead of counts).
564
+ """
565
+ return self.rgb_hist
566
+
567
+ def get_oklab_hist(self) -> np.ndarray:
568
+ """Get the OKLAB histogram.
569
+
570
+ Returns:
571
+ A np.ndarray histogram (returns as a density instead of counts).
572
+ """
573
+ return self.oklab_hist
574
+
575
+ def get_uv_hist(self) -> np.ndarray:
576
+ """Get the u'v' histogram.
577
+
578
+ Returns:
579
+ A np.ndarray histogram (returns as a density instead of counts).
580
+ """
581
+ return self.uv_hist
582
+
583
+ def compute(self):
584
+ """Compute the ColorDistribution.
585
+ """
586
+
587
+ samples = self.samples
588
+ if isinstance(self.samples, ColorSample):
589
+ samples = [self.samples]
590
+
591
+ for sample in samples:
592
+
593
+ self.h_hist += sample.get_h_hist(density=self.equally_weighted)
594
+ self.s_hist += sample.get_s_hist(density=self.equally_weighted)
595
+ self.v_hist += sample.get_v_hist(density=self.equally_weighted)
596
+ self.rgb_hist += sample.get_rgb_hist(density=self.equally_weighted)
597
+ self.oklab_hist += sample.get_oklab_hist(density=self.equally_weighted)
598
+ self.uv_hist += sample.get_uv_hist(density=self.equally_weighted)
599
+
600
+ self.h_hist = self.h_hist / np.sum(self.h_hist)
601
+ self.s_hist = self.s_hist / np.sum(self.s_hist)
602
+ self.v_hist = self.v_hist / np.sum(self.v_hist)
603
+ self.rgb_hist = self.rgb_hist / np.sum(self.rgb_hist)
604
+ self.oklab_hist = self.oklab_hist / np.sum(self.oklab_hist)
605
+ self.uv_hist = self.uv_hist / np.sum(self.uv_hist)
606
+
607
+ # Smooth
608
+ self.h_hist = gaussian_filter(self.h_hist, sigma=2.0)
609
+ self.h_hist = self.h_hist / np.sum(self.h_hist)
610
+
611
+ self.s_hist = gaussian_filter(self.s_hist, sigma=2.0)
612
+ self.s_hist = self.s_hist / np.sum(self.s_hist)
613
+
614
+ self.v_hist = gaussian_filter(self.v_hist, sigma=2.0)
615
+ self.v_hist = self.v_hist / np.sum(self.v_hist)
616
+
617
+ self.rgb_hist = gaussian_filter(self.rgb_hist, sigma=0.5)
618
+ self.rgb_hist = self.rgb_hist / np.sum(self.rgb_hist)
619
+
620
+ self.oklab_hist = gaussian_filter(self.oklab_hist, sigma=0.5)
621
+ self.oklab_hist = self.oklab_hist / np.sum(self.oklab_hist)
622
+
623
+ self.uv_hist = gaussian_filter(self.uv_hist, sigma=0.5)
624
+ self.uv_hist = self.uv_hist / np.sum(self.uv_hist)
625
+
626
+ class ColorComparison:
627
+
628
+ def __init__(self, reference: ColorDistribution | str, query: ColorSample | str):
629
+ """Compute a comparison between a ColorDistribution and a ColorSample:
630
+
631
+ Args:
632
+ reference: The reference ColorDistribution. This parameter can be set to a str if the only use of this object is to store attributes and not to compute.
633
+ query: The query ColorSample. This parameter can be set to a str if the only use of this object is to store attributes and not to compute.
634
+ """
635
+
636
+ if not isinstance(reference, ColorDistribution) and not isinstance(reference, str):
637
+ raise Exception("reference should be a ColorDistribution")
638
+ if not isinstance(query, ColorSample) and not isinstance(query, str):
639
+ raise Exception("query should be a ColorSample")
640
+
641
+ self.reference = reference
642
+ self.query = query
643
+
644
+ self.h_dist = None
645
+ self.s_dist = None
646
+ self.v_dist = None
647
+ self.rgb_dist = None
648
+ self.oklab_dist = None
649
+
650
+ def save(self, output_dir: str):
651
+ """Save metric to disk.
652
+
653
+ Args:
654
+ output_dir: Folder path to output the metric to.
655
+ """
656
+
657
+ json_output_path = os.path.join(output_dir, "color_comparison.json")
658
+ with open(json_output_path, "w") as file:
659
+ json.dump({
660
+ "reference": self.reference.identifier,
661
+ "query": self.query.identifier,
662
+ "h_dist": self.h_dist,
663
+ "s_dist": self.s_dist,
664
+ "v_dist": self.v_dist,
665
+ "rgb_dist": self.rgb_dist,
666
+ "oklab_dist": self.oklab_dist,
667
+ }, file)
668
+
669
+ @classmethod
670
+ def load(cls, input_dir: str) -> ColorComparison:
671
+ """Load metric from disk.
672
+
673
+ Args:
674
+ input_dir: Folder path to load the metric from.
675
+
676
+ Returns:
677
+ A ColorComparison.
678
+ """
679
+
680
+ json_input_path = os.path.join(input_dir, "color_comparison.json")
681
+ with open(json_input_path, "r") as file:
682
+ json_data = json.load(file)
683
+
684
+ cc = cls(json_data["reference"], json_data["query"])
685
+ cc.h_dist, cc.s_dist, cc.v_dist, cc.rgb_dist, cc.oklab_dist = json_data["h_dist"], json_data["s_dist"], json_data["v_dist"], json_data["rgb_dist"], json_data["oklab_dist"]
686
+
687
+ return cc
688
+
689
+ def get_val(self, val_type: str) -> float:
690
+ """Get a metric/statistic.
691
+
692
+ Options for ``val_type``:
693
+ * "h": Hue (HSV) distance.
694
+ * "s": Saturation (HSV) distance.
695
+ * "v": Value (HSV) distance.
696
+ * "rgb": RGB distance.
697
+ * "oklab": OKLAB distance.
698
+
699
+ Args:
700
+ val_type: The name of the metric/statistic to get.
701
+
702
+ Returns:
703
+ The requested metric/statistic.
704
+ """
705
+ if val_type == "h":
706
+ return self.h_dist
707
+ elif val_type == "s":
708
+ return self.s_dist
709
+ elif val_type == "v":
710
+ return self.v_dist
711
+ elif val_type == "rgb":
712
+ return self.rgb_dist
713
+ elif val_type == "oklab":
714
+ return self.oklab_dist
715
+ else:
716
+ raise Exception(f"{val_type} is not a valid value type.")
717
+
718
+ @property
719
+ def query_identifier(self) -> str:
720
+ """
721
+ Returns:
722
+ The ID of the query.
723
+ """
724
+ return self.query.identifier
725
+
726
+ @property
727
+ def reference_identifier(self) -> str:
728
+ """
729
+ Returns:
730
+ The ID of the reference.
731
+ """
732
+ return self.reference.identifier
733
+
734
+ def dist_metric(self, reference_hist: np.ndarray, query_hist: np.ndarray) -> float:
735
+ """Compute the distance between two histograms.
736
+
737
+ Args:
738
+ reference_hist: The reference histogram.
739
+ query_hist: The query histogram.
740
+
741
+ Returns:
742
+ The distance between two histograms.
743
+ """
744
+ return self.bhattacharyya(reference_hist, query_hist)
745
+
746
+ def bhattacharyya(self, reference_hist: np.ndarray, query_hist: np.ndarray) -> float:
747
+ """Compute the Bhattacharyya distance between two histograms.
748
+
749
+ Args:
750
+ reference_hist: The reference histogram.
751
+ query_hist: The query histogram.
752
+
753
+ Returns:
754
+ The Bhattacharyya distance between two histograms.
755
+ """
756
+ BC = np.sum(np.sqrt(reference_hist * query_hist))
757
+ Db = -1.0 * np.log(BC)
758
+ return Db
759
+
760
+ def compute(self):
761
+ """Compute the ColorComparison.
762
+ """
763
+
764
+ print(f"Comparing {self.query.identifier} to {self.reference.identifier}...")
765
+
766
+ self.h_dist = self.dist_metric(self.reference.get_h_hist(), self.query.get_h_hist(density=True))
767
+ self.s_dist = self.dist_metric(self.reference.get_s_hist(), self.query.get_s_hist(density=True))
768
+ self.v_dist = self.dist_metric(self.reference.get_v_hist(), self.query.get_v_hist(density=True))
769
+ self.rgb_dist = self.dist_metric(self.reference.get_rgb_hist(), self.query.get_rgb_hist(density=True))
770
+ self.oklab_dist = self.dist_metric(self.reference.get_oklab_hist(), self.query.get_oklab_hist(density=True))