File size: 7,846 Bytes
a490ef3
 
8e24178
a490ef3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3010da
 
 
 
 
 
 
 
a490ef3
 
 
 
 
 
2482d63
a490ef3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2482d63
a490ef3
 
 
8e24178
 
 
 
 
 
a490ef3
 
 
 
 
 
 
8e24178
 
 
 
 
 
 
a490ef3
 
 
 
 
 
 
 
b3010da
 
 
 
a490ef3
 
b3010da
a490ef3
b3010da
 
 
a490ef3
8e24178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a490ef3
 
 
 
 
 
 
 
 
 
 
 
 
b3010da
a490ef3
 
 
 
 
 
 
 
8e24178
 
 
 
 
a490ef3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
from pathlib import Path

import albumentations as A
from PIL import Image

try:
    import numpy as np
except ImportError:
    np = None

try:
    import torch
    from torch.utils.data import Dataset
except ImportError:
    torch = None

    class Dataset:
        pass


def resolve_split_root(root, split):
    root = Path(root)
    candidates = [root / split, root / split / split, root]
    for candidate in candidates:
        if (candidate / "videos").is_dir() and (candidate / "labels").is_dir():
            return candidate
    checked = "\n".join(str(candidate) for candidate in candidates)
    raise FileNotFoundError(f"Could not resolve split '{split}'. Checked:\n{checked}")


def label_path_for(image_path, image_dir, label_dir):
    return (label_dir / image_path.relative_to(image_dir)).with_suffix(".txt")


def read_varroa_boxes(label_path):
    if not label_path.exists():
        return []

    lines = [line.strip() for line in label_path.read_text().splitlines() if line.strip()]
    if not lines:
        return []

    boxes = []
    for line in lines[1:]:
        values = [float(x) for x in line.replace(",", " ").split()]
        for i in range(0, len(values) - 3, 4):
            boxes.append(values[i : i + 4])
    return boxes


def clamp_boxes_xyxy(boxes, width, height):
    clamped = []
    for x1, y1, x2, y2 in boxes:
        left, right = sorted((max(0.0, min(float(x1), width)), max(0.0, min(float(x2), width))))
        top, bottom = sorted((max(0.0, min(float(y1), height)), max(0.0, min(float(y2), height))))
        if right > left and bottom > top:
            clamped.append([left, top, right, bottom])
    return clamped


def letterbox_image_and_boxes(image, boxes, input_height, input_width):
    if np is None:
        raise ImportError("VarroaDetectionDataset requires numpy. Install numpy in the training environment.")

    width, height = image.size
    scale = min(input_width / width, input_height / height)
    resized_width = int(round(width * scale))
    resized_height = int(round(height * scale))
    pad_x = (input_width - resized_width) // 2
    pad_y = (input_height - resized_height) // 2

    if (resized_width, resized_height) != (width, height):
        image = image.resize((resized_width, resized_height), Image.BILINEAR)

    if resized_width == input_width and resized_height == input_height:
        canvas = image
    else:
        canvas = Image.new("RGB", (input_width, input_height), (0, 0, 0))
        canvas.paste(image, (pad_x, pad_y))

    boxes = np.asarray(boxes, dtype=np.float32).reshape(-1, 4)
    if len(boxes):
        boxes[:, [0, 2]] = boxes[:, [0, 2]] * scale + pad_x
        boxes[:, [1, 3]] = boxes[:, [1, 3]] * scale + pad_y
        boxes = clamp_boxes_xyxy(boxes, input_width, input_height)
        boxes = np.asarray(boxes, dtype=np.float32).reshape(-1, 4)
    return canvas, boxes, scale, pad_x, pad_y


