Meehai commited on
Commit
85a37ac
2 Parent(s): e381a70 5e6866e

Merge branch 'main' of hf.co:datasets/Meehai/dronescapes

Browse files
dronescapes_reader/__init__.py CHANGED
@@ -1,22 +1,2 @@
1
  """init file"""
2
  from .multitask_dataset import MultiTaskDataset, NpzRepresentation
3
- from .dronescapes_representations import DepthRepresentation, OpticalFlowRepresentation, SemanticRepresentation, \
4
- ColorRepresentation, EdgesRepresentation, NormalsRepresentation, HSVRepresentation
5
-
6
- _color_map = [[0, 255, 0], [0, 127, 0], [255, 255, 0], [255, 255, 255],
7
- [255, 0, 0], [0, 0, 255], [0, 255, 255], [127, 127, 63]]
8
- _m2f_name = "semantic_mask2former_swin_mapillary_converted"
9
- dronescapes_task_types = { # some pre-baked representations
10
- "rgb": ColorRepresentation("rgb", 3),
11
- "hsv": HSVRepresentation("hsv", 3),
12
- "edges_dexined": ColorRepresentation("edges_dexined", 1),
13
- "depth_dpt": DepthRepresentation("depth_dpt", min_depth=0, max_depth=0.999),
14
- "depth_sfm_manual202204": DepthRepresentation("depth_sfm_manual202204", min_depth=0, max_depth=300),
15
- "normals_sfm_manual202204": NormalsRepresentation("normals_sfm_manual202204"),
16
- "depth_ufo": DepthRepresentation("depth_ufo", min_depth=0, max_depth=1),
17
- "opticalflow_rife": OpticalFlowRepresentation,
18
- "semantic_segprop8": SemanticRepresentation("semantic_segprop8", classes=8, color_map=_color_map),
19
- _m2f_name: SemanticRepresentation(_m2f_name, classes=8, color_map=_color_map),
20
- "softseg_gb": ColorRepresentation("softseg_gb", 3),
21
- "edges_gb": EdgesRepresentation("edges_gb"),
22
- }
 
1
  """init file"""
2
  from .multitask_dataset import MultiTaskDataset, NpzRepresentation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dronescapes_reader/dronescapes_representations.py CHANGED
@@ -7,9 +7,13 @@ import flow_vis
7
  from skimage.color import rgb2hsv, hsv2rgb
8
  from overrides import overrides
9
  from matplotlib.cm import hot # pylint: disable=no-name-in-module
10
- from .multitask_dataset import NpzRepresentation
11
  from torch.nn import functional as F
12
 
 
 
 
 
 
13
  class ColorRepresentation(NpzRepresentation):
14
  def __init__(self, name: str, n_channels: int):
15
  super().__init__(name)
@@ -134,3 +138,21 @@ class SemanticRepresentation(NpzRepresentation):
134
  @overrides
135
  def n_channels(self) -> int:
136
  return self.n_classes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  from skimage.color import rgb2hsv, hsv2rgb
8
  from overrides import overrides
9
  from matplotlib.cm import hot # pylint: disable=no-name-in-module
 
10
  from torch.nn import functional as F
11
 
12
+ try:
13
+ from npz_representation import NpzRepresentation
14
+ except ImportError:
15
+ from .npz_representation import NpzRepresentation
16
+
17
  class ColorRepresentation(NpzRepresentation):
18
  def __init__(self, name: str, n_channels: int):
19
  super().__init__(name)
 
138
  @overrides
139
  def n_channels(self) -> int:
140
  return self.n_classes
141
+
142
+ _color_map = [[0, 255, 0], [0, 127, 0], [255, 255, 0], [255, 255, 255],
143
+ [255, 0, 0], [0, 0, 255], [0, 255, 255], [127, 127, 63]]
144
+ _m2f_name = "semantic_mask2former_swin_mapillary_converted"
145
+ dronescapes_task_types = { # some pre-baked representations
146
+ "rgb": ColorRepresentation("rgb", 3),
147
+ "hsv": HSVRepresentation("hsv", 3),
148
+ "edges_dexined": ColorRepresentation("edges_dexined", 1),
149
+ "depth_dpt": DepthRepresentation("depth_dpt", min_depth=0, max_depth=0.999),
150
+ "depth_sfm_manual202204": DepthRepresentation("depth_sfm_manual202204", min_depth=0, max_depth=300),
151
+ "normals_sfm_manual202204": NormalsRepresentation("normals_sfm_manual202204"),
152
+ "depth_ufo": DepthRepresentation("depth_ufo", min_depth=0, max_depth=1),
153
+ "opticalflow_rife": OpticalFlowRepresentation,
154
+ "semantic_segprop8": SemanticRepresentation("semantic_segprop8", classes=8, color_map=_color_map),
155
+ _m2f_name: SemanticRepresentation(_m2f_name, classes=8, color_map=_color_map),
156
+ "softseg_gb": ColorRepresentation("softseg_gb", 3),
157
+ "edges_gb": EdgesRepresentation("edges_gb"),
158
+ }
dronescapes_reader/multitask_dataset.py CHANGED
@@ -1,6 +1,7 @@
1
  #!/usr/bin/env python3
