Skip to content

segmentation

segmentation_props(pred, mask)

Return some information regarding a segmentation task.

Parameters:

  • pred (ndarray[bool]) –

    Prediction of a segmentation model as a binary image.

  • mask (ndarray[bool]) –

    Ground truth mask as binary image

Returns:

  • float

    1-Dice(pred, mask) Given a matrix (a_ij) = (1-Dice)(prediction_i, ground_truth_j), where prediction_i is the i-th prediction connected component and ground_truth_j is the j-th ground truth connected component, I compute the LSA (Linear Sum Assignment) to find the optimal 1-to-1 assignment between predictions and ground truths that minimize the (1-Dice) score. Then, for every unique pair of (predictioni, ground_truthj) we compute Average (1-Dice)(predictioni, ground_truthj)

  • float

    Average (1-Dice)(predictioni, ground_truthj) between True Positives (that is predictions associated to a ground truth), which is gratis from a[i,j], where the average is computed w.r.t. the total number of True Positives found.

  • float

    Average IoU(predictioni, ground_truthj) between True Positives (that is predictions associated to a ground truth), where the average is computed w.r.t. the total number of True Positives found. The IoU is computed between the minimum enclosing bounding box of a prediction and a ground truth.

  • float

    Average area of False Positives

  • list[float]

    Histogram of false positives

  • float

    Average area of False Negatives

  • int

    Number of True Positives (predictions associated to a ground truth)

  • int

    Number of False Positives (predictions without a ground truth associated) and their avg. area (avg is taken w.r.t. the total number of False Positives found)

  • int

    Number of False Negatives (ground truth without a predictions associated) and their avg. area (avg is taken w.r.t. the total number of False Negatives found)

  • int

    Number of labels in the mask.

