Skip to content

Commit 2d343a2

Browse files
authored
Merge pull request #75 from SonanceAI/feat/DAT-946
Update notebooks to match the new refactorings (DAT-946)
2 parents c592be0 + e3eab51 commit 2d343a2

10 files changed

Lines changed: 153 additions & 724 deletions

File tree

datamint/dataset/base.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1008,6 +1008,8 @@ def _process_segmentations(self,
10081008
segmentations,
10091009
strategy=self.semantic_seg_merge_strategy
10101010
)
1011+
if isinstance(segmentations, np.ndarray):
1012+
segmentations = torch.from_numpy(segmentations).to(torch.get_default_dtype())
10111013
_LOGGER.debug("Merged segmentation shape: %s", segmentations.shape)
10121014
else:
10131015
if output_shape is None:

datamint/dataset/image_dataset.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,8 @@ def apply_alb_transform(
8585
box_labels_tensor = targets.get('box_labels')
8686
if boxes_tensor is not None:
8787
alb_kwargs['bboxes'] = boxes_tensor.tolist() if isinstance(boxes_tensor, torch.Tensor) else list(boxes_tensor)
88-
alb_kwargs['box_labels'] = box_labels_tensor.tolist() if isinstance(box_labels_tensor, torch.Tensor) else list(box_labels_tensor)
88+
# Use 'labels': the standard albumentations label_fields key convention.
89+
alb_kwargs['labels'] = box_labels_tensor.tolist() if isinstance(box_labels_tensor, torch.Tensor) else list(box_labels_tensor)
8990

9091
aug = self.alb_transform(**alb_kwargs)
9192
aug_img = aug['image']
@@ -104,10 +105,10 @@ def apply_alb_transform(
104105
start += count
105106
result['masks'] = aug_segmentations
106107

107-
# Reconstruct boxes
108+
# Reconstruct boxes, map 'labels' back to 'box_labels' in our output dict
108109
if boxes_tensor is not None:
109110
aug_bboxes: list = list(aug.get('bboxes', []))
110-
aug_box_labels: list = list(aug.get('box_labels', []))
111+
aug_box_labels: list = list(aug.get('labels', []))
111112
if aug_bboxes:
112113
result['boxes'] = torch.tensor(aug_bboxes, dtype=torch.float32)
113114
result['box_labels'] = torch.tensor(aug_box_labels, dtype=torch.int64)

datamint/dataset/sliced_dataset.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -459,7 +459,7 @@ def __getitem__(self, index: int) -> dict[str, Any]:
459459
460460
Returns dict with:
461461
- 'image': np.ndarray or Tensor of shape (C, H, W).
462-
- 'segmentations' (if enabled): segmentation masks with depth dimension removed.
462+
- 'masks' (if enabled): segmentation masks with depth dimension removed.
463463
- 'image_labels': dict of annotator -> label tensor.
464464
"""
465465
if index >= len(self):
@@ -482,10 +482,10 @@ def __getitem__(self, index: int) -> dict[str, Any]:
482482

483483
# Apply albumentations if present
484484
if self.alb_transform:
485-
aug_result = self.apply_alb_transform(img, sliced_segs)
485+
aug_result = self.apply_alb_transform(img, {'masks': sliced_segs})
486486
img = aug_result['image']
487487
result['image'] = img
488-
sliced_segs = aug_result['segmentations']
488+
sliced_segs = aug_result.get('masks', {})
489489

490490
segmentations_processed, seg_labels_out = self._process_segmentations(sliced_segs, seg_labels,
491491
output_shape=img.shape[1:])
@@ -497,9 +497,9 @@ def __getitem__(self, index: int) -> dict[str, Any]:
497497
if isinstance(segmentations_processed[author], (Tensor, np.ndarray)):
498498
segmentations_processed[author] = segmentations_processed[author].squeeze(1)
499499

500-
result['segmentations'] = segmentations_processed
500+
result['masks'] = segmentations_processed
501501
if seg_labels_out:
502-
result['seg_labels'] = seg_labels_out
502+
result['mask_labels'] = seg_labels_out
503503

504504
# Process image-level labels
505505
result['image_labels'] = self._extract_image_labels(annotations)
@@ -520,22 +520,22 @@ def __getitem__(self, index: int) -> dict[str, Any]:
520520
def apply_alb_transform(
521521
self,
522522
img: np.ndarray,
523-
segmentations: dict[str, np.ndarray],
523+
targets: dict[str, Any],
524524
) -> dict[str, Any]:
525525
"""Apply 2D albumentations transform to a single-slice image and masks.
526526
527-
Uses the same approach as ImageDataset: treats the data as 2D.
528-
529527
Args:
530528
img: Image array of shape (C, 1, H, W) or (C, H, W).
531-
segmentations: Dict of author -> mask arrays of shape (#instances, 1, H, W) or (#instances, H, W).
529+
targets: Dict with optional key ``'masks'``: author -> array (#instances, 1, H, W).
532530
533531
Returns:
534-
Dict with transformed 'image' and 'segmentations'.
532+
Dict with transformed ``'image'`` and ``'masks'``.
535533
"""
536534
if self.alb_transform is None:
537535
raise ValueError("alb_transform is not set")
538536

537+
segmentations = targets.get('masks', {})
538+
539539
# Squeeze depth=1 if present
540540
orig_dim = img.ndim
541541
if orig_dim == 4:
@@ -578,10 +578,10 @@ def apply_alb_transform(
578578
if orig_dim == 4:
579579
aug_img = aug_img[:, np.newaxis, :, :]
580580

581-
return {
582-
'image': aug_img,
583-
'segmentations': aug_segmentations,
584-
}
581+
result: dict[str, Any] = {'image': aug_img}
582+
if aug_segmentations:
583+
result['masks'] = aug_segmentations
584+
return result
585585

586586
def __repr__(self) -> str:
587587
base = super().__repr__()

datamint/lightning/trainers/lightning_modules/detection_modules/yolox_module.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ def forward(self, x: Tensor) -> Tensor:
129129

130130
def training_step(self, batch: dict, batch_idx: int) -> Tensor:
131131
images: Tensor = batch['image']
132-
targets = self._build_targets(batch['boxes'], batch['labels'], images.device)
132+
targets = self._build_targets(batch['boxes'], batch['box_labels'], images.device)
133133
outputs: dict = self.model(images, targets)
134134
self.log('train/loss', outputs['total_loss'], prog_bar=True, on_step=True, on_epoch=True)
135135
self.log('train/iou_loss', outputs['iou_loss'], on_step=False, on_epoch=True)
@@ -167,7 +167,7 @@ def validation_step(self, batch: dict, batch_idx: int) -> None:
167167
})
168168
target_list.append({
169169
'boxes': batch['boxes'][i].cpu(),
170-
'labels': batch['labels'][i].cpu(),
170+
'labels': batch['box_labels'][i].cpu(),
171171
})
172172

173173
self.map_metric.update(pred_list, target_list)

datamint/lightning/trainers/specialized/yolox.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def _train_transform(self) -> 'BaseCompose':
118118

119119
bbox_params = A.BboxParams(
120120
format='pascal_voc',
121-
label_fields=['labels', 'identifiers'],
121+
label_fields=['labels'],
122122
min_visibility=0.0,
123123
)
124124
return A.Compose([
@@ -136,7 +136,7 @@ def _eval_transform(self) -> 'BaseCompose':
136136

137137
bbox_params = A.BboxParams(
138138
format='pascal_voc',
139-
label_fields=['labels', 'identifiers'],
139+
label_fields=['labels'],
140140
min_visibility=0.0,
141141
)
142142
return A.Compose([

0 commit comments

Comments
 (0)