2
  """MultiTask Dataset module compatible with torch.utils.data.Dataset & DataLoader."""
3
  from __future__ import annotations
 
4
  from pathlib import Path
5
  from typing import Dict, List, Tuple
6
  from argparse import ArgumentParser
@@ -12,52 +13,15 @@ import numpy as np
12
  from torch.utils.data import Dataset, DataLoader
13
  from lovely_tensors import monkey_patch
14
 
 
 
 
 
 
15
  monkey_patch()
16
  BuildDatasetTuple = Tuple[Dict[str, List[Path]], List[str]]
17
  MultiTaskItem = Tuple[Dict[str, tr.Tensor], str, List[str]] # [{task: data}, stem(name) | list[stem(name)], [tasks]]
18
-
19
-
20
- class NpzRepresentation:
21
- """Generic Task with data read from/saved to npz files. Tries to read data as-is from disk and store it as well"""
22
- def __init__(self, name: str):
23
- self.name = name
24
-
25
- def load_from_disk(self, path: Path) -> tr.Tensor:
26
- """Reads the npz data from the disk and transforms it properly"""
27
- data = np.load(path, allow_pickle=False)
28
- data = data if isinstance(data, np.ndarray) else data["arr_0"] # in case on npz, we need this as well
29
- return tr.from_numpy(data) # can be uint8, float16, float32 etc.
30
-
31
- def save_to_disk(self, data: tr.Tensor, path: Path):
32
- """stores this item to the disk which can then be loaded via `load_from_disk`"""
33
- np.save(path, data.cpu().detach().numpy(), allow_pickle=False)
34
-
35
- def plot_fn(self, x: tr.Tensor) -> np.ndarray:
36
- """very basic implementation of converting this representation to a viewable image. You should overwrite this"""
37
- assert isinstance(x, tr.Tensor), type(x)
38
- if len(x.shape) == 2:
39
- x = x.unsqueeze(-1)
40
- assert len(x.shape) == 3, x.shape # guaranteed to be (H, W, C) at this point
41
- if x.shape[-1] != 3:
42
- x = x[..., 0:1]
43
- if x.shape[-1] == 1:
44
- x = x.repeat(1, 1, 3)
45
- x = x.nan_to_num(0).cpu().detach().numpy() # guaranteed to be (H, W, 3) at this point hopefully
46
- _min, _max = x.min((0, 1), keepdims=True), x.max((0, 1), keepdims=True)
47
- if x.dtype != np.uint8:
48
- x = np.nan_to_num((x - _min) / (_max - _min) * 255, 0).astype(np.uint8)
49
- return x
50
-
51
- @property
52
- def n_channels(self) -> int:
53
- """return the number of channels for this representation. Must be updated by each downstream representation"""
54
- raise NotImplementedError(f"n_channels is not implemented for {self}")
55
-
56
- def __repr__(self):
57
- return str(self)
58
-
59
- def __str__(self):
60
- return f"{str(type(self)).split('.')[-1][0:-2]}({self.name})"
61
 
62
  class MultiTaskDataset(Dataset):
