Skip to content

napari_cellseg3d.code_plugins.plugin_metrics

CURRENTLY UNUSED.

Classes:

Name Description
MetricsUtils

Plugin to evaluate metrics between two sets of labels, ground truth and prediction.

MetricsUtils

Bases: BasePluginFolder

Plugin to evaluate metrics between two sets of labels, ground truth and prediction.

Methods:

Name Description
__init__

Creates a MetricsUtils widget for computing and plotting dice metrics between labels.

compute_dice

Computes the dice metric between pairs of labels.

plot_dice

Plots the dice loss for each pair of labels on viewer.

remove_plots

Clears plots from window view.

Attributes:

Name Type Description
canvas

Canvas to render plots on

layout

Called for plotting

plots

Array that references all plots currently on the window

Source code in napari_cellseg3d/code_plugins/plugin_metrics.py
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
class MetricsUtils(BasePluginFolder):
    """Plugin to evaluate metrics between two sets of labels, ground truth and prediction."""

    def __init__(self, viewer: "napari.viewer.Viewer", parent=None):
        """Creates a MetricsUtils widget for computing and plotting dice metrics between labels.

        Args:
            viewer: viewer to display the widget in
            parent : parent widget.
        """
        super().__init__(viewer, parent, has_results=False)

        self._viewer = viewer
        """Viewer to display widget in"""

        self.layout = None
        """Called for plotting"""
        self.canvas = None
        """Canvas to render plots on"""
        self.plots = []
        """Array that references all plots currently on the window"""

        ######################################
        # interface
        self.io_panel = self._build_io_panel()

        # set new descriptions for Filewidgets
        self.image_filewidget.description = "Ground truth"
        self.labels_filewidget.description = "Prediction"

        self.btn_compute_dice = ui.Button("Compute Dice", self.compute_dice)

        self.rotate_choice = ui.CheckBox("Find best orientation")

        self.btn_reset_plot = ui.Button("Clear plots", self.remove_plots)

        self.lbl_threshold_box = ui.make_label("Score threshold", self)
        self.threshold_box = ui.DoubleIncrementCounter(
            lower=0.1, upper=1, default=DEFAULT_THRESHOLD, step=0.1
        )

        self.results_filewidget.button.setVisible(False)
        self.results_filewidget.text_field.setVisible(False)

        self.rotate_choice.setToolTip(
            "This will rotate and flip your images to find the orientation with the best Dice coefficient.\n"
            "Use this if your labels and predictions are not oriented the same way."
        )
        self.threshold_box.setToolTip(
            "Any label-prediction pair below this threshold will be shown in napari"
        )
        self.btn_reset_plot.setToolTip("Erase all plots")

        self._build()

    def _build(self):
        """Builds the layout of the widget."""
        # self.filetype_choice.label.setVisible(False)

        w = ui.ContainerWidget()
        self.layout = w.layout

        metrics_group_w, metrics_group_l = ui.make_group("Data")

        ui.add_widgets(
            metrics_group_l,
            [
                ui.combine_blocks(
                    right_or_below=self.image_filewidget.button,
                    left_or_above=self.image_filewidget.text_field,
                    min_spacing=70,
                ),  # images -> ground truth
                ui.combine_blocks(
                    right_or_below=self.labels_filewidget.button,
                    left_or_above=self.labels_filewidget.text_field,
                    min_spacing=70,
                ),  # labels -> prediction
            ],
        )

        metrics_group_w.setLayout(metrics_group_l)
        ############################
        ui.add_blank(self, self.layout)
        ############################
        param_group_w, param_group_l = ui.make_group("Parameters")

        thresh_container = ui.combine_blocks(
            self.threshold_box, self.lbl_threshold_box, horizontal=False, l=2
        )

        ui.add_widgets(param_group_l, [thresh_container, self.rotate_choice], None)

        param_group_w.setLayout(param_group_l)
        ##############################
        ui.add_widgets(
            self.layout,
            [
                metrics_group_w,
                param_group_w,
                self.btn_compute_dice,
                self._make_close_button(),
                self.btn_reset_plot,
            ],
        )

        self.btn_reset_plot.setVisible(False)

        ui.ScrollArea.make_scrollable(self.layout, self)

    def plot_dice(self, dice_coeffs, threshold=DEFAULT_THRESHOLD):
        """Plots the dice loss for each pair of labels on viewer."""
        self.btn_reset_plot.setVisible(True)
        colors = []

        bckgrd_color = (0, 0, 0, 0)

        for coeff in dice_coeffs:  # TODO add threshold manual setting
            if coeff < threshold:
                colors.append(ui.dark_red)  # 72071d # crimson red
            else:
                colors.append(ui.default_cyan)  # 8dd3c7 # turquoise cyan
        with plt.style.context("dark_background"):
            if self.canvas is None:
                self.canvas = FigureCanvas(Figure(figsize=(2, 5)))
                self.layout.addWidget(self.canvas)
                self.canvas.figure.tight_layout()
            else:
                self.dice_plot.cla()
            self.canvas.figure.set_facecolor(bckgrd_color)
            dice_plot = self.canvas.figure.add_subplot(1, 1, 1)
            labels = np.array(range(len(dice_coeffs))) + 1

            dice_plot.barh(labels, dice_coeffs, color=colors)
            dice_plot.set_facecolor(bckgrd_color)

            dice_plot.invert_yaxis()

            self.plots.append(self.canvas)
            dice_plot.axvline(threshold, color=ui.dark_red)
            dice_plot.set_title(
                f"Session {len(self.plots)}\nMean dice : {np.mean(dice_coeffs):.4f}"
            )
            # dice_plot.set_xticks(rotation=45)
            dice_plot.set_xlabel("Dice coefficient")
            # dice_plot.set_ylabel("Labels pair id", rotation=90)

            self.canvas.draw_idle()

    def remove_plots(self):
        """Clears plots from window view."""
        if self.plots:
            for p in self.plots:
                p.setVisible(False)
        self.plots = []
        self.btn_reset_plot.setVisible(False)

    def compute_dice(self):
        """Computes the dice metric between pairs of labels.

        Rotates the prediction label to find matching orientation as well.
        """
        # u = 0
        # t = 0

        threshold = self.threshold_box.value()
        rotate = self.rotate_choice.isChecked()

        total_metrics = []
        self.canvas = None  # kind of terrible way to stack plots... but it works.

        for image_id, (ground_path, pred_path) in enumerate(
            zip(self.images_filepaths, self.labels_filepaths, strict=False),
            start=1,
        ):
            ground = imread(ground_path)
            pred = imread(pred_path)

            ground = to_semantic(ground).astype(np.int8)
            pred = to_semantic(pred).astype(np.int8)

            pred_dims = pred.shape[-3:]
            pad_pred = utils.get_padding_dim(pred_dims)

            while len(pred.shape) < 5:
                pred = np.expand_dims(pred, axis=0)

            while len(ground.shape) < 4:
                ground = np.expand_dims(ground, axis=0)

            ground = (SpatialPad(pad_pred)(ToTensor()(ground))).numpy()

            while len(ground.shape) < len(pred.shape):
                ground = np.expand_dims(ground, axis=0)

            if ground.shape != pred.shape:
                raise ValueError(
                    "Padded sizes of images do not match! "
                    f"Padded ground label: {ground.shape}. "
                    f"Padded pred label: {pred.shape}."
                )

            scores = []

            if rotate:
                pred_flip_x = np.rot90(pred[0][0], axes=(0, 1))
                pred_flip_y = np.rot90(pred[0][0], axes=(1, 2))
                pred_flip_z = np.rot90(pred[0][0], axes=(0, 2))

                for rotated_pred in [pred[0][0], pred_flip_x, pred_flip_y, pred_flip_z]:
                    scores.append(utils.dice_coeff(rotated_pred, ground))
                    scores.append(utils.dice_coeff(np.flip(rotated_pred), ground))

                    for axis in range(3):
                        scores.append(
                            utils.dice_coeff(np.flip(rotated_pred, axis=axis), ground)
                        )
            else:
                scores.append(utils.dice_coeff(pred, ground))

            score = max(scores)

            if score < threshold:
                self._viewer.dims.ndisplay = 3
                self._viewer.add_image(
                    ground, name=f"ground_{image_id}", colormap="blue", opacity=0.7
                )
                self._viewer.add_image(
                    pred, name=f"pred_{image_id}", colormap="red", opacity=0.7
                )

            total_metrics.append(score)
        # print(f"DICE METRIC :{total_metrics}")
        self.plot_dice(total_metrics, threshold)

