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,759 @@
|
|
|
1
|
+
import stainnormprogram.norm.background as background
|
|
2
|
+
from stainnormprogram.slide import SlideImage, SlideImageCollection
|
|
3
|
+
from stainnormprogram.assessment.color import ColorSample, ColorDistribution, ColorComparison
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import math
|
|
7
|
+
import io
|
|
8
|
+
import base64
|
|
9
|
+
import pickle
|
|
10
|
+
import random
|
|
11
|
+
from typing import Dict, List, Tuple, Any, Union
|
|
12
|
+
|
|
13
|
+
import plotly
|
|
14
|
+
import plotly.express as px
|
|
15
|
+
import plotly.graph_objects as go
|
|
16
|
+
import plotly.io as pio
|
|
17
|
+
pio.renderers.default = 'iframe'
|
|
18
|
+
|
|
19
|
+
import colour
|
|
20
|
+
import numpy as np
|
|
21
|
+
import matplotlib.pyplot as plt
|
|
22
|
+
|
|
23
|
+
markers = ['s', 'o', 'D', '^', '+', 'x', 'v', '<', '>']
|
|
24
|
+
|
|
25
|
+
plot_labels = {
|
|
26
|
+
"color_dist_h": ["Distance", "HSV Hue"],
|
|
27
|
+
"color_dist_s": ["Distance", "HSV Saturation"],
|
|
28
|
+
"color_dist_v": ["Distance", "HSV Value"],
|
|
29
|
+
"color_dist_rgb": ["Distance", "RGB"],
|
|
30
|
+
"color_dist_oklab": ["Distance", "OKLAB"],
|
|
31
|
+
|
|
32
|
+
"palette_compare": ["Difference", "Comparison to Reference Palette"],
|
|
33
|
+
"palette_Hdiv": ["Diversity", "Palette Hematoxylin Diversity"],
|
|
34
|
+
"palette_Ediv": ["Diversity", "Palette Eosin Diversity"],
|
|
35
|
+
"palette_HEsep": ["Separability", "Palette Hematoxylin & Eosin Separability"],
|
|
36
|
+
|
|
37
|
+
"gamut_oog_count": ["Pixels", "Number of Pixels Outside of Reference Gamut"],
|
|
38
|
+
"gamut_ig_count": ["Pixels", "Number of Pixels Inside Reference Gamut"],
|
|
39
|
+
|
|
40
|
+
"background": ["Distance", "Comparison to Reference Background"],
|
|
41
|
+
|
|
42
|
+
"contrast": ["+/- Change", "Contrast Change from Original"],
|
|
43
|
+
|
|
44
|
+
"structure": ["Absolute Change", "Structure Change from Original"],
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
class HistPlot:
|
|
48
|
+
|
|
49
|
+
def __init__(self, data: ColorSample | ColorDistribution | list[ColorSample | ColorDistribution], trace_labels: list[str] | None = None):
|
|
50
|
+
"""A wrapper for a Plotly histogram plot.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
data: One or more ColorSamples or ColorDistributions to make a histogram plot from.
|
|
54
|
+
trace_labels: Labels for each trace (only for 2D plots with more than one trace).
|
|
55
|
+
"""
|
|
56
|
+
self.data = data
|
|
57
|
+
self.trace_labels = trace_labels
|
|
58
|
+
|
|
59
|
+
if self.trace_labels is None:
|
|
60
|
+
if not isinstance(data, list):
|
|
61
|
+
self.trace_labels = data.identifier
|
|
62
|
+
else:
|
|
63
|
+
identifiers = [d.identifier for d in data]
|
|
64
|
+
if len(set(identifiers)) == len(identifiers):
|
|
65
|
+
self.trace_labels = identifiers
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def hist_plot_3d(self, xedges: np.ndarray, yedges: np.ndarray, zedges: np.ndarray, hist: np.ndarray, axes: list[str] = ["x","y","z"], title: str = "Histogram") -> plotly.graph_objects.Figure:
|
|
69
|
+
"""Plot a 3D histogram.
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
xedges: X-axis edges.
|
|
73
|
+
yedges: Y-axis edges.
|
|
74
|
+
zedges: Z-axis edges.
|
|
75
|
+
hist: Histogram.
|
|
76
|
+
axes: Axes labels.
|
|
77
|
+
title: Title of the plot.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
A Plotly figure.
|
|
81
|
+
"""
|
|
82
|
+
xcenters = (xedges[:-1] + xedges[1:]) / 2
|
|
83
|
+
ycenters = (yedges[:-1] + yedges[1:]) / 2
|
|
84
|
+
zcenters = (zedges[:-1] + zedges[1:]) / 2
|
|
85
|
+
|
|
86
|
+
# Compute a meshgrid to get all of the coordinates
|
|
87
|
+
xc, yc, zc = np.meshgrid(xcenters, ycenters, zcenters, indexing='ij')
|
|
88
|
+
x_flat = xc.flatten()
|
|
89
|
+
y_flat = yc.flatten()
|
|
90
|
+
z_flat = zc.flatten()
|
|
91
|
+
|
|
92
|
+
# Mask out all zero count bins
|
|
93
|
+
hist_flat = hist.flatten()
|
|
94
|
+
mask = hist_flat > 0
|
|
95
|
+
x_flat = x_flat[mask]
|
|
96
|
+
y_flat = y_flat[mask]
|
|
97
|
+
z_flat = z_flat[mask]
|
|
98
|
+
hist_flat = hist_flat[mask]
|
|
99
|
+
|
|
100
|
+
# Plot histogram
|
|
101
|
+
fig = go.Figure(data=go.Scatter3d(
|
|
102
|
+
x=x_flat,
|
|
103
|
+
y=y_flat,
|
|
104
|
+
z=z_flat,
|
|
105
|
+
mode='markers',
|
|
106
|
+
marker=dict(
|
|
107
|
+
sizemode='diameter',
|
|
108
|
+
sizeref=10,
|
|
109
|
+
color=hist_flat,
|
|
110
|
+
colorscale='Viridis',
|
|
111
|
+
),
|
|
112
|
+
customdata=hist_flat,
|
|
113
|
+
hovertemplate=(
|
|
114
|
+
"<b>Bar Properties</b><br>" +
|
|
115
|
+
f"{axes[0]}: %{x:.3f}<br>" +
|
|
116
|
+
f"{axes[1]}: %{y:.3f}<br>" +
|
|
117
|
+
f"{axes[2]}: %{z:.3f}<br>" +
|
|
118
|
+
"Height: %{customdata:}"
|
|
119
|
+
"<extra></extra>"
|
|
120
|
+
)
|
|
121
|
+
))
|
|
122
|
+
|
|
123
|
+
fig.update_layout(height=800, width=800,
|
|
124
|
+
scene=dict(
|
|
125
|
+
xaxis=dict(title=dict(text=axes[0])),
|
|
126
|
+
yaxis=dict(title=dict(text=axes[1])),
|
|
127
|
+
zaxis=dict(title=dict(text=axes[2]))
|
|
128
|
+
),
|
|
129
|
+
title=dict(text=f'{title}'),
|
|
130
|
+
font=dict(family="Arial", size=14, weight="bold"),
|
|
131
|
+
title_font_size=25,
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
return fig
|
|
135
|
+
|
|
136
|
+
def oklab_hist_plot(self, density: bool = False) -> plotly.graph_objects.Figure:
|
|
137
|
+
"""Plot a 3D histogram of colors in OKLAB color space.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
density: Plot as a density.
|
|
141
|
+
|
|
142
|
+
Returns:
|
|
143
|
+
A Plotly figure.
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
if not isinstance(self.data, (ColorSample, ColorDistribution)):
|
|
147
|
+
raise Exception("Data must be a single ColorSample or ColorDistribution.")
|
|
148
|
+
|
|
149
|
+
# Get histogram
|
|
150
|
+
if isinstance(self.data, ColorSample):
|
|
151
|
+
hist = self.data.get_oklab_hist(density=density)
|
|
152
|
+
else:
|
|
153
|
+
hist = self.data.get_oklab_hist()
|
|
154
|
+
|
|
155
|
+
fig = self.hist_plot_3d(self.data.edges.oklab_l_hist_edges, self.data.edges.oklab_a_hist_edges, self.data.edges.oklab_b_hist_edges, hist, axes=["l", "a", "b"], title="OKLAB")
|
|
156
|
+
return fig
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def rgb_hist_plot(self, density: bool = False) -> plotly.graph_objects.Figure:
|
|
160
|
+
"""Plot a 3D histogram of colors in RGB color space.
|
|
161
|
+
|
|
162
|
+
Args:
|
|
163
|
+
density: Plot as a density.
|
|
164
|
+
|
|
165
|
+
Returns:
|
|
166
|
+
A Plotly figure.
|
|
167
|
+
"""
|
|
168
|
+
|
|
169
|
+
if not isinstance(self.data, (ColorSample, ColorDistribution)):
|
|
170
|
+
raise Exception("Data must be a single ColorSample or ColorDistribution.")
|
|
171
|
+
|
|
172
|
+
# Get histogram
|
|
173
|
+
if isinstance(self.data, ColorSample):
|
|
174
|
+
hist = self.data.get_rgb_hist(density=density)
|
|
175
|
+
else:
|
|
176
|
+
hist = self.data.get_rgb_hist()
|
|
177
|
+
|
|
178
|
+
fig = self.hist_plot_3d(self.data.edges.rgb_r_hist_edges, self.data.edges.rgb_g_hist_edges, self.data.edges.rgb_b_hist_edges, hist, axes=["R", "G", "B"], title="RGB")
|
|
179
|
+
return fig
|
|
180
|
+
|
|
181
|
+
def hist_plot_2d(self, edges: np.ndarray, heights: np.ndarray, identifiers: str | list[str] | None = None, axis_title: str = "Values", title: str = "Histogram", density: bool = False) -> plotly.graph_objects.Figure:
|
|
182
|
+
"""Plot a 2D histogram.
|
|
183
|
+
|
|
184
|
+
Args:
|
|
185
|
+
edges: Edges of the histogram.
|
|
186
|
+
heights: Heights of the bars.
|
|
187
|
+
identifiers: Trace labels.
|
|
188
|
+
axis_title: Y-axis title.
|
|
189
|
+
title: Title of the histogram.
|
|
190
|
+
density: Plot as a density.
|
|
191
|
+
|
|
192
|
+
Returns:
|
|
193
|
+
A Plotly figure.
|
|
194
|
+
"""
|
|
195
|
+
bin_centers = (edges[:-1] + edges[1:]) / 2
|
|
196
|
+
bin_widths = np.diff(edges)
|
|
197
|
+
|
|
198
|
+
if isinstance(heights, np.ndarray):
|
|
199
|
+
heights = [heights]
|
|
200
|
+
if not isinstance(identifiers, list):
|
|
201
|
+
identifiers = [identifiers]
|
|
202
|
+
if len(identifiers) != len(heights):
|
|
203
|
+
identifiers = ["Image" + str(i) for i in range(1,len(heights)+1)]
|
|
204
|
+
|
|
205
|
+
fig = go.Figure()
|
|
206
|
+
|
|
207
|
+
for i, height in enumerate(heights):
|
|
208
|
+
fig.add_trace(
|
|
209
|
+
go.Bar(
|
|
210
|
+
x=bin_centers,
|
|
211
|
+
y=height,
|
|
212
|
+
width=bin_widths,
|
|
213
|
+
offset=0,
|
|
214
|
+
marker_line_color="white",
|
|
215
|
+
marker_line_width=1,
|
|
216
|
+
opacity=0.6,
|
|
217
|
+
name=identifiers[i],
|
|
218
|
+
)
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
yaxis_title = "Density" if density else "Pixels"
|
|
222
|
+
fig.update_layout(
|
|
223
|
+
title=title,
|
|
224
|
+
xaxis_title=axis_title,
|
|
225
|
+
yaxis_title=yaxis_title,
|
|
226
|
+
bargap=0,
|
|
227
|
+
barmode="overlay",
|
|
228
|
+
font=dict(family="Arial", size=14, weight="bold"),
|
|
229
|
+
title_font_size=25,
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
return fig
|
|
233
|
+
|
|
234
|
+
def h_hist_plot(self, density: bool = False) -> plotly.graph_objects.Figure:
|
|
235
|
+
"""Plot a 2D hue (HSV) histogram.
|
|
236
|
+
|
|
237
|
+
Args:
|
|
238
|
+
density: Plot as a density.
|
|
239
|
+
|
|
240
|
+
Returns:
|
|
241
|
+
A Plotly figure.
|
|
242
|
+
"""
|
|
243
|
+
|
|
244
|
+
if not isinstance(self.data, (ColorSample, ColorDistribution)):
|
|
245
|
+
raise Exception("Data must be a single ColorSample or ColorDistribution.")
|
|
246
|
+
|
|
247
|
+
if isinstance(self.data, ColorSample):
|
|
248
|
+
heights = self.data.get_h_hist(density=density)
|
|
249
|
+
else:
|
|
250
|
+
heights = self.data.get_h_hist()
|
|
251
|
+
density = True
|
|
252
|
+
|
|
253
|
+
fig = self.hist_plot_2d(self.data.edges.hsv_h_hist_edges, heights, identifiers=self.data.identifier, axis_title="Hue", title="HSV Hue", density=density)
|
|
254
|
+
return fig
|
|
255
|
+
|
|
256
|
+
def s_hist_plot(self, density: bool = False) -> plotly.graph_objects.Figure:
|
|
257
|
+
"""Plot a 2D saturation (HSV) histogram.
|
|
258
|
+
|
|
259
|
+
Args:
|
|
260
|
+
density: Plot as a density.
|
|
261
|
+
|
|
262
|
+
Returns:
|
|
263
|
+
A Plotly figure.
|
|
264
|
+
"""
|
|
265
|
+
|
|
266
|
+
if not isinstance(self.data, (ColorSample, ColorDistribution)):
|
|
267
|
+
raise Exception("Data must be a single ColorSample or ColorDistribution.")
|
|
268
|
+
|
|
269
|
+
if isinstance(self.data, ColorSample):
|
|
270
|
+
heights = self.data.get_s_hist(density=density)
|
|
271
|
+
else:
|
|
272
|
+
heights = self.data.get_s_hist()
|
|
273
|
+
density = True
|
|
274
|
+
|
|
275
|
+
fig = self.hist_plot_2d(self.data.edges.hsv_s_hist_edges, heights, identifiers=self.data.identifier, axis_title="Saturation", title="HSV Saturation", density=density)
|
|
276
|
+
return fig
|
|
277
|
+
|
|
278
|
+
def v_hist_plot(self, density: bool = False) -> plotly.graph_objects.Figure:
|
|
279
|
+
"""Plot a 2D value (HSV) histogram.
|
|
280
|
+
|
|
281
|
+
Args:
|
|
282
|
+
density: Plot as a density.
|
|
283
|
+
|
|
284
|
+
Returns:
|
|
285
|
+
A Plotly figure.
|
|
286
|
+
"""
|
|
287
|
+
|
|
288
|
+
if not isinstance(self.data, (ColorSample, ColorDistribution)):
|
|
289
|
+
raise Exception("Data must be a single ColorSample or ColorDistribution.")
|
|
290
|
+
|
|
291
|
+
if isinstance(self.data, ColorSample):
|
|
292
|
+
heights = self.data.get_v_hist(density=density)
|
|
293
|
+
else:
|
|
294
|
+
heights = self.data.get_v_hist()
|
|
295
|
+
density = True
|
|
296
|
+
|
|
297
|
+
fig = self.hist_plot_2d(self.data.edges.hsv_v_hist_edges, heights, identifiers=self.data.identifier, axis_title="Value", title="HSV Value", density=density)
|
|
298
|
+
return fig
|
|
299
|
+
|
|
300
|
+
def h_hist_compare(self, density: bool = False) -> plotly.graph_objects.Figure:
|
|
301
|
+
"""Plot a 2D hue (HSV) histogram that compares two or more images.
|
|
302
|
+
|
|
303
|
+
Args:
|
|
304
|
+
density: Plot as a density.
|
|
305
|
+
|
|
306
|
+
Returns:
|
|
307
|
+
A Plotly figure.
|
|
308
|
+
"""
|
|
309
|
+
|
|
310
|
+
if not isinstance(self.data, list):
|
|
311
|
+
raise Exception("Data must be a list of two or more ColorSamples or ColorDistributions.")
|
|
312
|
+
|
|
313
|
+
for d in self.data:
|
|
314
|
+
if isinstance(d, ColorDistribution):
|
|
315
|
+
density = True
|
|
316
|
+
|
|
317
|
+
heights = []
|
|
318
|
+
for d in self.data:
|
|
319
|
+
if isinstance(d, ColorSample):
|
|
320
|
+
heights.append(d.get_h_hist(density=density))
|
|
321
|
+
else:
|
|
322
|
+
heights.append(d.get_h_hist())
|
|
323
|
+
|
|
324
|
+
fig = self.hist_plot_2d(self.data[0].edges.hsv_h_hist_edges, heights, identifiers=self.trace_labels, axis_title="Hue", title="HSV Hue", density=density)
|
|
325
|
+
return fig
|
|
326
|
+
|
|
327
|
+
def s_hist_compare(self, density: bool = False) -> plotly.graph_objects.Figure:
|
|
328
|
+
"""Plot a 2D saturation (HSV) histogram that compares two or more images.
|
|
329
|
+
|
|
330
|
+
Args:
|
|
331
|
+
density: Plot as a density.
|
|
332
|
+
|
|
333
|
+
Returns:
|
|
334
|
+
A Plotly figure.
|
|
335
|
+
"""
|
|
336
|
+
|
|
337
|
+
if not isinstance(self.data, list):
|
|
338
|
+
raise Exception("Data must be a list of two or more ColorSamples or ColorDistributions.")
|
|
339
|
+
|
|
340
|
+
for d in self.data:
|
|
341
|
+
if isinstance(d, ColorDistribution):
|
|
342
|
+
density = True
|
|
343
|
+
|
|
344
|
+
heights = []
|
|
345
|
+
for d in self.data:
|
|
346
|
+
if isinstance(d, ColorSample):
|
|
347
|
+
heights.append(d.get_s_hist(density=density))
|
|
348
|
+
else:
|
|
349
|
+
heights.append(d.get_s_hist())
|
|
350
|
+
|
|
351
|
+
fig = self.hist_plot_2d(self.data[0].edges.hsv_s_hist_edges, heights, identifiers=self.trace_labels, axis_title="Saturation", title="HSV Saturation", density=density)
|
|
352
|
+
return fig
|
|
353
|
+
|
|
354
|
+
def v_hist_compare(self, density: bool = False) -> plotly.graph_objects.Figure:
|
|
355
|
+
"""Plot a 2D value (HSV) histogram that compares two or more images.
|
|
356
|
+
|
|
357
|
+
Args:
|
|
358
|
+
density: Plot as a density.
|
|
359
|
+
|
|
360
|
+
Returns:
|
|
361
|
+
A Plotly figure.
|
|
362
|
+
"""
|
|
363
|
+
|
|
364
|
+
if not isinstance(self.data, list):
|
|
365
|
+
raise Exception("Data must be a list of two or more ColorSamples or ColorDistributions.")
|
|
366
|
+
|
|
367
|
+
for d in self.data:
|
|
368
|
+
if isinstance(d, ColorDistribution):
|
|
369
|
+
density = True
|
|
370
|
+
|
|
371
|
+
heights = []
|
|
372
|
+
for d in self.data:
|
|
373
|
+
if isinstance(d, ColorSample):
|
|
374
|
+
heights.append(d.get_v_hist(density=density))
|
|
375
|
+
else:
|
|
376
|
+
heights.append(d.get_v_hist())
|
|
377
|
+
|
|
378
|
+
fig = self.hist_plot_2d(self.data[0].edges.hsv_v_hist_edges, heights, identifiers=self.trace_labels, axis_title="Value", title="HSV Value", density=density)
|
|
379
|
+
return fig
|
|
380
|
+
|
|
381
|
+
def uv_hist(self, color: str | list[str] | None = None, density: bool = False, hide_axes: bool = False) -> plotly.graph_objects.Figure:
|
|
382
|
+
"""
|
|
383
|
+
Plot the CIE 1976 UCS chromaticity diagram on a u'v' coordinate grid, then adds points.
|
|
384
|
+
|
|
385
|
+
Modified from
|
|
386
|
+
Source - https://stackoverflow.com/a/76033328
|
|
387
|
+
Posted by Kel Solaar
|
|
388
|
+
Retrieved 2026-07-02, License - CC BY-SA 4.0
|
|
389
|
+
|
|
390
|
+
Args:
|
|
391
|
+
color: One or more colors for each trace. Use Plotly colors.
|
|
392
|
+
density: Plot as a density.
|
|
393
|
+
hide_axes: Hide the axes.
|
|
394
|
+
|
|
395
|
+
Returns:
|
|
396
|
+
A Plotly figure.
|
|
397
|
+
"""
|
|
398
|
+
|
|
399
|
+
data = self.data
|
|
400
|
+
if not isinstance(data, list):
|
|
401
|
+
data = [data]
|
|
402
|
+
|
|
403
|
+
if color is not None and not isinstance(color, list):
|
|
404
|
+
color = [color]
|
|
405
|
+
if len(color) != len(data):
|
|
406
|
+
raise Exception
|
|
407
|
+
else:
|
|
408
|
+
color = ["black"] * len(data)
|
|
409
|
+
|
|
410
|
+
for d in data:
|
|
411
|
+
if isinstance(d, ColorDistribution):
|
|
412
|
+
density = True
|
|
413
|
+
|
|
414
|
+
u_prime_centers = (data[0].edges.uv_u_hist_edges[:-1] + data[0].edges.uv_u_hist_edges[1:]) / 2
|
|
415
|
+
v_prime_centers = (data[0].edges.uv_v_hist_edges[:-1] + data[0].edges.uv_v_hist_edges[1:]) / 2
|
|
416
|
+
|
|
417
|
+
colour.plotting.colour_style()
|
|
418
|
+
# Resolution of the background image divided by 10, i.e. 1000px here.
|
|
419
|
+
plt.rcParams.update({"figure.figsize": (10.00, 10.00)})
|
|
420
|
+
|
|
421
|
+
# Drawing the background image with Matplotlib.
|
|
422
|
+
figure, axes = colour.plotting.diagrams.plot_chromaticity_diagram_colours(
|
|
423
|
+
diagram_colours="RGB", axes_visible=False, show=False, method='CIE 1976 UCS')
|
|
424
|
+
figure.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
|
425
|
+
|
|
426
|
+
buffer = io.BytesIO()
|
|
427
|
+
plt.savefig(buffer, format="png")
|
|
428
|
+
data_png = "data:image/png;base64," + base64.b64encode(buffer.getbuffer()).decode("utf8")
|
|
429
|
+
plt.close()
|
|
430
|
+
|
|
431
|
+
identifiers = self.trace_labels
|
|
432
|
+
if not isinstance(identifiers, list):
|
|
433
|
+
identifiers = [identifiers]
|
|
434
|
+
if self.trace_labels is None:
|
|
435
|
+
identifiers = ["Image" + str(i) for i in range(1,len(data)+1)]
|
|
436
|
+
|
|
437
|
+
# Displaying it with Plotly.
|
|
438
|
+
figure = go.Figure()
|
|
439
|
+
figure.update_layout(
|
|
440
|
+
width=1000,
|
|
441
|
+
height=1000,
|
|
442
|
+
xaxis=dict(
|
|
443
|
+
range=[0, 1]
|
|
444
|
+
),
|
|
445
|
+
yaxis=dict(
|
|
446
|
+
range=[0, 1]
|
|
447
|
+
),
|
|
448
|
+
)
|
|
449
|
+
figure.update_yaxes(
|
|
450
|
+
scaleanchor="x",
|
|
451
|
+
scaleratio=1,
|
|
452
|
+
)
|
|
453
|
+
figure.add_layout_image(
|
|
454
|
+
dict(
|
|
455
|
+
source=data_png,
|
|
456
|
+
xref="x",
|
|
457
|
+
yref="y",
|
|
458
|
+
x=0,
|
|
459
|
+
y=1,
|
|
460
|
+
sizex=1,
|
|
461
|
+
sizey=1,
|
|
462
|
+
sizing="stretch",
|
|
463
|
+
layer="below"
|
|
464
|
+
)
|
|
465
|
+
)
|
|
466
|
+
|
|
467
|
+
for i, d in enumerate(data):
|
|
468
|
+
x_coords = []
|
|
469
|
+
y_coords = []
|
|
470
|
+
vals = []
|
|
471
|
+
|
|
472
|
+
for u in range(d.edges.uv_bins[0]):
|
|
473
|
+
for v in range(d.edges.uv_bins[1]):
|
|
474
|
+
if d.uv_hist[u,v] > 0:
|
|
475
|
+
x_coords.append(u_prime_centers[u])
|
|
476
|
+
y_coords.append(v_prime_centers[v])
|
|
477
|
+
vals.append(d.uv_hist[u,v])
|
|
478
|
+
|
|
479
|
+
opacities = np.array(vals)
|
|
480
|
+
opacities = opacities / opacities.max()
|
|
481
|
+
opacities = np.power(opacities, 0.5)
|
|
482
|
+
opacities = opacities.clip(0,1)
|
|
483
|
+
|
|
484
|
+
figure.add_trace(
|
|
485
|
+
go.Scatter(
|
|
486
|
+
x=x_coords,
|
|
487
|
+
y=y_coords,
|
|
488
|
+
mode="markers",
|
|
489
|
+
marker=dict(
|
|
490
|
+
size=15,
|
|
491
|
+
color=color[i],
|
|
492
|
+
opacity=opacities,
|
|
493
|
+
),
|
|
494
|
+
name=identifiers[i],
|
|
495
|
+
text=identifiers[i],
|
|
496
|
+
customdata=vals,
|
|
497
|
+
hovertemplate=(
|
|
498
|
+
"<b>Bar Properties</b><br>" +
|
|
499
|
+
"u': %{x:.3f}<br>" +
|
|
500
|
+
"v': %{y:.3f}<br>" +
|
|
501
|
+
"Height: %{customdata:}"
|
|
502
|
+
"<extra></extra>"
|
|
503
|
+
)
|
|
504
|
+
)
|
|
505
|
+
)
|
|
506
|
+
|
|
507
|
+
figure.update_layout(
|
|
508
|
+
width=1000,
|
|
509
|
+
height=1000,
|
|
510
|
+
xaxis=dict(range=[0, 0.7]),
|
|
511
|
+
yaxis=dict(range=[0, 0.7]),
|
|
512
|
+
title=f"CIE 1976 u'v' Histogram",
|
|
513
|
+
xaxis_title="u'",
|
|
514
|
+
yaxis_title="v'",
|
|
515
|
+
font=dict(family="Arial", size=14, weight="bold"),
|
|
516
|
+
title_font_size=25,
|
|
517
|
+
)
|
|
518
|
+
|
|
519
|
+
if hide_axes:
|
|
520
|
+
figure.update_layout(
|
|
521
|
+
plot_bgcolor="white",
|
|
522
|
+
)
|
|
523
|
+
figure.update_xaxes(
|
|
524
|
+
showgrid=False,
|
|
525
|
+
zeroline=False,
|
|
526
|
+
)
|
|
527
|
+
figure.update_yaxes(
|
|
528
|
+
showgrid=False,
|
|
529
|
+
zeroline=False,
|
|
530
|
+
)
|
|
531
|
+
|
|
532
|
+
print("Click on the labels in the legend to toggle the plots on/off. Repeatedly toggle to see the difference between the two plots.")
|
|
533
|
+
|
|
534
|
+
return figure
|
|
535
|
+
|
|
536
|
+
class ScatterPlot:
|
|
537
|
+
|
|
538
|
+
def __init__(self, data: dict[str | None, list[tuple[str, str, float | tuple[float, float]]]], yaxis_title: str = "Value", title: str = "Scatter Plot"):
|
|
539
|
+
"""A wrapper for a Plotly scatter plot where the x-axis is images and the y-axis is some metric from the assessment.
|
|
540
|
+
|
|
541
|
+
Args:
|
|
542
|
+
data: Data to plot. A dict with keys for each trace, and each trace being a list of (identifier, group, value) tuples. Value can be a float or a tuple of two floats (mean, std).
|
|
543
|
+
yaxis_title: Y-axis title.
|
|
544
|
+
title: Title of the plot.
|
|
545
|
+
"""
|
|
546
|
+
self.data = data
|
|
547
|
+
self.yaxis_title = yaxis_title
|
|
548
|
+
self.title = title
|
|
549
|
+
self.fig = None
|
|
550
|
+
|
|
551
|
+
self.threshold = None
|
|
552
|
+
self.sort = None
|
|
553
|
+
self.sort_by = None
|
|
554
|
+
self.clip_ids = None
|
|
555
|
+
self.hide_ids = None
|
|
556
|
+
|
|
557
|
+
def save_plot(self, save_path: str, threshold: float | None = None, sort: bool = True, sort_by: str | None = None, clip_ids: bool = False, hide_ids: bool = False):
|
|
558
|
+
"""Save the plot.
|
|
559
|
+
|
|
560
|
+
Saving a Plotly plot can get complicated, so we chose to make an the plot in matplotlib and save that instead.
|
|
561
|
+
|
|
562
|
+
Args:
|
|
563
|
+
save_path: Path to save the figure.
|
|
564
|
+
threshold: Value for a horizontal threshold line drawn on the graph.
|
|
565
|
+
sort: Sort points. If True, set sort_by.
|
|
566
|
+
sort_by: Version name to sort by. If None and sort=True, the None version is used.
|
|
567
|
+
clip_ids: Clip IDs if they are too long.
|
|
568
|
+
hide_ids: Hide IDs.
|
|
569
|
+
"""
|
|
570
|
+
|
|
571
|
+
plt.rcParams['font.size'] = 14
|
|
572
|
+
|
|
573
|
+
fig = plt.figure(figsize=(14, 6))
|
|
574
|
+
ax = fig.add_subplot(111)
|
|
575
|
+
|
|
576
|
+
for j, (trace, points) in enumerate(self.data.items()):
|
|
577
|
+
ids = []
|
|
578
|
+
vals = []
|
|
579
|
+
groups = []
|
|
580
|
+
errors = []
|
|
581
|
+
for pt in points:
|
|
582
|
+
ids.append(pt[0])
|
|
583
|
+
groups.append(pt[1])
|
|
584
|
+
val = pt[2]
|
|
585
|
+
if isinstance(val, tuple):
|
|
586
|
+
vals.append(val[0])
|
|
587
|
+
errors.append(val[1])
|
|
588
|
+
else:
|
|
589
|
+
vals.append(val)
|
|
590
|
+
|
|
591
|
+
# Clip identifiers if they are too long
|
|
592
|
+
if clip_ids:
|
|
593
|
+
for i in range(len(ids)):
|
|
594
|
+
if len(ids[i]) > 25:
|
|
595
|
+
ids[i] = ids[i][0:25]
|
|
596
|
+
|
|
597
|
+
if sort and trace == sort_by:
|
|
598
|
+
if len(errors) > 0:
|
|
599
|
+
sorted_tuples = sorted(zip(vals, errors, ids))
|
|
600
|
+
vals, errors, ids = zip(*sorted_tuples)
|
|
601
|
+
ids = list(ids)
|
|
602
|
+
vals = list(vals)
|
|
603
|
+
errors = list(errors)
|
|
604
|
+
else:
|
|
605
|
+
sorted_tuples = sorted(zip(vals, ids))
|
|
606
|
+
vals, ids = zip(*sorted_tuples)
|
|
607
|
+
vals = list(vals)
|
|
608
|
+
ids = list(ids)
|
|
609
|
+
|
|
610
|
+
if len(errors) > 0:
|
|
611
|
+
ax.errorbar(
|
|
612
|
+
ids,
|
|
613
|
+
vals,
|
|
614
|
+
markersize=60,
|
|
615
|
+
yerr=errors,
|
|
616
|
+
fmt=markers[j % len(markers)],
|
|
617
|
+
label=trace,
|
|
618
|
+
)
|
|
619
|
+
else:
|
|
620
|
+
ax.scatter(
|
|
621
|
+
ids,
|
|
622
|
+
vals,
|
|
623
|
+
s=60,
|
|
624
|
+
marker=markers[j % len(markers)],
|
|
625
|
+
label=trace,
|
|
626
|
+
)
|
|
627
|
+
|
|
628
|
+
if threshold is not None:
|
|
629
|
+
ax.axhline(y=threshold, color="red", linestyle="--", linewidth=1.5, label="Threshold")
|
|
630
|
+
|
|
631
|
+
if hide_ids:
|
|
632
|
+
ax.tick_params(axis="x", which="both", bottom=False, labelbottom=False)
|
|
633
|
+
else:
|
|
634
|
+
ax.set_xticks(ax.get_xticks())
|
|
635
|
+
ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha="right", fontsize=8)
|
|
636
|
+
|
|
637
|
+
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0., fontsize=14)
|
|
638
|
+
ax.set_title(self.title, fontsize=20, fontweight="bold")
|
|
639
|
+
ax.set_xlabel("Images", fontsize=20, fontweight="bold")
|
|
640
|
+
ax.set_ylabel(self.yaxis_title, fontsize=20, fontweight="bold")
|
|
641
|
+
|
|
642
|
+
plt.tight_layout()
|
|
643
|
+
plt.savefig(
|
|
644
|
+
save_path,
|
|
645
|
+
dpi=300,
|
|
646
|
+
bbox_inches="tight",
|
|
647
|
+
)
|
|
648
|
+
plt.close("all")
|
|
649
|
+
|
|
650
|
+
print(f"Saved figure to {save_path}")
|
|
651
|
+
|
|
652
|
+
def make_plot(self, threshold: float | None = None, sort: bool = True, sort_by: str | None = None, clip_ids: bool = False, hide_ids: bool = False):
|
|
653
|
+
"""Make the plot and display it.
|
|
654
|
+
|
|
655
|
+
Args:
|
|
656
|
+
threshold: Value for a horizontal threshold line drawn on the graph.
|
|
657
|
+
sort: Sort points. If True, set sort_by.
|
|
658
|
+
sort_by: Version name to sort by. If None and sort=True, the None version is used.
|
|
659
|
+
clip_ids: Clip IDs if they are too long.
|
|
660
|
+
hide_ids: Hide IDs.
|
|
661
|
+
"""
|
|
662
|
+
|
|
663
|
+
if self.fig is not None and threshold == self.threshold and sort == self.sort and sort_by == self.sort_by and clip_ids == self.clip_ids and hide_ids == self.hide_ids:
|
|
664
|
+
return self.fig
|
|
665
|
+
|
|
666
|
+
self.threshold = threshold
|
|
667
|
+
self.sort = sort
|
|
668
|
+
self.sort_by = sort_by
|
|
669
|
+
self.clip_ids = clip_ids
|
|
670
|
+
self.hide_ids = hide_ids
|
|
671
|
+
|
|
672
|
+
fig = go.Figure()
|
|
673
|
+
|
|
674
|
+
for trace, points in self.data.items():
|
|
675
|
+
ids = []
|
|
676
|
+
vals = []
|
|
677
|
+
groups = []
|
|
678
|
+
errors = []
|
|
679
|
+
for pt in points:
|
|
680
|
+
ids.append(pt[0])
|
|
681
|
+
groups.append(pt[1])
|
|
682
|
+
val = pt[2]
|
|
683
|
+
if isinstance(val, tuple):
|
|
684
|
+
vals.append(val[0])
|
|
685
|
+
errors.append(val[1])
|
|
686
|
+
else:
|
|
687
|
+
vals.append(val)
|
|
688
|
+
|
|
689
|
+
# Clip identifiers if they are too long
|
|
690
|
+
if clip_ids:
|
|
691
|
+
for i in range(len(ids)):
|
|
692
|
+
if len(ids[i]) > 25:
|
|
693
|
+
ids[i] = ids[i][0:25]
|
|
694
|
+
|
|
695
|
+
if sort and trace == sort_by:
|
|
696
|
+
if len(errors) > 0:
|
|
697
|
+
sorted_tuples = sorted(zip(vals, errors, ids))
|
|
698
|
+
vals, errors, ids = zip(*sorted_tuples)
|
|
699
|
+
ids = list(ids)
|
|
700
|
+
vals = list(vals)
|
|
701
|
+
errors = list(errors)
|
|
702
|
+
else:
|
|
703
|
+
sorted_tuples = sorted(zip(vals, ids))
|
|
704
|
+
vals, ids = zip(*sorted_tuples)
|
|
705
|
+
vals = list(vals)
|
|
706
|
+
ids = list(ids)
|
|
707
|
+
|
|
708
|
+
fig.update_xaxes(
|
|
709
|
+
categoryorder="array",
|
|
710
|
+
categoryarray=ids,
|
|
711
|
+
)
|
|
712
|
+
|
|
713
|
+
fig.add_trace(
|
|
714
|
+
go.Scatter(
|
|
715
|
+
x=ids,
|
|
716
|
+
y=vals,
|
|
717
|
+
mode="markers",
|
|
718
|
+
marker=dict(size=12),
|
|
719
|
+
customdata=groups,
|
|
720
|
+
hovertemplate="<b>ID:</b> %{x}<br><b>Group:</b> %{customdata}<br><b>Value:</b> %{y}<extra></extra>",
|
|
721
|
+
name=trace,
|
|
722
|
+
)
|
|
723
|
+
)
|
|
724
|
+
|
|
725
|
+
if len(errors) > 0:
|
|
726
|
+
fig.update_traces(
|
|
727
|
+
error_y=dict(
|
|
728
|
+
type="data",
|
|
729
|
+
array=errors,
|
|
730
|
+
visible=True,
|
|
731
|
+
),
|
|
732
|
+
selector=dict(name=trace),
|
|
733
|
+
)
|
|
734
|
+
|
|
735
|
+
if threshold is not None:
|
|
736
|
+
fig.add_hline(
|
|
737
|
+
y=threshold,
|
|
738
|
+
line_dash="dash",
|
|
739
|
+
line_color="red",
|
|
740
|
+
line_width=3,
|
|
741
|
+
annotation_text=f"Threshold: {threshold}",
|
|
742
|
+
annotation_position="top left",
|
|
743
|
+
)
|
|
744
|
+
|
|
745
|
+
fig.update_layout(
|
|
746
|
+
title=self.title,
|
|
747
|
+
xaxis_title="Images",
|
|
748
|
+
yaxis_title=self.yaxis_title,
|
|
749
|
+
template="plotly_white",
|
|
750
|
+
xaxis=dict(tickangle=-45),
|
|
751
|
+
font=dict(family="Arial", size=14, weight="bold"),
|
|
752
|
+
title_font_size=25,
|
|
753
|
+
)
|
|
754
|
+
|
|
755
|
+
if hide_ids:
|
|
756
|
+
fig.update_layout(xaxis=dict(showticklabels=False))
|
|
757
|
+
|
|
758
|
+
self.fig = fig
|
|
759
|
+
return self.fig
|