63
  """
@@ -81,7 +45,8 @@ class MultiTaskDataset(Dataset):
81
 
82
  def __init__(self, path: Path, task_names: list[str] | None = None, handle_missing_data: str = "fill_none",
83
  files_suffix: str = "npz", task_types: dict[str, type] | None = None,
84
- files_per_repr_overwrites: dict[str, str] | None = None):
 
85
  assert Path(path).exists(), f"Provided path '{path}' doesn't exist!"
86
  assert handle_missing_data in ("drop", "fill_none", "fill_zero", "fill_nan"), \
87
  f"Invalid handle_missing_data mode: {handle_missing_data}"
@@ -108,6 +73,7 @@ class MultiTaskDataset(Dataset):
108
  self.name_to_task = {task.name: task for task in self.tasks}
109
  logger.info(f"Tasks used in this dataset: {self.task_names}")
110
  self._default_vals: dict[str, tr.Tensor] | None = None
 
111
 
112
  # Public methods and properties
113
 
@@ -223,6 +189,43 @@ class MultiTaskDataset(Dataset):
223
  assert len(files_per_repr) > 0
224
  return files_per_repr, all_files
225
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
  # Python magic methods (pretty printing the reader object, reader[0], len(reader) etc.)
227
 
228
  def __getitem__(self, index: int | slice | list[int] | tuple) -> MultiTaskItem:
 
1
  #!/usr/bin/env python3
2
  """MultiTask Dataset module compatible with torch.utils.data.Dataset & DataLoader."""
3
  from __future__ import annotations
4
+ import os
5
  from pathlib import Path
6
  from typing import Dict, List, Tuple
7
  from argparse import ArgumentParser
 
13
  from torch.utils.data import Dataset, DataLoader
14
  from lovely_tensors import monkey_patch
15
 
16
+ try:
17
+ from npz_representation import NpzRepresentation
18
+ except ImportError:
19
+ from .npz_representation import NpzRepresentation
20
+
21
  monkey_patch()
22
  BuildDatasetTuple = Tuple[Dict[str, List[Path]], List[str]]
23
  MultiTaskItem = Tuple[Dict[str, tr.Tensor], str, List[str]] # [{task: data}, stem(name) | list[stem(name)], [tasks]]
24
+ TaskStatistics = Tuple[tr.Tensor, tr.Tensor, tr.Tensor, tr.Tensor] # (min, max, mean, std)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
  class MultiTaskDataset(Dataset):
27
  """
 
45
 
46
  def __init__(self, path: Path, task_names: list[str] | None = None, handle_missing_data: str = "fill_none",
47
  files_suffix: str = "npz", task_types: dict[str, type] | None = None,
48
+ files_per_repr_overwrites: dict[str, str] | None = None,
49
+ compute_statistics: bool = False):
50
  assert Path(path).exists(), f"Provided path '{path}' doesn't exist!"
51
  assert handle_missing_data in ("drop", "fill_none", "fill_zero", "fill_nan"), \
52
  f"Invalid handle_missing_data mode: {handle_missing_data}"
 
73
  self.name_to_task = {task.name: task for task in self.tasks}
74
  logger.info(f"Tasks used in this dataset: {self.task_names}")
75
  self._default_vals: dict[str, tr.Tensor] | None = None
76
+ self.statistics = None if compute_statistics is False else self._compute_statistics()
77
 
78
  # Public methods and properties
79
 
 
189
  assert len(files_per_repr) > 0
190
  return files_per_repr, all_files
191
 
192
+ def _compute_statistics(self) -> dict[str, tr.Tensor]:
193
+ cache_path = self.path / f".task_statistics.npz"
194
+ res: dict[str, TaskStatistics] = {}
195
+ if os.getenv("CACHE_IMG_STATS", "0") == "1" and cache_path.exists():
196
+ res = np.load(cache_path, allow_pickle=True)["arr_0"].item()
197
+ logger.info(f"Loaded task statistics: { {k: v.shape for k, v in res.items()} }")
198
+ missing_tasks = list(set(self.task_names).difference(res.keys()))
199
+ if len(missing_tasks) == 0:
200
+ return res
201
+ logger.info(f"Computing global task statistics (dataset len {len(self)}) for {missing_tasks}")
202
+ old_tasks = self.tasks
203
+ self._tasks = [t for t in self.tasks if t.name in missing_tasks]
204
+ res = {**res, **self._compute_channel_level_stats(missing_tasks)}
205
+ self._tasks = old_tasks
206
+ logger.info(f"Computed task statistics: { {k: v[0].shape for k, v in res.items()} }")
207
+ if os.getenv("CACHE_IMG_STATS", "0") == "1":
208
+ np.savez(cache_path, res)
209
+ return res
210
+
211
+ def _compute_channel_level_stats(self, missing_tasks: list[str]) -> dict[str, TaskStatistics]:
212
+ ch = {k: v[-1] if len(v) == 3 else 1 for k, v in self.data_shape.items()}
213
+ sums = {task_name: tr.zeros(ch[task_name]).type(tr.float64) for task_name in missing_tasks}
214
+ counts = {task_name: tr.zeros(ch[task_name]).long() for task_name in missing_tasks}
215
+ mins = {task_name: tr.zeros(ch[task_name]).type(tr.float64) - 1<<31 for task_name in missing_tasks}
216
+ maxs = {task_name: tr.zeros(ch[task_name]).type(tr.float64) + 1<<31 for task_name in missing_tasks}
217
+
218
+
219
+ for ix in range(len(self)):
220
+ item = self.base_dataset[ix][0]
221
+ for task in missing_tasks:
222
+ item_flat_ch = item[task].reshape(-1, self.ch[task])
223
+ sums[task] += item_flat_ch.nan_to_num(0).type(tr.float64).sum(0)
224
+ counts[task] += (item_flat_ch == item_flat_ch).long().sum(0)
225
+ res_ch = {k: (sums[k] / counts[k]).nan_to_num(0).float() for k in missing_tasks}
226
+ res = {k: v.reshape(-1, 1, 1).repeat(1, self.h, self.w) for k, v in res_ch.items()}
227
+ return res
228
+
229
  # Python magic methods (pretty printing the reader object, reader[0], len(reader) etc.)
