Meehai commited on
Commit
5e6866e
1 Parent(s): f755e76

small changes to dronescapes_reader. Added initial support for norm/std

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,10 @@ 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 +135,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
+ from npz_representation import NpzRepresentation
13
+
14
  class ColorRepresentation(NpzRepresentation):
15
  def __init__(self, name: str, n_channels: int):
16
  super().__init__(name)
 
135
  @overrides
136
  def n_channels(self) -> int:
137
  return self.n_classes
138
+
139
+ _color_map = [[0, 255, 0], [0, 127, 0], [255, 255, 0], [255, 255, 255],
140
+ [255, 0, 0], [0, 0, 255], [0, 255, 255], [127, 127, 63]]
141
+ _m2f_name = "semantic_mask2former_swin_mapillary_converted"
142
+ dronescapes_task_types = { # some pre-baked representations
143
+ "rgb": ColorRepresentation("rgb", 3),
144
+ "hsv": HSVRepresentation("hsv", 3),
145
+ "edges_dexined": ColorRepresentation("edges_dexined", 1),
146
+ "depth_dpt": DepthRepresentation("depth_dpt", min_depth=0, max_depth=0.999),
147
+ "depth_sfm_manual202204": DepthRepresentation("depth_sfm_manual202204", min_depth=0, max_depth=300),
148
+ "normals_sfm_manual202204": NormalsRepresentation("normals_sfm_manual202204"),
149
+ "depth_ufo": DepthRepresentation("depth_ufo", min_depth=0, max_depth=1),
150
+ "opticalflow_rife": OpticalFlowRepresentation,
151
+ "semantic_segprop8": SemanticRepresentation("semantic_segprop8", classes=8, color_map=_color_map),
152
+ _m2f_name: SemanticRepresentation(_m2f_name, classes=8, color_map=_color_map),
153
+ "softseg_gb": ColorRepresentation("softseg_gb", 3),
154
+ "edges_gb": EdgesRepresentation("edges_gb"),
155
+ }
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,12 @@ 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 +42,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 +70,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 +186,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
+ from npz_representation import NpzRepresentation
17
+
18
  monkey_patch()
19
  BuildDatasetTuple = Tuple[Dict[str, List[Path]], List[str]]
20
  MultiTaskItem = Tuple[Dict[str, tr.Tensor], str, List[str]] # [{task: data}, stem(name) | list[stem(name)], [tasks]]
