Coverage for collectra/tasks/image_segmentation/mask_metrics.py: 100.00%

20 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-13 04:26 +0000

1"""Shared, class-aware foreground overlap for bitmap segmentation trainers.""" 

2 

3 

4def mask_overlap(prediction, target, threshold): 

5 """Class-aware foreground intersection/union, independent of instance order. 

6 

7 Validation targets use the resized image grid; RF-DETR's postprocessor uses 

8 original image dimensions. Compare unions on the target grid, excluding 

9 low-confidence predictions and retaining false positives in absent classes. 

10 """ 

11 import torch 

12 from torch.nn.functional import interpolate 

13 

14 masks = prediction["masks"] 

15 if masks.ndim == 4: 

16 masks = masks[:, 0] 

17 keep = prediction["scores"] >= threshold 

18 masks, labels = masks[keep], prediction["labels"][keep] 

19 truth = target["masks"].bool() 

20 if len(masks) and masks.shape[-2:] != truth.shape[-2:]: 

21 masks = interpolate(masks[:, None].float(), size=truth.shape[-2:], mode="nearest")[:, 0].bool() 

22 intersection = torch.zeros((), dtype=torch.int64, device=truth.device) 

23 union = intersection.clone() 

24 classes = torch.cat((labels, target["labels"])).unique() 

25 for label in classes: 

26 predicted = masks[labels == label].any(0) if (labels == label).any() else torch.zeros( 

27 truth.shape[-2:], dtype=torch.bool, device=truth.device, 

28 ) 

29 actual = truth[target["labels"] == label].any(0) 

30 intersection += (predicted & actual).sum() 

31 union += (predicted | actual).sum() 

32 return torch.stack((intersection, union)) 

33 

34