230
 
231
  def __getitem__(self, index: int | slice | list[int] | tuple) -> MultiTaskItem:
dronescapes_reader/npz_representation.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MultiTask representations stored as .npz files on the disk"""
2
+ from __future__ import annotations
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import torch as tr
6
+
7
+ class NpzRepresentation:
8
+ """Generic Task with data read from/saved to npz files. Tries to read data as-is from disk and store it as well"""
9
+ def __init__(self, name: str):
10
+ self.name = name
11
+
12
+ def load_from_disk(self, path: Path) -> tr.Tensor:
13
+ """Reads the npz data from the disk and transforms it properly"""
14
+ data = np.load(path, allow_pickle=False)
15
+ data = data if isinstance(data, np.ndarray) else data["arr_0"] # in case on npz, we need this as well
16
+ return tr.from_numpy(data) # can be uint8, float16, float32 etc.
17
+
18
+ def save_to_disk(self, data: tr.Tensor, path: Path):
19
+ """stores this item to the disk which can then be loaded via `load_from_disk`"""
20
+ np.save(path, data.cpu().detach().numpy(), allow_pickle=False)
21
+
22
+ def plot_fn(self, x: tr.Tensor) -> np.ndarray:
23
+ """very basic implementation of converting this representation to a viewable image. You should overwrite this"""
24
+ assert isinstance(x, tr.Tensor), type(x)
25
+ if len(x.shape) == 2:
26
+ x = x.unsqueeze(-1)
27
+ assert len(x.shape) == 3, x.shape # guaranteed to be (H, W, C) at this point
28
+ if x.shape[-1] != 3:
29
+ x = x[..., 0:1]
30
+ if x.shape[-1] == 1:
31
+ x = x.repeat(1, 1, 3)
32
+ x = x.nan_to_num(0).cpu().detach().numpy() # guaranteed to be (H, W, 3) at this point hopefully
33
+ _min, _max = x.min((0, 1), keepdims=True), x.max((0, 1), keepdims=True)
34
+ if x.dtype != np.uint8:
35
+ x = np.nan_to_num((x - _min) / (_max - _min) * 255, 0).astype(np.uint8)
36
+ return x
37
+
38
+ def normalize(self, x: tr.Tensor, x_min: tr.Tensor, x_max: tr.Tensor) -> tr.Tensor:
39
+ """normalizes a data point read with self.load_from_disk(path) using external min/max information"""
40
+ return ((x - x_max) / (x_max - x_min)).nan_to_num(0, 0, 0)
41
+
42
+ def standardize(self, x: tr.Tensor, x_mean: tr.Tensor, x_std: tr.Tensor) -> tr.Tensor:
43
+ """standardizes a data point read with self.load_from_disk(path) using external min/max information"""
44
+ return ((x - x_mean) / x_std).nan_to_num(0, 0, 0)
45
+
46
+ @property
47
+ def n_channels(self) -> int:
48
+ """return the number of channels for this representation. Must be updated by each downstream representation"""
49
+ raise NotImplementedError(f"n_channels is not implemented for {self}")
50
+
51
+ def __repr__(self):
52
+ return str(self)
53
+
54
+ def __str__(self):
55
+ return f"{str(type(self)).split('.')[-1][0:-2]}({self.name})"
scripts/dronescapes_viewer.ipynb CHANGED
The diff for this file is too large to render. See raw diff
 
scripts/dronescapes_viewer.py CHANGED
@@ -2,7 +2,8 @@
2
  import sys
3
  from pathlib import Path
4
  sys.path.append(Path(__file__).parents[1].__str__())
5
- from dronescapes_reader import MultiTaskDataset, dronescapes_task_types
 
6
  from pprint import pprint
7
  from torch.utils.data import DataLoader
8
  import random
 
2
  import sys
3
  from pathlib import Path
4
  sys.path.append(Path(__file__).parents[1].__str__())
5
+ from dronescapes_reader import MultiTaskDataset
6
+ from dronescapes_reader.dronescapes_representations import dronescapes_task_types
7
  from pprint import pprint
8
  from torch.utils.data import DataLoader
9
  import random