TLMHoang commited on
Commit
e224eee
·
verified ·
1 Parent(s): d2ee00f

Upload prepare_dataset.py

Browse files
Files changed (1) hide show
  1. prepare_dataset.py +349 -0
prepare_dataset.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Convert the original Varroa bbox dataset to Ultralytics YOLO format."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import random
8
+ import shutil
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ from PIL import Image
13
+
14
+
15
+ SPLITS = ("train", "val", "test")
16
+ IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg")
17
+ GT_SOURCES = ("gt_one", "gt_filtered")
18
+ CLASS_POLICIES = ("all", "only-class-1", "drop-class-3", "map-3-to-1")
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class SampleRecord:
23
+ """Single source image plus its annotation metadata."""
24
+
25
+ source_split: str
26
+ rel_image_path: str
27
+ class_token: str
28
+ boxes: list[list[float]]
29
+ is_positive: bool
30
+
31
+
32
+ def resolve_repo_root(root: str | Path) -> Path:
33
+ root = Path(root).expanduser().resolve()
34
+ missing = [split for split in SPLITS if not (root / split / "videos").is_dir()]
35
+ if missing:
36
+ raise FileNotFoundError(f"Missing split video folders under {root}: {', '.join(missing)}")
37
+ return root
38
+
39
+
40
+ def source_image_path(root_path: Path, record: SampleRecord) -> Path:
41
+ return root_path / record.source_split / record.rel_image_path
42
+
43
+
44
+ def flattened_name(image_path: Path, image_dir: Path) -> str:
45
+ return "__".join(image_path.relative_to(image_dir).parts)
46
+
47
+
48
+ def output_name_for_record(root_path: Path, record: SampleRecord) -> str:
49
+ image_path = source_image_path(root_path, record)
50
+ image_dir = root_path / record.source_split / "videos"
51
+ return f"{record.source_split}__{flattened_name(image_path, image_dir)}"
52
+
53
+
54
+ def iter_images(image_dir: Path) -> list[Path]:
55
+ images: list[Path] = []
56
+ for suffix in IMAGE_EXTENSIONS:
57
+ images.extend(image_dir.rglob(f"*{suffix}"))
58
+ return sorted(images)
59
+
60
+
61
+ def clamp_xyxy_boxes(boxes: list[list[float]], width: int, height: int) -> list[list[float]]:
62
+ clamped: list[list[float]] = []
63
+ for x1, y1, x2, y2 in boxes:
64
+ left, right = sorted((max(0.0, min(float(x1), width)), max(0.0, min(float(x2), width))))
65
+ top, bottom = sorted((max(0.0, min(float(y1), height)), max(0.0, min(float(y2), height))))
66
+ if right > left and bottom > top:
67
+ clamped.append([left, top, right, bottom])
68
+ return clamped
69
+
70
+
71
+ def yolo_rows_from_boxes(boxes: list[list[float]], width: int, height: int) -> list[str]:
72
+ rows: list[str] = []
73
+ for left, top, right, bottom in boxes:
74
+ box_w = right - left
75
+ box_h = bottom - top
76
+ cx = (left + right) * 0.5 / width
77
+ cy = (top + bottom) * 0.5 / height
78
+ rows.append(f"0 {cx:.8f} {cy:.8f} {box_w / width:.8f} {box_h / height:.8f}")
79
+ return rows
80
+
81
+
82
+ def read_original_boxes(label_path: Path) -> list[list[float]]:
83
+ """Read native label txt files where the first row is a count and later rows are xyxy."""
84
+ if not label_path.exists():
85
+ return []
86
+
87
+ boxes: list[list[float]] = []
88
+ for idx, line in enumerate(label_path.read_text(encoding="utf-8").splitlines()):
89
+ line = line.strip()
90
+ if not line:
91
+ continue
92
+ if idx == 0:
93
+ continue
94
+ parts = line.split()
95
+ if len(parts) >= 4:
96
+ boxes.append([float(parts[0]), float(parts[1]), float(parts[2]), float(parts[3])])
97
+ return boxes
98
+
99
+
100
+ def label_path_for(image_path: Path, image_dir: Path, label_dir: Path) -> Path:
101
+ return label_dir / image_path.relative_to(image_dir).with_suffix(".txt")
102
+
103
+
104
+ def parse_gt_csv(csv_path: Path) -> dict[str, list[list[float]]]:
105
+ """Backward-compatible parser for gt_filtered.csv-style files."""
106
+ return {record.rel_image_path: record.boxes for record in parse_gt_records(csv_path, infer_filtered_positive=True)}
107
+
108
+
109
+ def parse_gt_records(csv_path: Path, *, infer_filtered_positive: bool = False) -> list[SampleRecord]:
110
+ """Parse GT CSV rows into a uniform record structure."""
111
+ if not csv_path.exists():
112
+ return []
113
+
114
+ source_split = csv_path.parent.name
115
+ records: list[SampleRecord] = []
116
+ for line in csv_path.read_text(encoding="utf-8").splitlines():
117
+ line = line.strip()
118
+ if not line:
119
+ continue
120
+ parts = line.split()
121
+ if len(parts) < 2:
122
+ continue
123
+ rel_img_path = parts[0]
124
+ class_token = parts[1]
125
+ values = [float(value) for value in parts[2:]]
126
+ boxes = [values[idx : idx + 4] for idx in range(0, len(values) - 3, 4)]
127
+ if infer_filtered_positive and boxes:
128
+ class_token = "1"
129
+ is_positive = bool(boxes) and class_token != "0"
130
+ records.append(
131
+ SampleRecord(
132
+ source_split=source_split,
133
+ rel_image_path=rel_img_path,
134
+ class_token=class_token,
135
+ boxes=boxes,
136
+ is_positive=is_positive,
137
+ )
138
+ )
139
+ return records
140
+
141
+
142
+ def load_records(root_path: Path, gt_source: str) -> list[SampleRecord]:
143
+ records: list[SampleRecord] = []
144
+ for split in SPLITS:
145
+ csv_path = root_path / split / f"{gt_source}.csv"
146
+ records.extend(parse_gt_records(csv_path, infer_filtered_positive=(gt_source == "gt_filtered")))
147
+ return records
148
+
149
+
150
+ def filter_records(
151
+ records: list[SampleRecord],
152
+ *,
153
+ only_positives: bool,
154
+ class_policy: str,
155
+ ) -> list[SampleRecord]:
156
+ filtered: list[SampleRecord] = []
157
+ for record in records:
158
+ if only_positives and not record.is_positive:
159
+ continue
160
+ if class_policy == "only-class-1" and record.class_token != "1":
161
+ continue
162
+ if class_policy == "drop-class-3" and record.class_token == "3":
163
+ continue
164
+ if class_policy == "map-3-to-1" and record.class_token == "3":
165
+ record = SampleRecord(
166
+ source_split=record.source_split,
167
+ rel_image_path=record.rel_image_path,
168
+ class_token="1",
169
+ boxes=record.boxes,
170
+ is_positive=record.is_positive,
171
+ )
172
+ filtered.append(record)
173
+ return filtered
174
+
175
+
176
+ def dedupe_records(records: list[SampleRecord]) -> list[SampleRecord]:
177
+ deduped: list[SampleRecord] = []
178
+ seen: set[tuple[str, str]] = set()
179
+ for record in records:
180
+ key = (record.source_split, record.rel_image_path)
181
+ if key in seen:
182
+ continue
183
+ seen.add(key)
184
+ deduped.append(record)
185
+ return deduped
186
+
187
+
188
+ def assign_output_splits(
189
+ records: list[SampleRecord],
190
+ *,
191
+ seed: int,
192
+ ) -> dict[str, list[SampleRecord]]:
193
+ shuffled = list(records)
194
+ random.Random(seed).shuffle(shuffled)
195
+
196
+ total = len(shuffled)
197
+ val_end = round(total * 0.15)
198
+ test_end = val_end + round(total * 0.15)
199
+
200
+ return {
201
+ "train": shuffled[test_end:],
202
+ "val": shuffled[:val_end],
203
+ "test": shuffled[val_end:test_end],
204
+ }
205
+
206
+
207
+ def write_data_yaml(
208
+ out_dir: Path,
209
+ *,
210
+ split_counts: dict[str, int],
211
+ gt_source: str,
212
+ only_positives: bool,
213
+ class_policy: str,
214
+ seed: int,
215
+ ) -> Path:
216
+ yaml_path = out_dir / "varroa.yaml"
217
+ splits_line = (
218
+ f"split_counts: {{train: {split_counts['train']}, "
219
+ f"val: {split_counts['val']}, test: {split_counts['test']}}}"
220
+ )
221
+ yaml_path.write_text(
222
+ "\n".join(
223
+ [
224
+ f"path: {out_dir.resolve()}",
225
+ "train: images/train",
226
+ "val: images/val",
227
+ "test: images/test",
228
+ "nc: 1",
229
+ "names: [varroa]",
230
+ splits_line,
231
+ f"gt_source: {gt_source}",
232
+ f"only_positives: {str(only_positives).lower()}",
233
+ f"class_policy: {class_policy}",
234
+ f"seed: {seed}",
235
+ "",
236
+ ]
237
+ ),
238
+ encoding="utf-8",
239
+ )
240
+ return yaml_path
241
+
242
+
243
+ def prepare_dataset(
244
+ root: str | Path = ".",
245
+ out_dir: str | Path = "yolo_related/datasets/varroa_yolo",
246
+ *,
247
+ overwrite_labels: bool = True,
248
+ copy_images: bool = True,
249
+ limit: int = 0,
250
+ gt_source: str = "gt_one",
251
+ only_positives: bool = True,
252
+ class_policy: str = "map-3-to-1",
253
+ seed: int = 42,
254
+ ) -> Path:
255
+ if gt_source not in GT_SOURCES:
256
+ raise ValueError(f"Unsupported gt_source: {gt_source}")
257
+ if class_policy not in CLASS_POLICIES:
258
+ raise ValueError(f"Unsupported class_policy: {class_policy}")
259
+
260
+ root_path = resolve_repo_root(root)
261
+ out_path = Path(out_dir).expanduser()
262
+ if not out_path.is_absolute():
263
+ out_path = (root_path / out_path).resolve()
264
+
265
+ records = load_records(root_path, gt_source)
266
+ records = filter_records(records, only_positives=only_positives, class_policy=class_policy)
267
+ records = dedupe_records(records)
268
+ split_records = assign_output_splits(records, seed=seed)
269
+
270
+ split_counts: dict[str, int] = {}
271
+ for split in SPLITS:
272
+ records_for_split = split_records[split]
273
+ if limit > 0:
274
+ records_for_split = records_for_split[:limit]
275
+ split_records[split] = records_for_split
276
+ split_counts[split] = len(records_for_split)
277
+
278
+ yolo_image_dir = out_path / "images" / split
279
+ yolo_label_dir = out_path / "labels" / split
280
+ if copy_images and yolo_image_dir.exists():
281
+ shutil.rmtree(yolo_image_dir)
282
+ if overwrite_labels and yolo_label_dir.exists():
283
+ shutil.rmtree(yolo_label_dir)
284
+ yolo_image_dir.mkdir(parents=True, exist_ok=True)
285
+ yolo_label_dir.mkdir(parents=True, exist_ok=True)
286
+
287
+ for record in records_for_split:
288
+ image_path = source_image_path(root_path, record)
289
+ dst_name = output_name_for_record(root_path, record)
290
+ dst_image = yolo_image_dir / dst_name
291
+ dst_label = yolo_label_dir / Path(dst_name).with_suffix(".txt").name
292
+
293
+ if copy_images:
294
+ shutil.copy2(image_path, dst_image)
295
+
296
+ if overwrite_labels or not dst_label.exists():
297
+ with Image.open(image_path) as image:
298
+ width, height = image.size
299
+ boxes = clamp_xyxy_boxes(record.boxes, width, height)
300
+ dst_label.write_text("\n".join(yolo_rows_from_boxes(boxes, width, height)), encoding="utf-8")
301
+
302
+ return write_data_yaml(
303
+ out_path,
304
+ split_counts=split_counts,
305
+ gt_source=gt_source,
306
+ only_positives=only_positives,
307
+ class_policy=class_policy,
308
+ seed=seed,
309
+ )
310
+
311
+
312
+ def parse_args() -> argparse.Namespace:
313
+ parser = argparse.ArgumentParser(description="Convert Varroa labels to Ultralytics YOLO format.")
314
+ parser.add_argument("--root", default=".", help="Repo root containing train/val/test folders.")
315
+ parser.add_argument("--out-dir", default="yolo_related/datasets/varroa_yolo")
316
+ parser.add_argument("--limit", type=int, default=0, help="Optional max images per split for smoke tests.")
317
+ parser.add_argument("--no-copy-images", action="store_true", help="Only write labels/YAML; do not copy images.")
318
+ parser.add_argument("--keep-labels", action="store_true", help="Do not overwrite existing YOLO label files.")
319
+ parser.add_argument("--gt-source", default="gt_one", choices=GT_SOURCES)
320
+ parser.add_argument(
321
+ "--only-positives",
322
+ action=argparse.BooleanOptionalAction,
323
+ default=True,
324
+ help="Keep only positive rows. Use --no-only-positives to keep token 0 rows.",
325
+ )
326
+ parser.add_argument("--class-policy", default="map-3-to-1", choices=CLASS_POLICIES)
327
+ parser.add_argument("--seed", type=int, default=42)
328
+ return parser.parse_args()
329
+
330
+
331
+ def main() -> None:
332
+ args = parse_args()
333
+ yaml_path = prepare_dataset(
334
+ args.root,
335
+ args.out_dir,
336
+ overwrite_labels=not args.keep_labels,
337
+ copy_images=not args.no_copy_images,
338
+ limit=args.limit,
339
+ gt_source=args.gt_source,
340
+ only_positives=args.only_positives,
341
+ class_policy=args.class_policy,
342
+ seed=args.seed,
343
+ )
344
+ print(f"YOLO dataset ready: {yaml_path}")
345
+ print(yaml_path.read_text(encoding='utf-8'))
346
+
347
+
348
+ if __name__ == "__main__":
349
+ main()