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,252 @@
1
+ from stainnormprogram.slide import SlideImage, SlideImageCollection
2
+ import stainnormprogram.norm.background as background
3
+
4
+ import statistics
5
+ import os
6
+ import json
7
+
8
+ import numpy as np
9
+
10
+ class Contrast:
11
+
12
+ def __init__(
13
+ self,
14
+ slide: SlideImage | SlideImageCollection,
15
+ identifier: str | None = None,
16
+ tile_size: int = 512,
17
+ background_method: str = "hsv_threshold",
18
+ accept_perc: int = 10,
19
+ max_pixels: int = 50_000_000,
20
+ tile_locs: list[dict[str, str | int]] | None = None
21
+ ):
22
+ """``Contrast`` estimates the root mean square (RMS) contrast of an image.
23
+
24
+ Options for ``background_method``:
25
+ * "hsv_threshold": Threshold using saturation and value channels in HSV color space.
26
+
27
+ If you want to compare the contrast between two images and use the same tiles for both, first compute the Contrast for one image, then get the ``tile_locs`` attribute from that Contrast and give it to the second image's Contrast using the ``tile_locs`` parameter.
28
+
29
+ Args:
30
+ slide: Image to perform contrast estimation on.
31
+ identifier: An identifier. If None, the identifier is taken from the slide.
32
+ tile_size: Tile size to use.
33
+ background_method: Method for identifying the background/foreground.
34
+ accept_perc: Tiles with less than accept_perc percent of foreground are not used in the computation.
35
+ max_pixels: If the number of pixels used goes over max_pixels, stop the computation.
36
+ tile_locs: Tile locations to visit. Useful when you want to compare the contrast between two images and use the same tiles for both. Should be a list of locations, each location is a dict with "x", "y", "w", "h", and (if SlideImageCollection) "identifier" keys.
37
+ """
38
+ self.slide = slide
39
+ self.identifier = identifier if identifier is not None else self.slide.identifier
40
+ self.background_method = background_method
41
+ self.accept_perc = accept_perc
42
+
43
+ # Tile size
44
+ if self.slide is not None:
45
+ self.slide.set_tile_size(tile_size)
46
+
47
+ self.num_pixels = 0
48
+ self.num_tiles = 0
49
+ self.max_pixels = max_pixels
50
+ self.tile_size = tile_size
51
+
52
+ self.rms_vals = []
53
+ self.tile_locs = [] if tile_locs is None else tile_locs
54
+
55
+ def save(self, output_dir: str):
56
+ """Save metric to disk.
57
+
58
+ Args:
59
+ output_dir: Folder path to output the metric to.
60
+ """
61
+
62
+ json_output_path = os.path.join(output_dir, "contrast.json")
63
+ with open(json_output_path, "w") as file:
64
+ json.dump({
65
+ "identifier": self.identifier,
66
+ "background_method": self.background_method,
67
+ "accept_perc": self.accept_perc,
68
+ "tile_size": self.tile_size,
69
+ "num_pixels": self.num_pixels,
70
+ "num_tiles": self.num_tiles,
71
+ "max_pixels": self.max_pixels,
72
+ }, file)
73
+
74
+ contrast_output_path = os.path.join(input_dir, "contrast_vals.npz")
75
+ np.savez(contrast_output_path, rms_vals=self.rms_vals, tile_locs=self.tile_locs, allow_pickle=False)
76
+
77
+ @classmethod
78
+ def load(cls, input_dir: str) -> Contrast:
79
+ """Load metric from disk.
80
+
81
+ Args:
82
+ input_dir: Folder path to load the metric from.
83
+
84
+ Returns:
85
+ A Contrast.
86
+ """
87
+
88
+ json_input_path = os.path.join(input_dir, "contrast.json")
89
+ with open(json_input_path, "r") as file:
90
+ json_data = json.load(file)
91
+
92
+ contrast = 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"])
93
+
94
+ contrast_input_path = os.path.join(input_dir, "contrast_vals.npz")
95
+ with np.load(contrast_input_path, allow_pickle=False) as data:
96
+ contrast.rms_vals, contrast.tile_locs = data["rms_vals"], data["tile_locs"]
97
+
98
+ return contrast
99
+
100
+ def compute_tile(self, tile: Tile, fg_filtering: bool = True) -> bool:
101
+ """Compute the RMS contrast of an image tile.
102
+
103
+ Args:
104
+ tile: A Tile.
105
+ fg_filtering: If True, tiles with less than accept_perc percent of foreground pixels will be rejected.
106
+
107
+ Returns:
108
+ A bool indicating whether the tile was accepted for computation or not.
109
+ """
110
+
111
+ if self.background_method == "hsv_threshold":
112
+ fg_mask = background.hsv_threshold_foreground(tile).flatten()
113
+ else:
114
+ raise Exception(f"{self.background_method} is not a valid method.")
115
+
116
+ n = np.sum(fg_mask).item()
117
+ if fg_filtering and n / fg_mask.size * 100 < self.accept_perc:
118
+ return False
119
+
120
+ lum = tile.luv()[:,:,0].flatten()
121
+ lum = lum / 100. # Normalize to [0., 1.]
122
+
123
+ # RMS contrast
124
+ rms = np.std(lum)
125
+
126
+ self.num_tiles = self.num_tiles + 1
127
+ self.num_pixels = self.num_pixels + n
128
+
129
+ self.rms_vals.append(rms)
130
+
131
+ return True
132
+
133
+ def compute(self):
134
+ """Compute the Contrast.
135
+ """
136
+
137
+ print(f"Computing Contrast for {self.identifier}...")
138
+
139
+ if len(self.tile_locs) == 0:
140
+ print("Using random iterator...")
141
+ self.slide.set_mode("random")
142
+ else:
143
+ # Use corresponding tile locations
144
+ print("Using custom iterator...")
145
+ self.slide.set_mode("custom")
146
+ self.slide.set_custom_iter_locs(self.tile_locs)
147
+
148
+ for tile, metadata in self.slide:
149
+ success = self.compute_tile(tile, fg_filtering=(self.slide.mode == "random"))
150
+
151
+ if success and self.num_tiles % 10 == 0:
152
+ print(f"Processed {self.num_tiles} tiles so far...")
153
+
154
+ if self.slide.mode == "random" and success:
155
+ self.tile_locs.append(metadata)
156
+ if self.num_pixels > self.max_pixels:
157
+ break
158
+
159
+ print("Finished computing Contrast")
160
+ print(f"Tiles used = {self.num_tiles}")
161
+ print(f"Foreground pixels used = {self.num_pixels}")
162
+
163
+
164
+ class ContrastChange:
165
+
166
+ def __init__(self, reference: Contrast, query: Contrast):
167
+ """Compute the contrast change between a reference and query.
168
+
169
+ Args:
170
+ reference: The Contrast of a reference image.
171
+ query: The Contrast of a query image.
172
+ """
173
+ self.reference = reference
174
+ self.query = query
175
+
176
+ self.changes = []
177
+
178
+ self.change_mean = None
179
+ self.change_std = None
180
+
181
+ def save(self, output_dir: str):
182
+ """Save metric to disk.
183
+
184
+ Args:
185
+ output_dir: Folder path to output the metric to.
186
+ """
187
+
188
+ json_output_path = os.path.join(output_dir, "contrast_change.json")
189
+ with open(json_output_path, "w") as file:
190
+ json.dump({
191
+ "reference": self.reference.identifier,
192
+ "query": self.query.identifier,
193
+ "change_mean": self.change_mean,
194
+ "change_std": self.change_std,
195
+ }, file)
196
+
197
+ contrast_output_path = os.path.join(input_dir, "contrast_change_vals.npz")
198
+ np.savez(contrast_output_path, changes=self.changes, allow_pickle=False)
199
+
200
+ @classmethod
201
+ def load(cls, input_dir: str) -> ContrastChange:
202
+ """Load metric from disk.
203
+
204
+ Args:
205
+ input_dir: Folder path to load the metric from.
206
+
207
+ Returns:
208
+ A ContrastChange.
209
+ """
210
+
211
+ json_input_path = os.path.join(input_dir, "contrast_change.json")
212
+ with open(json_input_path, "r") as file:
213
+ json_data = json.load(file)
214
+
215
+ cc = cls(json_data["reference"], json_data["query"])
216
+ cc.change_mean = json_data["change_mean"]
217
+ cc.change_std = json_data["change_std"]
218
+
219
+ contrast_input_path = os.path.join(input_dir, "contrast_change_vals.npz")
220
+ with np.load(contrast_input_path, allow_pickle=False) as data:
221
+ cc.changes = data["changes"].tolist()
222
+
223
+ return cc
224
+
225
+ def get_val(self) -> tuple[float, float]:
226
+ """Get the contrast change metric.
227
+
228
+ If the change is positive, the query increased in contrast relative to the reference.
229
+ If the change is negative, the query decreased in contrast relative to the reference.
230
+
231
+ Returns:
232
+ A tuple with (contrast change mean, contrast change standard deviation).
233
+ """
234
+ return (self.change_mean, self.change_std)
235
+
236
+ def compute(self):
237
+ """Compute the ContrastChange.
238
+ """
239
+
240
+ num_vals = len(self.reference.rms_vals)
241
+
242
+ if num_vals != len(self.query.rms_vals):
243
+ raise Exception(f"Number of RMS values are not equal for reference and query. Reference = {num_vals}, Query = {len(self.query.rms_vals)}")
244
+
245
+ for i in range(num_vals):
246
+
247
+ change = self.query.rms_vals[i] - self.reference.rms_vals[i]
248
+ self.changes.append(change)
249
+
250
+ self.change_mean = statistics.mean(self.changes)
251
+ self.change_std = statistics.stdev(self.changes)
252
+
@@ -0,0 +1,407 @@
1
+ from stainnormprogram.slide import SlideImage, SlideImageCollection
2
+ import stainnormprogram.norm.background as background
3
+
4
+ import os
5
+ import json
6
+
7
+ from bitarray import bitarray
8
+ import numpy as np
9
+
10
+ class GamutArray:
11
+
12
+ def __init__(self):
13
+ """A wrapper for a bitarray that keeps track of which colors are in the gamut.
14
+ """
15
+ self.array = bitarray(256 * 256 * 256)
16
+
17
+ @staticmethod
18
+ def colors_to_indices(rgb: np.ndarray) -> np.ndarray:
19
+ """Colors to array indices.
20
+
21
+ Args:
22
+ rgb: A (N,3) array containing RGB colors as uint8.
23
+
24
+ Returns:
25
+ Indices as a (N,) np.uint32 array.
26
+ """
27
+ rgb = rgb.astype(np.uint32)
28
+ indices = rgb[:,0] * 256 * 256 + rgb[:,1] * 256 + rgb[:,2]
29
+ return indices # (N,) np.uint32
30
+
31
+ @staticmethod
32
+ def indices_to_colors(indices: np.ndarray | list) -> np.ndarray:
33
+ """Array indices to colors.
34
+
35
+ Args:
36
+ indices: Array indices.
37
+
38
+ Returns:
39
+ Colors as a RGB (N,3) np.uint8 array.
40
+ """
41
+ colors = []
42
+ for idx in indices:
43
+ x = idx % (256*256)
44
+ b = x % 256
45
+ g = x // 256
46
+ r = (idx - b - g * 256) // (256 * 256)
47
+ color = (round(r), round(g), round(b))
48
+ colors.append(color)
49
+
50
+ colors = np.array(colors)
51
+ assert colors.min() >= 0 and colors.max() <= 255, f"min = {colors.min()}, max = {colors.max()}"
52
+ colors = colors.astype(np.uint8)
53
+ return colors # (N,3) np.ndarray uint8
54
+
55
+ def bitwise_or(self, gamut_array: bitarray.bitarray):
56
+ """Perform bitwise OR.
57
+
58
+ Args:
59
+ gamut_array: The bitarray to perform bitwise OR with.
60
+ """
61
+ right_array = gamut_array.array
62
+ left_array = self.array
63
+
64
+ self.array = left_array | right_array
65
+
66
+ def add_colors(self, rgb: np.ndarray): # (N,3) np.ndarray uint8
67
+ """Add colors to the GamutArray.
68
+
69
+ Args:
70
+ rgb: Colors as a (N,3) np.uint8 array.
71
+ """
72
+ indices = self.colors_to_indices(rgb)
73
+ for idx in indices:
74
+ self.array[idx] = 1
75
+
76
+ def has_colors(self, rgb: np.ndarray) -> np.ndarray: # (N,3) np.ndarray uint8
77
+ """Check if the GamutArray as certain colors.
78
+
79
+ Args:
80
+ rgb: Colors to check as a (N,3) np.uint8 array.
81
+
82
+ Returns:
83
+ A (N,) bool np.ndarray where True means that the color is in the gamut and False otherwise.
84
+ """
85
+ indices = self.colors_to_indices(rgb)
86
+ flags = []
87
+ for position in range(indices.size):
88
+ flags[position] = bool(self.array[indices[position]])
89
+ flags = np.array(flags)
90
+ return flags # (N,) np.ndarray bool
91
+
92
+ class Gamut:
93
+
94
+ def __init__(
95
+ self,
96
+ slide: SlideImage | SlideImageCollection,
97
+ identifier: str | None = None,
98
+ tile_size: int = 32,
99
+ background_method: str = "hsv_threshold",
100
+ accept_perc: int = 10,
101
+ max_pixels: int = 1_000_000
102
+ ):
103
+ """Compute the Gamut for an image.
104
+
105
+ Options for ``background_method``:
106
+ * "hsv_threshold": Threshold using saturation and value channels in HSV color space.
107
+
108
+ Args:
109
+ slide: The slide to calculate the gamut of.
110
+ identifier: An ID for this Gamut. If None, the identifier of the slide will be used.
111
+ tile_size: Tile size to use.
112
+ background_method: Method for identifying the background/foreground.
113
+ accept_perc: Tiles with less than accept_perc percent of foreground are not used in the computation.
114
+ max_pixels: If the number of pixels used goes over max_pixels, stop the computation.
115
+ """
116
+
117
+ self.slide = slide
118
+ self.identifier = identifier if identifier is not None else self.slide.identifier
119
+ self.background_method = background_method
120
+ self.accept_perc = accept_perc
121
+
122
+ # Tile size
123
+ if isinstance(self.slide, (SlideImage, SlideImageCollection)):
124
+ self.slide.set_tile_size(tile_size)
125
+
126
+ self.num_pixels = 0
127
+ self.num_tiles = 0
128
+ self.max_pixels = max_pixels
129
+ self.tile_size = tile_size
130
+
131
+ self.gamut_array = GamutArray()
132
+
133
+ def save(self, output_dir: str):
134
+ """Save metric to disk.
135
+
136
+ Args:
137
+ output_dir: Folder path to output the metric to.
138
+ """
139
+
140
+ json_output_path = os.path.join(output_dir, "gamut.json")
141
+ with open(json_output_path, "w") as file:
142
+ json.dump({
143
+ "identifier": self.identifier,
144
+ "background_method": self.background_method,
145
+ "accept_perc": self.accept_perc,
146
+ "num_pixels": self.num_pixels,
147
+ "num_tiles": self.num_tiles,
148
+ "max_pixels": self.max_pixels,
149
+ "tile_size": self.tile_size,
150
+ }, file)
151
+
152
+ gamut_output_path = os.path.join(output_dir, "gamut.bin")
153
+ with open(gamut_output_path, "wb") as f:
154
+ self.gamut_array.tofile(f)
155
+
156
+ @classmethod
157
+ def load(cls, input_dir: str) -> Gamut:
158
+ """Load metric from disk.
159
+
160
+ Args:
161
+ input_dir: Folder path to load the metric from.
162
+
163
+ Returns:
164
+ A Gamut.
165
+ """
166
+
167
+ json_input_path = os.path.join(input_dir, "gamut.json")
168
+ with open(json_input_path, "r") as file:
169
+ json_data = json.load(file)
170
+
171
+ gamut = cls(None, json_data["identifier"], json_data["tile_size"], json_data["background_method"], json_data["accept_perc"], json_data["max_pixels"])
172
+
173
+ gamut_input_path = os.path.join(input_dir, "gamut.bin")
174
+ with open(gamut_input_path, "rb") as f:
175
+ gamut.gamut_array.fromfile(f)
176
+
177
+ return gamut
178
+
179
+ def compute_tile(self, tile: Tile):
180
+ """Add colors from the image tile to the gamut.
181
+
182
+ Args:
183
+ tile: Image tile.
184
+ """
185
+
186
+ if self.background_method == "hsv_threshold":
187
+ fg_mask = background.hsv_threshold_foreground(tile).flatten()
188
+ else:
189
+ raise Exception(f"{self.background_method} is not a valid background estimation method.")
190
+
191
+ n = np.sum(fg_mask).item()
192
+ if n / fg_mask.size * 100 < self.accept_perc:
193
+ return
194
+
195
+ tile_rgb_flat = tile.rgb(as_uint8=True).reshape((-1,3))
196
+ self.gamut_array.add_colors(tile_rgb_flat)
197
+
198
+ self.num_tiles = self.num_tiles + 1
199
+ self.num_pixels = self.num_pixels + n
200
+
201
+ def compute(self):
202
+ """Compute the Gamut.
203
+ """
204
+
205
+ print(f"Computing Gamut for {self.identifier}...")
206
+
207
+ self.slide.set_mode("random")
208
+ for tile, _ in self.slide:
209
+ self.compute_tile(tile)
210
+ if self.num_pixels > self.max_pixels:
211
+ break
212
+
213
+ print("Finished computing Gamut")
214
+
215
+ class GamutComparison:
216
+
217
+ def __init__(self, reference: ReferenceGamut, query: Gamut):
218
+ """Compare a query Gamut with a ReferenceGamut.
219
+
220
+ Args:
221
+ reference: The ReferenceGamut.
222
+ query: The query Gamut.
223
+ """
224
+ self.reference = reference
225
+ self.query = query
226
+
227
+ # Out-of-gamut count and colors
228
+ self.oog_count = None
229
+ self.oog_colors = None # np.ndarray (N,3) uint8
230
+
231
+ self.ig_count = None
232
+
233
+ def save(self, output_dir: str):
234
+ """Save metric to disk.
235
+
236
+ Args:
237
+ output_dir: Folder path to output the metric to.
238
+ """
239
+
240
+ json_output_path = os.path.join(output_dir, "gamut_comparison.json")
241
+ with open(json_output_path, "w") as file:
242
+ json.dump({
243
+ "reference": self.reference.identifier,
244
+ "query": self.query.identifier,
245
+ "oog_count": self.oog_count,
246
+ "ig_count": self.ig_count,
247
+ }, file)
248
+
249
+ oog_output_path = os.path.join(output_dir, "gamut_oog_colors.npz")
250
+ if self.oog_colors is not None:
251
+ np.savez(oog_output_path, oog_colors=self.oog_colors, allow_pickle=False)
252
+
253
+
254
+ @classmethod
255
+ def load(cls, input_dir: str) -> GamutComparison:
256
+ """Load metric from disk.
257
+
258
+ Args:
259
+ input_dir: Folder path to load the metric from.
260
+
261
+ Returns:
262
+ A GamutComparison.
263
+ """
264
+
265
+ json_input_path = os.path.join(input_dir, "gamut_comparison.json")
266
+ with open(json_input_path, "r") as file:
267
+ json_data = json.load(file)
268
+
269
+ gc = cls(json_data["reference"], json_data["query"])
270
+
271
+ oog_input_path = os.path.join(output_dir, "gamut_oog_colors.npz")
272
+ if os.path.exists(oog_input_path):
273
+ with np.load(oog_input_path, allow_pickle=False) as data:
274
+ gc.oog_colors = data["oog_colors"]
275
+
276
+ return gc
277
+
278
+ def get_oog_colors(self, oog_mask: np.ndarray) -> np.ndarray:
279
+ """Get the out-of-gamut colors.
280
+
281
+ Args:
282
+ oog_mask: A bool np.ndarray where True indicates an out-of-gamut color. Each index corresponds to a color (as defined by GamutArray).
283
+
284
+ Returns:
285
+ Colors as a RGB (N,3) np.uint8 array.
286
+ """
287
+
288
+ indices = np.where(oog_mask)[0]
289
+ colors = GamutArray.indices_to_colors(indices)
290
+
291
+ return colors
292
+
293
+ def get_val(self, val_type: str) -> int:
294
+ """Get a metric computed by this GamutComparison.
295
+
296
+ Options for ``val_type``:
297
+ * "oog_count": Out-of-gamut color count.
298
+ * "ig_count": In-gamut color count.
299
+
300
+ Returns:
301
+ The requested metric.
302
+ """
303
+ if val_type == "oog_count":
304
+ return self.oog_count
305
+ elif val_type == "ig_count":
306
+ return self.ig_count
307
+ else:
308
+ raise Exception(f"{val_type} is not a valid metric that can be requested.")
309
+
310
+ def compute(self, get_colors: bool = False):
311
+ """Compute the GamutComparison.
312
+
313
+ Args:
314
+ get_colors: If True, attribute ``oog_colors`` is set to the out-of-gamut RGB colors. Nothing is returned.
315
+ """
316
+
317
+ ref_array = self.reference.gamut_array.array
318
+ ref_array = np.array(ref_array.tolist())
319
+
320
+ q_array = self.query.gamut_array.array
321
+ q_array = np.array(q_array.tolist())
322
+
323
+ # An out-of-gamut color is when query is 1 but ref is 0
324
+ oog_mask = (q_array == 1) & (ref_array == 0)
325
+ self.oog_count = np.sum(oog_mask).item()
326
+
327
+ ig_mask = (q_array == 1) & (ref_array == 1)
328
+ self.ig_count = np.sum(ig_mask).item()
329
+
330
+ if get_colors:
331
+ self.oog_colors = self.get_oog_colors(oog_mask)
332
+
333
+ class ReferenceGamut:
334
+
335
+ def __init__(self, ref_gamuts: Gamut | list[Gamut], identifier: str | None = None):
336
+ """A gamut for the reference distribution (i.e., a single gamut to represent multiple reference images).
337
+
338
+ Args:
339
+ ref_gamuts: Either a single Gamut or a list of Gamuts that represent the reference.
340
+ identifier: An ID for this reference.
341
+ """
342
+ self.ref_gamuts = ref_gamuts
343
+ if identifier is not None:
344
+ self.identifier = identifier
345
+ elif isinstance(ref_gamuts, Gamut):
346
+ self.identifier = ref_gamuts.identifier
347
+ elif isinstance(ref_gamuts, list) and len(ref_gamuts) == 1:
348
+ self.identifier = ref_gamuts[0].identifier
349
+ else:
350
+ raise Exception("Set an identifier when more than one Gamut is in ref_gamuts.")
351
+
352
+ if isinstance(self.ref_gamuts, Gamut):
353
+ self.ref_gamuts = [ref_gamuts]
354
+
355
+ self.gamut_array = GamutArray()
356
+
357
+ def save(self, output_dir: str):
358
+ """Save metric to disk.
359
+
360
+ Args:
361
+ output_dir: Folder path to output the metric to.
362
+ """
363
+
364
+ ref_gamut_identifiers = []
365
+ for rg in self.ref_gamuts:
366
+ ref_gamut_identifiers.append(rg)
367
+
368
+ json_output_path = os.path.join(output_dir, "reference_gamut.json")
369
+ with open(json_output_path, "w") as file:
370
+ json.dump({
371
+ "identifier": self.identifier,
372
+ "ref_gamut_identifiers": ref_gamut_identifiers,
373
+ }, file)
374
+
375
+ gamut_output_path = os.path.join(output_dir, "reference_gamut.bin")
376
+ with open(gamut_output_path, "wb") as f:
377
+ self.gamut_array.tofile(f)
378
+
379
+ @classmethod
380
+ def load(cls, input_dir: str) -> ReferenceGamut:
381
+ """Load metric from disk.
382
+
383
+ Args:
384
+ input_dir: Folder path to load the metric from.
385
+
386
+ Returns:
387
+ A ReferenceGamut.
388
+ """
389
+
390
+ json_input_path = os.path.join(input_dir, "reference_gamut.json")
391
+ with open(json_input_path, "r") as file:
392
+ json_data = json.load(file)
393
+
394
+ gamut = cls(json_data["ref_gamut_identifiers"], identifier=json_data["identifier"])
395
+
396
+ gamut_input_path = os.path.join(input_dir, "reference_gamut.bin")
397
+ with open(gamut_input_path, "rb") as f:
398
+ gamut.gamut_array.fromfile(f)
399
+
400
+ return gamut
401
+
402
+ def compute(self):
403
+ """Compute the ReferenceGamut.
404
+ """
405
+
406
+ for g in self.ref_gamuts:
407
+ self.gamut_array.bitwise_or(g.gamut_array)