Source code in quadra/metrics/segmentation.py
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
def segmentation_props(
    pred: np.ndarray, mask: np.ndarray
) -> tuple[float, float, float, float, list[float], float, int, int, int, int]:
    """Return some information regarding a segmentation task.

    Args:
        pred (np.ndarray[bool]): Prediction of a segmentation model as
            a binary image.
        mask (np.ndarray[bool]): Ground truth mask as binary image

    Returns:
        1-Dice(pred, mask) Given a matrix (a_ij) = (1-Dice)(prediction_i, ground_truth_j),
            where prediction_i is the i-th prediction connected component and
            ground_truth_j is the j-th ground truth connected component,
            I compute the LSA (Linear Sum Assignment) to find the optimal 1-to-1 assignment
            between predictions and ground truths that minimize the (1-Dice) score.
            Then, for every unique pair of (predictioni, ground_truthj) we compute Average
             (1-Dice)(predictioni, ground_truthj)
        Average (1-Dice)(predictioni, ground_truthj) between True Positives
            (that is predictions associated to a ground truth), which is gratis from a[i,j],
            where the average is computed w.r.t. the total number of True Positives found.
        Average IoU(predictioni, ground_truthj) between True Positives
            (that is predictions associated to a ground truth),
            where the average is computed w.r.t. the total number of True Positives found.
            The IoU is computed between the minimum enclosing bounding box
            of a prediction and a ground truth.
        Average area of False Positives
        Histogram of false positives
        Average area of False Negatives
        Number of True Positives (predictions associated to a ground truth)
        Number of False Positives (predictions without a ground truth associated)
                and their avg. area (avg is taken w.r.t. the total number of False Positives found)
        Number of False Negatives (ground truth without a predictions associated)
            and their avg. area (avg is taken w.r.t. the total number of False Negatives found)
        Number of labels in the mask.
    """
    labels_pred, n_labels_pred = label(pred, connectivity=2, return_num=True, background=0)
    labels_mask, n_labels_mask = label(mask, connectivity=2, return_num=True, background=0)

    labels_pred = cast(np.ndarray, labels_pred)
    labels_mask = cast(np.ndarray, labels_mask)
    n_labels_pred = cast(int, n_labels_pred)
    n_labels_mask = cast(int, n_labels_mask)

    props_pred = regionprops(labels_pred)
    props_mask = regionprops(labels_mask)
    pred_bbox = np.array([props_pred[i].bbox for i in range(len(props_pred))])
    mask_bbox = np.array([props_mask[i].bbox for i in range(len(props_mask))])

    global_dice = float(
        dice(
            torch.Tensor(pred).unsqueeze(0).unsqueeze(0),
            torch.Tensor(mask).unsqueeze(0).unsqueeze(0),
        ).item()
    )
    lsa_iou = 0.0
    lsa_dice = 0.0
    tp_num = 0
    fp_num = 0
    fn_num = 0
    fp_area = 0.0
    fn_area = 0.0
    fp_hist: list[float] = []
    if n_labels_pred > 0 and n_labels_mask > 0:
        dice_mat = _get_dice_matrix(labels_pred, n_labels_pred, labels_mask, n_labels_mask)
        # Thresholding over Dice scores
        dice_mat = np.where(dice_mat <= 0.9, dice_mat, 1.0)
        iou_mat = _get_iou(pred_bbox, mask_bbox, approx_iou=False)
        dice_mat_shape = dice_mat.shape
        max_dim = np.max(dice_mat_shape)
        # Add dummy Dices so LSA is unique and i can compute FP and FN
        dice_mat = _pad_to_shape(dice_mat, (max_dim, max_dim), 1)
        lsa = linear_sum_assignment(dice_mat, maximize=False)
        for row, col in zip(lsa[0], lsa[1]):
            # More preds than GTs --> False Positive
            if row < n_labels_pred and col >= n_labels_mask:
                min_row = pred_bbox[row][0]
                min_col = pred_bbox[row][1]
                h = pred_bbox[row][2] - min_row
                w = pred_bbox[row][3] - min_col
                fp_num += 1
                area = pred[min_row : min_row + h, min_col : min_col + w].sum()
                fp_area += area
                fp_hist.append(area)
                continue

            # More GTs than preds --> False Negative
            if col < n_labels_mask and row >= n_labels_pred:
                min_row = mask_bbox[col][0]
                min_col = mask_bbox[col][1]
                h = mask_bbox[col][2] - min_row
                w = mask_bbox[col][3] - min_col
                fn_num += 1
                fn_area += mask[min_row : min_row + h, min_col : min_col + w].sum()
                continue

            # Real True Positive: a prediction has been assigned to a gt
            # with at least a 1-Dice score of 0.9
            if dice_mat[row, col] <= 0.9:
                tp_num += 1
                lsa_iou += iou_mat[row, col]
                lsa_dice += dice_mat[row, col]
            else:
                # Here we have both a FP and a FN
                min_row = pred_bbox[row][0]
                min_col = pred_bbox[row][1]
                h = pred_bbox[row][2] - min_row
                w = pred_bbox[row][3] - min_col
                fp_num += 1
                area = pred[min_row : min_row + h, min_col : min_col + w].sum()
                fp_area += area
                fp_hist.append(area)

                min_row = mask_bbox[col][0]
                min_col = mask_bbox[col][1]
                h = mask_bbox[col][2] - min_row
                w = mask_bbox[col][3] - min_col
                fn_num += 1
                fn_area += mask[min_row : min_row + h, min_col : min_col + w].sum()
    elif len(pred_bbox) > 0 and len(mask_bbox) == 0:  # No GTs --> FP
        for p_bbox in pred_bbox:
            min_row = p_bbox[0]
            min_col = p_bbox[1]
            h = p_bbox[2] - min_row
            w = p_bbox[3] - min_col
            fp_num += 1
            # print("FP area:", pred[min_row : min_row + h, min_col : min_col + w].sum())
            area = pred[min_row : min_row + h, min_col : min_col + w].sum()
            fp_area += area
            fp_hist.append(area)
    elif len(pred_bbox) == 0 and len(mask_bbox) > 0:  # No preds --> FN
        for m_bbox in mask_bbox:
            min_row = m_bbox[0]
            min_col = m_bbox[1]
            h = m_bbox[2] - min_row
            w = m_bbox[3] - min_col
            fn_num += 1
            # print("FN area:", mask[min_row : min_row + h, min_col : min_col + w].sum())
            fn_area += mask[min_row : min_row + h, min_col : min_col + w].sum()
    return (
        global_dice,
        lsa_dice,
        lsa_iou,
        fp_area,
        fp_hist,
        fn_area,
        tp_num,
        fp_num,
        fn_num,
        n_labels_mask,
    )