canvas instance-attribute

canvas = None

Canvas to render plots on

layout instance-attribute

layout = None

Called for plotting

plots instance-attribute

plots = []

Array that references all plots currently on the window

__init__

__init__(viewer: Viewer, parent=None)

Creates a MetricsUtils widget for computing and plotting dice metrics between labels.

Parameters:

Name Type Description Default
viewer Viewer

viewer to display the widget in

required
parent

parent widget.

required
Source code in napari_cellseg3d/code_plugins/plugin_metrics.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def __init__(self, viewer: "napari.viewer.Viewer", parent=None):
    """Creates a MetricsUtils widget for computing and plotting dice metrics between labels.

    Args:
        viewer: viewer to display the widget in
        parent : parent widget.
    """
    super().__init__(viewer, parent, has_results=False)

    self._viewer = viewer
    """Viewer to display widget in"""

    self.layout = None
    """Called for plotting"""
    self.canvas = None
    """Canvas to render plots on"""
    self.plots = []
    """Array that references all plots currently on the window"""

    ######################################
    # interface
    self.io_panel = self._build_io_panel()

    # set new descriptions for Filewidgets
    self.image_filewidget.description = "Ground truth"
    self.labels_filewidget.description = "Prediction"

    self.btn_compute_dice = ui.Button("Compute Dice", self.compute_dice)

    self.rotate_choice = ui.CheckBox("Find best orientation")

    self.btn_reset_plot = ui.Button("Clear plots", self.remove_plots)

    self.lbl_threshold_box = ui.make_label("Score threshold", self)
    self.threshold_box = ui.DoubleIncrementCounter(
        lower=0.1, upper=1, default=DEFAULT_THRESHOLD, step=0.1
    )

    self.results_filewidget.button.setVisible(False)
    self.results_filewidget.text_field.setVisible(False)

    self.rotate_choice.setToolTip(
        "This will rotate and flip your images to find the orientation with the best Dice coefficient.\n"
        "Use this if your labels and predictions are not oriented the same way."
    )
    self.threshold_box.setToolTip(
        "Any label-prediction pair below this threshold will be shown in napari"
    )
    self.btn_reset_plot.setToolTip("Erase all plots")

    self._build()