class VarroaDetectionDataset(Dataset):
    """Varroa bbox dataset.

    Original layout:
      train|val|test/
        videos/<video-id>/*.png
        labels/<video-id>/*.txt

    Label files contain a first line with object count, then xyxy boxes in pixels.
    """

    def __init__(
        self,
        root=".",
        split="train",
        input_size=(288, 160),
        train=False,
        include_empty=True,
        normalize=True,
        hflip_prob=0.5,
        color_jitter_prob=0.25,
        color_jitter_brightness=0.2,
        color_jitter_contrast=0.0,
        color_jitter_saturation=0.0,
        color_jitter_hue=0.0,
    ):
        self.root = Path(root)
        self.split = split
        self.input_height, self.input_width = input_size
        self.train = train
        self.include_empty = include_empty
        self.normalize = normalize
        self.hflip_prob = hflip_prob
        self.color_jitter_prob = color_jitter_prob
        self.color_jitter_brightness = color_jitter_brightness
        self.color_jitter_contrast = color_jitter_contrast
        self.color_jitter_saturation = color_jitter_saturation
        self.color_jitter_hue = color_jitter_hue
        self.transform = self._build_transform()

        split_root = resolve_split_root(self.root, split)
        self.image_dir = split_root / "videos"
        self.label_dir = split_root / "labels"
        all_images = sorted(self.image_dir.rglob("*.png"))
        if not all_images:
            raise FileNotFoundError(f"No PNG images found under {self.image_dir}")

        all_boxes = [
            read_varroa_boxes(label_path_for(path, self.image_dir, self.label_dir))
            for path in all_images
        ]
        if include_empty:
            self.images = all_images
            self.raw_boxes = all_boxes
        else:
            kept = [(path, boxes) for path, boxes in zip(all_images, all_boxes) if boxes]
            self.images = [path for path, _ in kept]
            self.raw_boxes = [boxes for _, boxes in kept]

    def _build_transform(self):
        if not self.train:
            return None
        return A.Compose(
            [
                A.HorizontalFlip(p=self.hflip_prob),
                A.ColorJitter(
                    brightness=self.color_jitter_brightness,
                    contrast=self.color_jitter_contrast,
                    saturation=self.color_jitter_saturation,
                    hue=self.color_jitter_hue,
                    p=self.color_jitter_prob,
                ),
            ],
            bbox_params=A.BboxParams(
                format="pascal_voc",
                label_fields=["labels"],
                min_area=0.0,
                min_visibility=0.0,
            ),
        )

    def __len__(self):
        return len(self.images)

    def __getitem__(self, idx):
        if torch is None:
            raise ImportError("VarroaDetectionDataset requires torch. Install torch in the training environment.")
        if np is None:
            raise ImportError("VarroaDetectionDataset requires numpy. Install numpy in the training environment.")

        image_path = self.images[idx]
        image = Image.open(image_path).convert("RGB")
        orig_width, orig_height = image.size
        boxes = clamp_boxes_xyxy(
            self.raw_boxes[idx],
            orig_width,
            orig_height,
        )

        image, boxes, scale, pad_x, pad_y = letterbox_image_and_boxes(
            image, boxes, self.input_height, self.input_width
        )

        if self.transform is not None:
            labels = [1] * len(boxes)
            transformed = self.transform(image=np.asarray(image), bboxes=boxes.tolist(), labels=labels)
            image = Image.fromarray(transformed["image"])
            boxes = np.asarray(transformed["bboxes"], dtype=np.float32).reshape(-1, 4)

        array = np.asarray(image, dtype=np.float32) / 255.0
        if self.normalize:
            mean = np.asarray([0.485, 0.456, 0.406], dtype=np.float32)
            std = np.asarray([0.229, 0.224, 0.225], dtype=np.float32)
            array = (array - mean) / std
        tensor = torch.from_numpy(array).permute(2, 0, 1).contiguous()

        boxes_tensor = torch.as_tensor(boxes, dtype=torch.float32)
        target = {
            "boxes": boxes_tensor,
            "labels": torch.ones((boxes_tensor.shape[0],), dtype=torch.long),
            "image_id": torch.tensor(idx, dtype=torch.long),
            "orig_size": torch.tensor([orig_height, orig_width], dtype=torch.long),
            "scale_pad": torch.tensor([scale, pad_x, pad_y], dtype=torch.float32),
            "path": str(image_path),
        }
        return tensor, target


def detection_collate(batch):
    if torch is None:
        raise ImportError("detection_collate requires torch. Install torch in the training environment.")
    images, targets = zip(*batch)
    return torch.stack(images, dim=0), list(targets)