TLMHoang commited on
Commit
393b9b3
·
verified ·
1 Parent(s): 4987807

Upload prepare_dataset.py

Browse files
Files changed (1) hide show
  1. prepare_dataset.py +167 -0
prepare_dataset.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Convert the original Varroa bbox dataset to Ultralytics YOLO format.
3
+
4
+ This module is intentionally standalone. It does not import from
5
+ object_detection_related so YOLO experiments can evolve independently.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import shutil
12
+ from pathlib import Path
13
+
14
+ from PIL import Image
15
+
16
+
17
+ SPLITS = ("train", "val", "test")
18
+ IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg")
19
+
20
+
21
+ def resolve_repo_root(root: str | Path) -> Path:
22
+ root = Path(root).expanduser().resolve()
23
+ missing = [split for split in SPLITS if not (root / split / "videos").is_dir()]
24
+ if missing:
25
+ raise FileNotFoundError(f"Missing split video folders under {root}: {', '.join(missing)}")
26
+ return root
27
+
28
+
29
+ def label_path_for(image_path: Path, image_dir: Path, label_dir: Path) -> Path:
30
+ return (label_dir / image_path.relative_to(image_dir)).with_suffix(".txt")
31
+
32
+
33
+ def read_original_boxes(label_path: Path) -> list[list[float]]:
34
+ """Read original label files: first line count, remaining values are xyxy pixels."""
35
+ if not label_path.exists():
36
+ return []
37
+
38
+ lines = [line.strip() for line in label_path.read_text(encoding="utf-8").splitlines() if line.strip()]
39
+ if not lines:
40
+ return []
41
+
42
+ boxes: list[list[float]] = []
43
+ for line in lines[1:]:
44
+ values = [float(value) for value in line.replace(",", " ").split()]
45
+ for idx in range(0, len(values) - 3, 4):
46
+ boxes.append(values[idx : idx + 4])
47
+ return boxes
48
+
49
+
50
+ def clamp_xyxy_boxes(boxes: list[list[float]], width: int, height: int) -> list[list[float]]:
51
+ clamped: list[list[float]] = []
52
+ for x1, y1, x2, y2 in boxes:
53
+ left, right = sorted((max(0.0, min(float(x1), width)), max(0.0, min(float(x2), width))))
54
+ top, bottom = sorted((max(0.0, min(float(y1), height)), max(0.0, min(float(y2), height))))
55
+ if right > left and bottom > top:
56
+ clamped.append([left, top, right, bottom])
57
+ return clamped
58
+
59
+
60
+ def yolo_rows_from_boxes(boxes: list[list[float]], width: int, height: int) -> list[str]:
61
+ rows: list[str] = []
62
+ for left, top, right, bottom in boxes:
63
+ box_w = right - left
64
+ box_h = bottom - top
65
+ cx = (left + right) * 0.5 / width
66
+ cy = (top + bottom) * 0.5 / height
67
+ rows.append(f"0 {cx:.8f} {cy:.8f} {box_w / width:.8f} {box_h / height:.8f}")
68
+ return rows
69
+
70
+
71
+ def flattened_name(image_path: Path, image_dir: Path) -> str:
72
+ return "__".join(image_path.relative_to(image_dir).parts)
73
+
74
+
75
+ def iter_images(image_dir: Path) -> list[Path]:
76
+ images: list[Path] = []
77
+ for suffix in IMAGE_EXTENSIONS:
78
+ images.extend(image_dir.rglob(f"*{suffix}"))
79
+ return sorted(images)
80
+
81
+
82
+ def write_data_yaml(out_dir: Path) -> Path:
83
+ yaml_path = out_dir / "varroa.yaml"
84
+ yaml_path.write_text(
85
+ "\n".join(
86
+ [
87
+ f"path: {out_dir.resolve()}",
88
+ "train: images/train",
89
+ "val: images/val",
90
+ "test: images/test",
91
+ "nc: 1",
92
+ "names: [varroa]",
93
+ "",
94
+ ]
95
+ ),
96
+ encoding="utf-8",
97
+ )
98
+ return yaml_path
99
+
100
+
101
+ def prepare_dataset(
102
+ root: str | Path = ".",
103
+ out_dir: str | Path = "yolo_related/datasets/varroa_yolo",
104
+ *,
105
+ overwrite_labels: bool = True,
106
+ copy_images: bool = True,
107
+ limit: int = 0,
108
+ ) -> Path:
109
+ root_path = resolve_repo_root(root)
110
+ out_path = Path(out_dir).expanduser()
111
+ if not out_path.is_absolute():
112
+ out_path = (root_path / out_path).resolve()
113
+
114
+ for split in SPLITS:
115
+ image_dir = root_path / split / "videos"
116
+ label_dir = root_path / split / "labels"
117
+ yolo_image_dir = out_path / "images" / split
118
+ yolo_label_dir = out_path / "labels" / split
119
+ yolo_image_dir.mkdir(parents=True, exist_ok=True)
120
+ yolo_label_dir.mkdir(parents=True, exist_ok=True)
121
+
122
+ images = iter_images(image_dir)
123
+ if limit > 0:
124
+ images = images[:limit]
125
+
126
+ for image_path in images:
127
+ dst_name = flattened_name(image_path, image_dir)
128
+ dst_image = yolo_image_dir / dst_name
129
+ dst_label = yolo_label_dir / Path(dst_name).with_suffix(".txt").name
130
+
131
+ if copy_images and not dst_image.exists():
132
+ shutil.copy2(image_path, dst_image)
133
+
134
+ if overwrite_labels or not dst_label.exists():
135
+ with Image.open(image_path) as image:
136
+ width, height = image.size
137
+ original_label = label_path_for(image_path, image_dir, label_dir)
138
+ boxes = clamp_xyxy_boxes(read_original_boxes(original_label), width, height)
139
+ dst_label.write_text("\n".join(yolo_rows_from_boxes(boxes, width, height)), encoding="utf-8")
140
+
141
+ return write_data_yaml(out_path)
142
+
143
+
144
+ def parse_args() -> argparse.Namespace:
145
+ parser = argparse.ArgumentParser(description="Convert Varroa labels to Ultralytics YOLO format.")
146
+ parser.add_argument("--root", default=".", help="Repo root containing train/val/test folders.")
147
+ parser.add_argument("--out-dir", default="yolo_related/datasets/varroa_yolo")
148
+ parser.add_argument("--limit", type=int, default=0, help="Optional max images per split for smoke tests.")
149
+ parser.add_argument("--no-copy-images", action="store_true", help="Only write labels/YAML; do not copy images.")
150
+ parser.add_argument("--keep-labels", action="store_true", help="Do not overwrite existing YOLO label files.")
151
+ return parser.parse_args()
152
+
153
+
154
+ def main() -> None:
155
+ args = parse_args()
156
+ yaml_path = prepare_dataset(
157
+ args.root,
158
+ args.out_dir,
159
+ overwrite_labels=not args.keep_labels,
160
+ copy_images=not args.no_copy_images,
161
+ limit=args.limit,
162
+ )
163
+ print(f"YOLO dataset ready: {yaml_path}")
164
+
165
+
166
+ if __name__ == "__main__":
167
+ main()