compute_dice

compute_dice()

Computes the dice metric between pairs of labels.

Rotates the prediction label to find matching orientation as well.

Source code in napari_cellseg3d/code_plugins/plugin_metrics.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def compute_dice(self):
    """Computes the dice metric between pairs of labels.

    Rotates the prediction label to find matching orientation as well.
    """
    # u = 0
    # t = 0

    threshold = self.threshold_box.value()
    rotate = self.rotate_choice.isChecked()

    total_metrics = []
    self.canvas = None  # kind of terrible way to stack plots... but it works.

    for image_id, (ground_path, pred_path) in enumerate(
        zip(self.images_filepaths, self.labels_filepaths, strict=False),
        start=1,
    ):
        ground = imread(ground_path)
        pred = imread(pred_path)

        ground = to_semantic(ground).astype(np.int8)
        pred = to_semantic(pred).astype(np.int8)

        pred_dims = pred.shape[-3:]
        pad_pred = utils.get_padding_dim(pred_dims)

        while len(pred.shape) < 5:
            pred = np.expand_dims(pred, axis=0)

        while len(ground.shape) < 4:
            ground = np.expand_dims(ground, axis=0)

        ground = (SpatialPad(pad_pred)(ToTensor()(ground))).numpy()

        while len(ground.shape) < len(pred.shape):
            ground = np.expand_dims(ground, axis=0)

        if ground.shape != pred.shape:
            raise ValueError(
                "Padded sizes of images do not match! "
                f"Padded ground label: {ground.shape}. "
                f"Padded pred label: {pred.shape}."
            )

        scores = []

        if rotate:
            pred_flip_x = np.rot90(pred[0][0], axes=(0, 1))
            pred_flip_y = np.rot90(pred[0][0], axes=(1, 2))
            pred_flip_z = np.rot90(pred[0][0], axes=(0, 2))

            for rotated_pred in [pred[0][0], pred_flip_x, pred_flip_y, pred_flip_z]:
                scores.append(utils.dice_coeff(rotated_pred, ground))
                scores.append(utils.dice_coeff(np.flip(rotated_pred), ground))

                for axis in range(3):
                    scores.append(
                        utils.dice_coeff(np.flip(rotated_pred, axis=axis), ground)
                    )
        else:
            scores.append(utils.dice_coeff(pred, ground))

        score = max(scores)

        if score < threshold:
            self._viewer.dims.ndisplay = 3
            self._viewer.add_image(
                ground, name=f"ground_{image_id}", colormap="blue", opacity=0.7
            )
            self._viewer.add_image(
                pred, name=f"pred_{image_id}", colormap="red", opacity=0.7
            )

        total_metrics.append(score)
    # print(f"DICE METRIC :{total_metrics}")
    self.plot_dice(total_metrics, threshold)

