markus-42 commited on
Commit
e35a825
·
verified ·
1 Parent(s): 5d930e0

Upload OccuFly.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. OccuFly.py +334 -0
OccuFly.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ OccuFly Dataset Builder for Hugging Face Datasets.
3
+
4
+ Compatible with datasets>=2.0.0
5
+
6
+ Enables users to load the dataset with:
7
+ from datasets import load_dataset
8
+ dataset = load_dataset("username/occufly_test")
9
+ """
10
+
11
+ import datasets
12
+ from datasets import GeneratorBasedBuilder, BuilderConfig, Features, Image, Value, Array3D
13
+ import zipfile
14
+ import tempfile
15
+ from pathlib import Path
16
+ import numpy as np
17
+ from typing import Optional
18
+ from huggingface_hub import hf_hub_download
19
+ from PIL import Image as PILImage
20
+
21
+ logger = datasets.logging.get_logger(__name__)
22
+
23
+
24
+ class OccuFlyConfig(BuilderConfig):
25
+ """Builder config for OccuFly."""
26
+
27
+ def __init__(self, include_predictions=False, **kwargs):
28
+ """
29
+ Args:
30
+ include_predictions: If True, includes predicted depth maps
31
+ """
32
+ super().__init__(**kwargs)
33
+ self.include_predictions = include_predictions
34
+
35
+
36
+ class OccuFly(GeneratorBasedBuilder):
37
+ """OccuFly aerial dataset with depth, ground truth, and calibration."""
38
+
39
+ VERSION = datasets.Version("1.0.0")
40
+
41
+ BUILDER_CONFIGS = [
42
+ OccuFlyConfig(
43
+ name="default",
44
+ version=VERSION,
45
+ description="OccuFly dataset without depth predictions",
46
+ include_predictions=False,
47
+ ),
48
+ OccuFlyConfig(
49
+ name="with_predictions",
50
+ version=VERSION,
51
+ description="OccuFly dataset with predicted depth maps",
52
+ include_predictions=True,
53
+ ),
54
+ ]
55
+
56
+ DEFAULT_CONFIG_NAME = "default"
57
+
58
+ SCENES = {1, 2, 3, 4, 5, 6, 7, 8, 9}
59
+ ALTITUDES = {30, 40, 50}
60
+ SPLITS = {
61
+ "train": [1, 2, 3, 4, 5],
62
+ "validation": [6, 7],
63
+ "test": [8, 9]
64
+ }
65
+
66
+ def _info(self):
67
+ """Define dataset schema."""
68
+ features = {
69
+ "scene": Value("int32"),
70
+ "altitude": Value("int32"),
71
+ "frame_id": Value("int32"),
72
+ "image": Image(),
73
+ # Depth map from 3D reconstruction
74
+ "depth_map": Array3D(dtype="float32", shape=(None, None)),
75
+ # 3D Voxel grid ground truth (192, 128, 128) in camera coordinate system
76
+ # Physical coverage: 96m (W) × 64m (H) × 64m (D) at 0.5m voxel size
77
+ # Origin at camera position, Z pointing forward
78
+ "voxel_grid": {
79
+ # Semantic labels: uint8 (0=empty, 1-21=semantic classes, 255=invalid)
80
+ "label": Array3D(dtype="uint8", shape=(192, 128, 128)),
81
+ # Invalid mask: 1=invalid, 0=valid (outside frustum or no data)
82
+ "invalid": Array3D(dtype="bool", shape=(192, 128, 128)),
83
+ # Occlusion mask: 1=occluded from camera, 0=visible
84
+ "occluded": Array3D(dtype="bool", shape=(192, 128, 128)),
85
+ # Surface mask: 1=surface voxel, 0=interior/non-surface
86
+ "surface": Array3D(dtype="bool", shape=(192, 128, 128)),
87
+ },
88
+ # Camera calibration parameters
89
+ "calibration": {
90
+ "K": Array3D(dtype="float32", shape=(3, 3)),
91
+ },
92
+ }
93
+
94
+ if self.config.include_predictions:
95
+ # Predicted depth from fine-tuned Depth Anything v2
96
+ features["predicted_depth"] = Array3D(dtype="float32", shape=(None, None))
97
+
98
+ return datasets.DatasetInfo(
99
+ description=(
100
+ "OccuFly: A 3D Vision Benchmark for Semantic Scene Completion from the Aerial Perspective. "
101
+ "Contains RGB images, 3D semantic voxel grids, and metric depth maps captured from aerial perspectives "
102
+ "at multiple altitudes (30m, 40m, 50m) across urban, industrial, and rural environments with 21 semantic classes."
103
+ ),
104
+ features=Features(features),
105
+ supervised_keys=("image", "voxel_grid"),
106
+ homepage="https://huggingface.co/datasets/BharadhwajSaiMatha/occufly_test",
107
+ citation=(
108
+ "@misc{gross2025occufly,\n"
109
+ " title={{OccuFly}: A 3D Vision Benchmark for Semantic Scene Completion from the Aerial Perspective},\n"
110
+ " author={Markus Gross and Sai B. Matha and Aya Fahmy and Rui Song and Daniel Cremers and Henri Meess},\n"
111
+ " year={2025},\n"
112
+ " eprint={2512.20770},\n"
113
+ " archivePrefix={Accepted to CVPR 2026. arXiv},\n"
114
+ " primaryClass={cs.CV},\n"
115
+ " url={https://arxiv.org/abs/2512.20770}\n"
116
+ "}"
117
+ ),
118
+ )
119
+
120
+ def _split_generators(self, dl_manager):
121
+ """Download zips and return split generators."""
122
+
123
+ # Scene zip filenames
124
+ scene_zips = {
125
+ scene: f"OccuFly_Dataset/scene_{scene:02d}.zip"
126
+ for scene in self.SCENES
127
+ }
128
+
129
+ # Download scene zips
130
+ downloaded_paths = {}
131
+ logger.info("Downloading scene zips...")
132
+ for scene, filename in scene_zips.items():
133
+ try:
134
+ path = hf_hub_download(
135
+ repo_id="BharadhwajSaiMatha/occufly_test",
136
+ filename=filename,
137
+ repo_type="dataset",
138
+ cache_dir=dl_manager.manual_dir,
139
+ )
140
+ downloaded_paths[scene] = path
141
+ except Exception as e:
142
+ logger.warning(f"Could not download scene {scene}: {e}")
143
+
144
+ # Download predictions if requested
145
+ preds_path = None
146
+ if self.config.include_predictions:
147
+ try:
148
+ logger.info("Downloading depth predictions...")
149
+ preds_path = hf_hub_download(
150
+ repo_id="BharadhwajSaiMatha/occufly_test",
151
+ filename="OccuFly_Predicted_DepthMaps/OccuFly_Predicted_DepthMaps.zip",
152
+ repo_type="dataset",
153
+ cache_dir=dl_manager.manual_dir,
154
+ )
155
+ except Exception as e:
156
+ logger.warning(f"Could not download predictions: {e}")
157
+ preds_path = None
158
+
159
+ return [
160
+ datasets.SplitGenerator(
161
+ name=datasets.Split.TRAIN,
162
+ gen_kwargs={
163
+ "scenes": self.SPLITS["train"],
164
+ "downloaded_paths": downloaded_paths,
165
+ "preds_path": preds_path,
166
+ },
167
+ ),
168
+ datasets.SplitGenerator(
169
+ name=datasets.Split.VALIDATION,
170
+ gen_kwargs={
171
+ "scenes": self.SPLITS["validation"],
172
+ "downloaded_paths": downloaded_paths,
173
+ "preds_path": preds_path,
174
+ },
175
+ ),
176
+ datasets.SplitGenerator(
177
+ name=datasets.Split.TEST,
178
+ gen_kwargs={
179
+ "scenes": self.SPLITS["test"],
180
+ "downloaded_paths": downloaded_paths,
181
+ "preds_path": preds_path,
182
+ },
183
+ ),
184
+ ]
185
+
186
+ def _generate_examples(self, scenes, downloaded_paths, preds_path):
187
+ """Generate examples by extracting and iterating through frames."""
188
+
189
+ # Extract predictions if available
190
+ preds_extract_dir = None
191
+ if preds_path and self.config.include_predictions:
192
+ preds_extract_dir = tempfile.mkdtemp()
193
+ with zipfile.ZipFile(preds_path, 'r') as z:
194
+ z.extractall(preds_extract_dir)
195
+
196
+ example_id = 0
197
+
198
+ for scene_num in scenes:
199
+ if scene_num not in downloaded_paths:
200
+ logger.warning(f"Skipping scene {scene_num}: not downloaded")
201
+ continue
202
+
203
+ zip_path = downloaded_paths[scene_num]
204
+ scene_name = f"scene_{scene_num:02d}"
205
+
206
+ # Extract scene zip to temp directory
207
+ with tempfile.TemporaryDirectory() as extract_dir:
208
+ with zipfile.ZipFile(zip_path, 'r') as z:
209
+ z.extractall(extract_dir)
210
+
211
+ extract_path = Path(extract_dir) / scene_name
212
+
213
+ # Iterate through altitudes
214
+ for altitude in sorted(self.ALTITUDES):
215
+ alt_dir = extract_path / str(altitude)
216
+
217
+ if not alt_dir.exists():
218
+ logger.warning(f"Altitude {altitude} not found in scene {scene_num}")
219
+ continue
220
+
221
+ images_dir = alt_dir / "images" / "visual"
222
+ depth_dir = alt_dir / "depth_maps"
223
+ gt_dir = alt_dir / "ground_truth"
224
+
225
+ # Iterate through frames
226
+ if images_dir.exists():
227
+ for img_file in sorted(images_dir.glob("*.png")):
228
+ try:
229
+ frame_id = int(img_file.stem)
230
+ except ValueError:
231
+ logger.warning(f"Cannot parse frame ID from {img_file.name}")
232
+ continue
233
+ frame_str = f"{frame_id:06d}"
234
+
235
+ try:
236
+ # Load image
237
+ image = PILImage.open(img_file)
238
+
239
+ # Load depth map
240
+ depth_path = depth_dir / f"{frame_str}.npy"
241
+ if not depth_path.exists():
242
+ logger.warning(f"Missing depth for frame {frame_str}")
243
+ continue
244
+ depth_map = np.load(depth_path).astype(np.float32)
245
+
246
+ # Load voxel grid ground truth
247
+ gt_frame_dir = gt_dir / frame_str
248
+ label_path = gt_frame_dir / f"{frame_str}.label"
249
+ if not label_path.exists():
250
+ logger.warning(f"Missing label for {frame_str}")
251
+ continue
252
+ label = np.load(label_path)
253
+ label = label.reshape(192, 128, 128) # Reshape from flattened
254
+
255
+ # Load bitpacked boolean arrays and unpack
256
+ invalid = self._unpack_bitpacked(gt_frame_dir / f"{frame_str}.invalid", (192, 128, 128))
257
+ occluded = self._unpack_bitpacked(gt_frame_dir / f"{frame_str}.occluded", (192, 128, 128))
258
+ surface = self._unpack_bitpacked(gt_frame_dir / f"{frame_str}.surface", (192, 128, 128))
259
+
260
+ voxel_grid = {
261
+ "label": label,
262
+ "invalid": invalid,
263
+ "occluded": occluded,
264
+ "surface": surface,
265
+ }
266
+
267
+ # Load calibration
268
+ calib_path = extract_path / "calibration.txt"
269
+ calibration = self._load_calibration(calib_path)
270
+
271
+ example = {
272
+ "scene": scene_num,
273
+ "altitude": altitude,
274
+ "frame_id": frame_id,
275
+ "image": image,
276
+ "depth_map": depth_map,
277
+ "voxel_grid": voxel_grid,
278
+ "calibration": calibration,
279
+ }
280
+
281
+ # Add predictions if available
282
+ if self.config.include_predictions and preds_extract_dir:
283
+ pred_path = (
284
+ Path(preds_extract_dir) / "OccuFly_Predicted_DepthMaps" /
285
+ scene_name / str(altitude) / "depth_maps" / f"{frame_str}.npy"
286
+ )
287
+ if pred_path.exists():
288
+ pred_depth = np.load(pred_path).astype(np.float32)
289
+ example["predicted_depth"] = pred_depth
290
+
291
+ yield example_id, example
292
+ example_id += 1
293
+
294
+ except Exception as e:
295
+ logger.warning(f"Error processing frame {frame_str}: {e}")
296
+ continue
297
+
298
+ @staticmethod
299
+ def _unpack_bitpacked(bitfile_path, shape):
300
+ """Unpack bitpacked boolean array to proper shape."""
301
+ with open(bitfile_path, 'rb') as f:
302
+ bitpacked = np.frombuffer(f.read(), dtype=np.uint8)
303
+
304
+ # Unpack bits to boolean array
305
+ unpacked = np.unpackbits(bitpacked, bitorder='big')
306
+
307
+ # Resize to exact size needed
308
+ total_elements = np.prod(shape)
309
+ unpacked = unpacked[:total_elements]
310
+
311
+ # Reshape and convert to bool
312
+ return unpacked.reshape(shape).astype(bool)
313
+
314
+ @staticmethod
315
+ def _load_calibration(calib_path):
316
+ """Load camera calibration file."""
317
+ calib = {
318
+ "K": np.eye(3, dtype=np.float32),
319
+ }
320
+
321
+ if calib_path.exists():
322
+ with open(calib_path) as f:
323
+ for line in f:
324
+ parts = line.strip().split()
325
+ if not parts:
326
+ continue
327
+
328
+ key = parts[0].rstrip(':')
329
+ vals = [float(v) for v in parts[1:]]
330
+
331
+ if key == "K" and len(vals) == 9:
332
+ calib["K"] = np.array(vals, dtype=np.float32).reshape(3, 3)
333
+
334
+ return calib