21
+ TaskStatistics = Tuple[tr.Tensor, tr.Tensor, tr.Tensor, tr.Tensor] # (min, max, mean, std)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  class MultiTaskDataset(Dataset):
24
  """
 
42
 
43
  def __init__(self, path: Path, task_names: list[str] | None = None, handle_missing_data: str = "fill_none",
44
  files_suffix: str = "npz", task_types: dict[str, type] | None = None,
45
+ files_per_repr_overwrites: dict[str, str] | None = None,
46
+ compute_statistics: bool = False):
47
  assert Path(path).exists(), f"Provided path '{path}' doesn't exist!"
48
  assert handle_missing_data in ("drop", "fill_none", "fill_zero", "fill_nan"), \
49
  f"Invalid handle_missing_data mode: {handle_missing_data}"
 
70
  self.name_to_task = {task.name: task for task in self.tasks}
71
  logger.info(f"Tasks used in this dataset: {self.task_names}")
72
  self._default_vals: dict[str, tr.Tensor] | None = None
73
+ self.statistics = None if compute_statistics is False else self._compute_statistics()
74
 
75
  # Public methods and properties
76
 
 
186
  assert len(files_per_repr) > 0
187
  return files_per_repr, all_files
188
 
189
+ def _compute_statistics(self) -> dict[str, tr.Tensor]:
190
+ cache_path = self.path / f".task_statistics.npz"
191
+ res: dict[str, TaskStatistics] = {}
192
+ if os.getenv("CACHE_IMG_STATS", "0") == "1" and cache_path.exists():
193
+ res = np.load(cache_path, allow_pickle=True)["arr_0"].item()
194
+ logger.info(f"Loaded task statistics: { {k: v.shape for k, v in res.items()} }")
195
+ missing_tasks = list(set(self.task_names).difference(res.keys()))
196
+ if len(missing_tasks) == 0:
197
+ return res
198
+ logger.info(f"Computing global task statistics (dataset len {len(self)}) for {missing_tasks}")
199
+ old_tasks = self.tasks
200
+ self._tasks = [t for t in self.tasks if t.name in missing_tasks]
201
+ res = {**res, **self._compute_channel_level_stats(missing_tasks)}
202
+ self._tasks = old_tasks
203
+ logger.info(f"Computed task statistics: { {k: v[0].shape for k, v in res.items()} }")
204
+ if os.getenv("CACHE_IMG_STATS", "0") == "1":
205
+ np.savez(cache_path, res)
206
+ return res
207
+
208
+ def _compute_channel_level_stats(self, missing_tasks: list[str]) -> dict[str, TaskStatistics]:
209
+ ch = {k: v[-1] if len(v) == 3 else 1 for k, v in self.data_shape.items()}
210
+ sums = {task_name: tr.zeros(ch[task_name]).type(tr.float64) for task_name in missing_tasks}
211
+ counts = {task_name: tr.zeros(ch[task_name]).long() for task_name in missing_tasks}
212
+ mins = {task_name: tr.zeros(ch[task_name]).type(tr.float64) - 1<<31 for task_name in missing_tasks}
213
+ maxs = {task_name: tr.zeros(ch[task_name]).type(tr.float64) + 1<<31 for task_name in missing_tasks}
214
+
215
+
216
+ for ix in range(len(self)):
217
+ item = self.base_dataset[ix][0]
218
+ for task in missing_tasks:
219
+ item_flat_ch = item[task].reshape(-1, self.ch[task])
220
+ sums[task] += item_flat_ch.nan_to_num(0).type(tr.float64).sum(0)
221
+ counts[task] += (item_flat_ch == item_flat_ch).long().sum(0)
222
+ res_ch = {k: (sums[k] / counts[k]).nan_to_num(0).float() for k in missing_tasks}
223
+ res = {k: v.reshape(-1, 1, 1).repeat(1, self.h, self.w) for k, v in res_ch.items()}
224
+ return res
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:
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
@@ -4,14 +4,28 @@
4
  "cell_type": "code",
5
  "execution_count": 1,
6
  "metadata": {},
7
- "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  "source": [
9
  "import sys\n",
 
10
  "from pathlib import Path\n",
11
  "from pprint import pprint\n",
12
  "import random\n",
13
- "sys.path.append(Path.cwd().parent.__str__())\n",
14
- "from dronescapes_reader import MultiTaskDataset, dronescapes_task_types\n",
15
  "import numpy as np\n",
16
  "from media_processing_lib.collage_maker import collage_fn\n",
17
  "from media_processing_lib.image import image_add_title, image_write\n",
@@ -140,7 +154,7 @@
140
  "name": "python",
141
  "nbconvert_exporter": "python",
142
  "pygments_lexer": "ipython3",
143
- "version": "3.12.3"
144
  }
145
  },
146
  "nbformat": 4,
 
4
  "cell_type": "code",
5
  "execution_count": 1,
6
  "metadata": {},
7
+ "outputs": [
8
+ {
9
+ "ename": "ModuleNotFoundError",
10
+ "evalue": "No module named 'npz_representation'",
11
+ "output_type": "error",
12
+ "traceback": [
13
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
14
+ "\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)",
15
+ "Cell \u001b[0;32mIn[1], line 7\u001b[0m\n\u001b[1;32m 5\u001b[0m sys\u001b[38;5;241m.\u001b[39mpath\u001b[38;5;241m.\u001b[39mappend(Path\u001b[38;5;241m.\u001b[39mcwd()\u001b[38;5;241m.\u001b[39mparent\u001b[38;5;241m.\u001b[39m\u001b[38;5;21m__str__\u001b[39m())\n\u001b[1;32m 6\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mdronescapes_reader\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m MultiTaskDataset\n\u001b[0;32m----> 7\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mdronescapes_reader\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mdronescapes_representations\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m dronescapes_task_types\n\u001b[1;32m 8\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mnumpy\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m \u001b[38;5;21;01mnp\u001b[39;00m\n\u001b[1;32m 9\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mmedia_processing_lib\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mcollage_maker\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m collage_fn\n",
16
+ "File \u001b[0;32m~/data/dronescapes/dronescapes_reader/dronescapes_representations.py:12\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mmatplotlib\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mcm\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m hot \u001b[38;5;66;03m# pylint: disable=no-name-in-module\u001b[39;00m\n\u001b[1;32m 10\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mtorch\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mnn\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m functional \u001b[38;5;28;01mas\u001b[39;00m F\n\u001b[0;32m---> 12\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mnpz_representation\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m NpzRepresentation\n\u001b[1;32m 14\u001b[0m \u001b[38;5;28;01mclass\u001b[39;00m \u001b[38;5;21;01mColorRepresentation\u001b[39;00m(NpzRepresentation):\n\u001b[1;32m 15\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21m__init__\u001b[39m(\u001b[38;5;28mself\u001b[39m, name: \u001b[38;5;28mstr\u001b[39m, n_channels: \u001b[38;5;28mint\u001b[39m):\n",
17
+ "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'npz_representation'"
18
+ ]
19
+ }
20
+ ],
21
  "source": [
22
  "import sys\n",
23
+ "sys.path.append(Path.cwd().parent.__str__())\n",
24
  "from pathlib import Path\n",
25
  "from pprint import pprint\n",
26
  "import random\n",
27
+ "from dronescapes_reader import MultiTaskDataset\n",
28
+ "from dronescapes_reader.dronescapes_representations import dronescapes_task_types\n",
29
  "import numpy as np\n",
30
  "from media_processing_lib.collage_maker import collage_fn\n",
31
  "from media_processing_lib.image import image_add_title, image_write\n",
 
154
  "name": "python",
155
  "nbconvert_exporter": "python",
156
  "pygments_lexer": "ipython3",
157
+ "version": "3.11.9"
158
  }
159
  },
160
  "nbformat": 4,
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