plot_dice

plot_dice(dice_coeffs, threshold=DEFAULT_THRESHOLD)

Plots the dice loss for each pair of labels on viewer.

Source code in napari_cellseg3d/code_plugins/plugin_metrics.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
def plot_dice(self, dice_coeffs, threshold=DEFAULT_THRESHOLD):
    """Plots the dice loss for each pair of labels on viewer."""
    self.btn_reset_plot.setVisible(True)
    colors = []

    bckgrd_color = (0, 0, 0, 0)

    for coeff in dice_coeffs:  # TODO add threshold manual setting
        if coeff < threshold:
            colors.append(ui.dark_red)  # 72071d # crimson red
        else:
            colors.append(ui.default_cyan)  # 8dd3c7 # turquoise cyan
    with plt.style.context("dark_background"):
        if self.canvas is None:
            self.canvas = FigureCanvas(Figure(figsize=(2, 5)))
            self.layout.addWidget(self.canvas)
            self.canvas.figure.tight_layout()
        else:
            self.dice_plot.cla()
        self.canvas.figure.set_facecolor(bckgrd_color)
        dice_plot = self.canvas.figure.add_subplot(1, 1, 1)
        labels = np.array(range(len(dice_coeffs))) + 1

        dice_plot.barh(labels, dice_coeffs, color=colors)
        dice_plot.set_facecolor(bckgrd_color)

        dice_plot.invert_yaxis()

        self.plots.append(self.canvas)
        dice_plot.axvline(threshold, color=ui.dark_red)
        dice_plot.set_title(
            f"Session {len(self.plots)}\nMean dice : {np.mean(dice_coeffs):.4f}"
        )
        # dice_plot.set_xticks(rotation=45)
        dice_plot.set_xlabel("Dice coefficient")
        # dice_plot.set_ylabel("Labels pair id", rotation=90)

        self.canvas.draw_idle()

remove_plots

remove_plots()

Clears plots from window view.

Source code in napari_cellseg3d/code_plugins/plugin_metrics.py
173
174
175
176
177
178
179
def remove_plots(self):
    """Clears plots from window view."""
    if self.plots:
        for p in self.plots:
            p.setVisible(False)
    self.plots = []
    self.btn_reset_plot.setVisible(False)