-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdata.py
More file actions
165 lines (132 loc) · 5.48 KB
/
data.py
File metadata and controls
165 lines (132 loc) · 5.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
from abc import ABC, ABCMeta, abstractmethod
from pathlib import Path
from typing import Literal, Optional
from torch.utils.data import Dataset
import matplotlib.pyplot as plt
from skimage.color import label2rgb
class SanityCheckMeta(ABCMeta):
def __call__(cls, *args, **kwargs):
obj = super().__call__(*args, **kwargs)
if hasattr(obj, "_sanity_check"):
obj._sanity_check()
return obj
class MuViTDataset(Dataset, ABC, metaclass=SanityCheckMeta):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@abstractmethod
def __getitem__(self, idx: int):
pass
@abstractmethod
def __len__(self):
pass
@property
@abstractmethod
def ndim(self):
pass
@property
def n_levels(self):
return len(self.levels)
@property
@abstractmethod
def levels(self):
pass
@property
@abstractmethod
def n_channels(self):
pass
def _sanity_check(self):
if self.ndim not in (2, 3, 4):
raise ValueError("ndim must be 2, 3 or 4")
if len(self) == 0:
raise ValueError("Dataset is empty.")
sample = self[0]
if "img" not in sample or "bbox" not in sample:
raise ValueError("Sample must contain 'img' and 'bbox' keys.")
img = sample["img"]
bbox = sample["bbox"]
if bbox is not None:
expected_bbox_shape = (self.n_levels, 2, self.ndim)
if tuple(bbox.shape) != expected_bbox_shape:
raise ValueError(
f"Expected bbox shape {expected_bbox_shape}, got {tuple(bbox.shape)}"
)
expected_img_ndim = {2: 4, 3: 5, 4: 6}[self.ndim]
if img.ndim != expected_img_ndim:
raise ValueError(
f"Expected img.ndim = {expected_img_ndim} for ndim={self.ndim} (L,C"
f"{',D' if self.ndim == 3 else ''},H,W), got {img.ndim}"
)
if img.shape[0] != self.n_levels:
raise ValueError(
f"Expected img.shape[0] (L) = {self.n_levels}, got {img.shape[0]}"
)
if img.shape[1] != self.n_channels:
raise ValueError(
f"Expected img.shape[1] (C) = {self.n_channels}, got {img.shape[1]}"
)
def visualize_sample(self, idx: int = 0, save_file: Optional[Path] = None, view: Literal["yx", "zx", "zy"] = "yx", continuous_label_cmap=None):
if self.ndim not in (2,3):
raise NotImplementedError(
"Sample visualization is implemented for 2d and 3d only."
)
import numpy as np
from .utils import box_annotate
_item = self[idx]
img, bbox = _item["img"].cpu().numpy(), _item["bbox"].cpu().numpy()
if self.ndim == 3 and view not in ("yx", "zy", "zx"):
raise ValueError("view must be one of 'yx', 'zy', 'zx'")
if self.ndim == 3 and view == "yx":
img = img[..., img.shape[-3] // 2, :, :]
bbox = bbox[:, :, 1:]
elif self.ndim == 3 and view == "zx":
img = img[..., img.shape[-2] // 2, :]
bbox = bbox[:, :, [0, 2]]
elif self.ndim == 3 and view == "zy":
img = img[..., img.shape[-1] // 2]
bbox = bbox[:, :, :2]
box_annotate(img, bbox)
img = np.concatenate(
np.pad(img, ((0, 0), (0, 0), (1, 1), (1, 1)), constant_values=1), axis=-2
)
if img.shape[0] == 1:
img = np.repeat(img, 3, axis=0)
elif img.shape[0] == 2:
img = np.stack([img[0], img[1], img[0]], axis=0)
elif img.shape[0] > 3:
img = img[:3]
if "label" in _item and _item["label"] is not None:
label = _item["label"].cpu().numpy()
if self.ndim == 3 and view == "yx":
label = label[..., label.shape[-3] // 2, :, :]
elif self.ndim == 3 and view == "zx":
label = label[..., label.shape[-2] // 2, :]
elif self.ndim == 3 and view == "zy":
label = label[..., label.shape[-1] // 2]
label_cp = np.zeros((label.shape[0], 3, label.shape[1], label.shape[2]))
if continuous_label_cmap is None:
for s in range(label.shape[0]):
label_cp[s] = label2rgb(label[s], channel_axis=0) # CYX
else:
cmap_fun = plt.cm.get_cmap(continuous_label_cmap)
for s in range(label.shape[0]):
label_cp[s] = cmap_fun(label[s])[...,:3].transpose(2,0,1) # C,Y,X
box_annotate(label_cp, bbox)
label_cp = np.concatenate(np.pad(label_cp, ((0, 0), (0, 0), (1, 1), (1, 1)), constant_values=1),axis=-2)
if img.ndim != label_cp.ndim:
img = np.stack([img]*label_cp.shape[0], axis=0)
img = np.concatenate([img, label_cp], axis=-1)
if save_file:
save_file = Path(save_file)
save_file.parent.mkdir(exist_ok=True, parents=True)
fig, ax = plt.subplots(figsize=(10, 10))
if img.ndim > 2:
ax.imshow(img.transpose(1,2,0))
else:
ax.imshow(img, cmap="gray")
ax.axis("off")
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.spines["bottom"].set_visible(False)
fig.savefig(save_file, bbox_inches="tight")
plt.close(fig)