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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import cv2
|
| 3 |
+
from typing import TypeVar, Optional
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import albumentations as A
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import seaborn as sns
|
| 8 |
+
|
| 9 |
+
T = TypeVar("T", bound=np.number)
|
| 10 |
+
SampleArg = tuple[T, T] | T
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
CATEGORIES: dict[str, int] = {
|
| 14 |
+
"SA": 1,
|
| 15 |
+
"LI": 2,
|
| 16 |
+
"RI": 3,
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
LABELS: dict[int, str] = {v: k for k, v in CATEGORIES.items()}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def sample(x: SampleArg) -> T:
|
| 23 |
+
return np.random.uniform(x[0], x[1]) if isinstance(x, tuple) else x
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Dropout(A.PixelDropout):
|
| 27 |
+
def apply_to_bbox(self, bbox, **params):
|
| 28 |
+
return bbox
|
| 29 |
+
|
| 30 |
+
def apply_to_keypoint(self, keypoint, **params):
|
| 31 |
+
return keypoint
|
| 32 |
+
|
| 33 |
+
def apply_to_mask(self, img: np.ndarray, **params) -> np.ndarray:
|
| 34 |
+
return img
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class CoarseDropout(A.CoarseDropout):
|
| 38 |
+
def apply_to_bbox(self, bbox, **params):
|
| 39 |
+
return bbox
|
| 40 |
+
|
| 41 |
+
def apply_to_keypoint(self, keypoint, **params):
|
| 42 |
+
return keypoint
|
| 43 |
+
|
| 44 |
+
def apply_to_mask(self, img: np.ndarray, **params) -> np.ndarray:
|
| 45 |
+
return img
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def gaussian_contrast_fn(
|
| 49 |
+
images: np.ndarray,
|
| 50 |
+
alpha: float | tuple[float, float] = (0.6, 1.4),
|
| 51 |
+
sigma: float | tuple[float, float] = (0.1, 0.5),
|
| 52 |
+
max_value: float = 1,
|
| 53 |
+
):
|
| 54 |
+
original_type = images.dtype
|
| 55 |
+
images = images.astype(np.float32) / max_value
|
| 56 |
+
|
| 57 |
+
N, H, W, C = images.shape
|
| 58 |
+
if isinstance(alpha, tuple):
|
| 59 |
+
alpha = np.random.uniform(alpha[0], alpha[1])
|
| 60 |
+
if isinstance(sigma, tuple):
|
| 61 |
+
s = np.random.uniform(sigma[0], sigma[1]) * min(H, W)
|
| 62 |
+
else:
|
| 63 |
+
s = sigma * min(H, W)
|
| 64 |
+
|
| 65 |
+
mu_x = np.random.uniform(0, H, size=N)
|
| 66 |
+
mu_y = np.random.uniform(0, W, size=N)
|
| 67 |
+
xs, ys = np.meshgrid(
|
| 68 |
+
np.arange(H, dtype=np.float32), np.arange(W, dtype=np.float32), indexing="ij"
|
| 69 |
+
)
|
| 70 |
+
xdiff = xs[:, :, None] - mu_x[None, None, :]
|
| 71 |
+
ydiff = ys[:, :, None] - mu_y[None, None, :]
|
| 72 |
+
distance_squared = xdiff**2 + ydiff**2
|
| 73 |
+
h = np.exp(-distance_squared / (2 * s * s))
|
| 74 |
+
hmax = np.max(h, axis=(0, 1), keepdims=True)
|
| 75 |
+
hmap = h / hmax # in [0, 1]
|
| 76 |
+
alpha_map = hmap * (alpha - 1) + 1
|
| 77 |
+
images = 0.5 + (images - 0.5) * alpha_map
|
| 78 |
+
images = np.clip(images, 0, 1)
|
| 79 |
+
images = (images * max_value).astype(original_type)
|
| 80 |
+
return images
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def gaussian_contrast_aug(
|
| 84 |
+
alpha: float | tuple[float, float] = (0.6, 1.4),
|
| 85 |
+
sigma: float | tuple[float, float] = (0.1, 0.5),
|
| 86 |
+
max_value: float = 1,
|
| 87 |
+
) -> A.Lambda:
|
| 88 |
+
"""Nonuniform contrast augmentation.
|
| 89 |
+
|
| 90 |
+
Adjust the contrast by scaling each pixel with value `v` at `x` to
|
| 91 |
+
`0.5 + (v - 0.5) * exp(-(x - mu)**2 / (2 * sigma**2)))`
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
alpha (float or tuple of float): Alpha of the nonuniform contrast
|
| 95 |
+
augmentation. If a tuple is provided, the value will be randomly
|
| 96 |
+
selected from the range.
|
| 97 |
+
sigma (float or tuple of float): Standard deviation of the Gaussian
|
| 98 |
+
kernel, as a fraction of the (smaller) image size. If a tuple is provided, the value
|
| 99 |
+
will be randomly selected from the range.
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
imgaug.augmenters.Lambda: The augmenter.
|
| 103 |
+
"""
|
| 104 |
+
if isinstance(alpha, tuple):
|
| 105 |
+
assert len(alpha) == 2
|
| 106 |
+
assert alpha[0] <= alpha[1]
|
| 107 |
+
|
| 108 |
+
if isinstance(sigma, tuple):
|
| 109 |
+
assert len(sigma) == 2
|
| 110 |
+
assert sigma[0] <= sigma[1]
|
| 111 |
+
sigma = np.random.uniform(sigma[0], sigma[1])
|
| 112 |
+
|
| 113 |
+
def f_image(image, **kwargs):
|
| 114 |
+
# Images are in NHWC
|
| 115 |
+
return gaussian_contrast_fn(np.array([image]), alpha, sigma, max_value=max_value)[0]
|
| 116 |
+
|
| 117 |
+
def f_id(x, **kwargs):
|
| 118 |
+
return x
|
| 119 |
+
|
| 120 |
+
return A.Lambda(
|
| 121 |
+
image=f_image,
|
| 122 |
+
mask=f_id,
|
| 123 |
+
keypoint=f_id,
|
| 124 |
+
bbox=f_id,
|
| 125 |
+
name="gaussian_contrast",
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def neglog_fn(images: np.ndarray, epsilon: float = 0.001) -> np.ndarray:
|
| 130 |
+
"""Take the negative log transform of an intensity image.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
image (np.ndarray): [N,H,W,C] array of intensity images.
|
| 134 |
+
epsilon (float, optional): positive offset from 0 before taking the logarithm.
|
| 135 |
+
|
| 136 |
+
Returns:
|
| 137 |
+
np.ndarray: the image or images after a negative log transform.
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
# shift image to avoid invalid values
|
| 141 |
+
images += images.min(axis=(1, 2), keepdims=True) + epsilon
|
| 142 |
+
|
| 143 |
+
# negative log transform
|
| 144 |
+
images = -np.log(images)
|
| 145 |
+
|
| 146 |
+
return images
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def neglog_aug(epsilon: float = 0.001) -> A.Lambda:
|
| 150 |
+
"""Take the negative log transform of an intensity image.
|
| 151 |
+
|
| 152 |
+
Args:
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
def f_image(images: np.ndarray, **kwargs) -> np.ndarray:
|
| 156 |
+
return neglog_fn(images, epsilon)
|
| 157 |
+
|
| 158 |
+
def f_id(x, **kwargs):
|
| 159 |
+
return x
|
| 160 |
+
|
| 161 |
+
return A.Lambda(
|
| 162 |
+
image=f_image,
|
| 163 |
+
mask=f_id,
|
| 164 |
+
keypoint=f_id,
|
| 165 |
+
bbox=f_id,
|
| 166 |
+
name="neglog",
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def window_(
|
| 171 |
+
images: np.ndarray,
|
| 172 |
+
lower: SampleArg = 0.01,
|
| 173 |
+
upper: SampleArg = 0.99,
|
| 174 |
+
convert: bool = True,
|
| 175 |
+
) -> np.ndarray:
|
| 176 |
+
"""Apply a random window to an intensity image.
|
| 177 |
+
|
| 178 |
+
Args:
|
| 179 |
+
images (np.ndarray): [H,W,C] image
|
| 180 |
+
upper (float, optional): The upper quantile of the window. Defaults to 0.99.
|
| 181 |
+
lower (float, optional): The lower quantile of the window. Defaults to 0.01.
|
| 182 |
+
|
| 183 |
+
Returns:
|
| 184 |
+
np.ndarray: the image or images after having a random window applied.
|
| 185 |
+
"""
|
| 186 |
+
eps = 1e-7
|
| 187 |
+
upper = sample(upper)
|
| 188 |
+
upper = np.quantile(images, upper)
|
| 189 |
+
|
| 190 |
+
lower = sample(lower)
|
| 191 |
+
lower = np.quantile(images, lower)
|
| 192 |
+
|
| 193 |
+
if upper == lower:
|
| 194 |
+
upper = images.max()
|
| 195 |
+
lower = images.min()
|
| 196 |
+
|
| 197 |
+
images = images - lower
|
| 198 |
+
images = images / (upper - lower + eps)
|
| 199 |
+
images = np.clip(images, 0, 1)
|
| 200 |
+
|
| 201 |
+
if convert:
|
| 202 |
+
images = (images * 255).astype(np.uint8)
|
| 203 |
+
return images
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def window(
|
| 207 |
+
lower: SampleArg = 0.01,
|
| 208 |
+
upper: SampleArg = 0.99,
|
| 209 |
+
convert: bool = True,
|
| 210 |
+
):
|
| 211 |
+
"""Apply a random window to intensity images.
|
| 212 |
+
|
| 213 |
+
Args:
|
| 214 |
+
upper (float, optional): The upper quantile of the window. Defaults to 0.99.
|
| 215 |
+
lower (float, optional): The lower quantile of the window. Defaults to 0.01.
|
| 216 |
+
|
| 217 |
+
Returns:
|
| 218 |
+
np.ndarray: the image or images after having a random window applied.
|
| 219 |
+
"""
|
| 220 |
+
|
| 221 |
+
def _window(images: np.ndarray, **kwargs) -> np.ndarray:
|
| 222 |
+
return window_(images, upper, lower, convert=convert)
|
| 223 |
+
|
| 224 |
+
def f_id(x, **kwargs):
|
| 225 |
+
return x
|
| 226 |
+
|
| 227 |
+
return A.Lambda(
|
| 228 |
+
image=_window,
|
| 229 |
+
mask=f_id,
|
| 230 |
+
keypoint=f_id,
|
| 231 |
+
bbox=f_id,
|
| 232 |
+
name="window",
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def build_augmentation(train: bool = True, img_size: int = 448) -> A.SomeOf:
|
| 237 |
+
"""Build an augmentation pipeline.
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
train: Whether to build an augmentation for training or testing. If True, the wrapped
|
| 241 |
+
function is used to get the training augmentations.
|
| 242 |
+
|
| 243 |
+
annotations: Whether the dataset contains annotations.
|
| 244 |
+
image_size: The size to resize images to. If None, no resizing is done.
|
| 245 |
+
normalize: Whether to normalize the image to [-1, 1].
|
| 246 |
+
|
| 247 |
+
"""
|
| 248 |
+
if not train:
|
| 249 |
+
return A.Compose(
|
| 250 |
+
[neglog_aug(), window(0.01, 0.95, convert=False), A.Resize(img_size, img_size)]
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
return A.Compose(
|
| 254 |
+
[
|
| 255 |
+
neglog_aug(),
|
| 256 |
+
window((0, 0.05), (0.95, 1.0), convert=True),
|
| 257 |
+
A.Resize(img_size, img_size),
|
| 258 |
+
A.CLAHE(clip_limit=(1, 4), p=0.5),
|
| 259 |
+
A.InvertImg(p=0.5),
|
| 260 |
+
A.SomeOf(
|
| 261 |
+
[
|
| 262 |
+
A.OneOf(
|
| 263 |
+
[
|
| 264 |
+
A.GaussianBlur((3, 5)),
|
| 265 |
+
A.MotionBlur(blur_limit=(3, 5)),
|
| 266 |
+
A.MedianBlur(blur_limit=5),
|
| 267 |
+
],
|
| 268 |
+
),
|
| 269 |
+
A.OneOf(
|
| 270 |
+
[
|
| 271 |
+
A.Sharpen(alpha=(0.2, 0.5)),
|
| 272 |
+
A.Emboss(alpha=(0.2, 0.5)),
|
| 273 |
+
],
|
| 274 |
+
),
|
| 275 |
+
A.OneOf(
|
| 276 |
+
[
|
| 277 |
+
A.MultiplicativeNoise(multiplier=(0.9, 1.1)),
|
| 278 |
+
A.HueSaturationValue(
|
| 279 |
+
hue_shift_limit=20,
|
| 280 |
+
sat_shift_limit=30,
|
| 281 |
+
val_shift_limit=20,
|
| 282 |
+
),
|
| 283 |
+
A.RandomBrightnessContrast(
|
| 284 |
+
brightness_limit=(-0.4, 0.2), contrast_limit=(-0.4, 0.2)
|
| 285 |
+
),
|
| 286 |
+
gaussian_contrast_aug(
|
| 287 |
+
alpha=(0.6, 1.4), sigma=(0.1, 0.5), max_value=255
|
| 288 |
+
),
|
| 289 |
+
],
|
| 290 |
+
),
|
| 291 |
+
A.RandomToneCurve(scale=0.1),
|
| 292 |
+
A.OneOf(
|
| 293 |
+
[
|
| 294 |
+
A.RandomShadow(),
|
| 295 |
+
A.RandomFog(fog_coef_lower=0.1, fog_coef_upper=0.3, alpha_coef=0.08),
|
| 296 |
+
],
|
| 297 |
+
),
|
| 298 |
+
A.OneOf(
|
| 299 |
+
[
|
| 300 |
+
Dropout(dropout_prob=0.05),
|
| 301 |
+
CoarseDropout(
|
| 302 |
+
max_holes=12,
|
| 303 |
+
max_height=24,
|
| 304 |
+
max_width=24,
|
| 305 |
+
min_holes=4,
|
| 306 |
+
min_height=4,
|
| 307 |
+
min_width=4,
|
| 308 |
+
),
|
| 309 |
+
],
|
| 310 |
+
p=3,
|
| 311 |
+
),
|
| 312 |
+
],
|
| 313 |
+
n=np.random.randint(0, 5),
|
| 314 |
+
replace=False,
|
| 315 |
+
),
|
| 316 |
+
A.Normalize(mean=[0, 0, 0], std=[1, 1, 1], max_pixel_value=255), # Normalize to [0, 1]
|
| 317 |
+
],
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def load_image(path: Path) -> np.ndarray:
|
| 322 |
+
return np.array(Image.open(path))
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def _shift(category_id: int, fragment_id: int) -> int:
|
| 326 |
+
return 10 * (category_id - 1) + fragment_id
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def masks_to_seg(masks: np.ndarray, category_ids: list[int], fragment_ids: list[int]) -> np.ndarray:
|
| 330 |
+
"""Convert masks to a binary-encoded multi-label segmentation.
|
| 331 |
+
|
| 332 |
+
Binarizes the segmentation at each pixel by left shifting the one-hot mask by
|
| 333 |
+
10 * (category_id - 1) + (fragment_id)
|
| 334 |
+
|
| 335 |
+
Args:
|
| 336 |
+
masks (np.ndarray): [n, h, w] boolean masks.
|
| 337 |
+
category_ids (list[int]): [n] integer category IDs, in SA (1), LI (2) or RI (3).
|
| 338 |
+
fragment_ids (list[int]): [n] integer fragment IDs, in [1,10].
|
| 339 |
+
|
| 340 |
+
Returns:
|
| 341 |
+
np.ndarray: [h, w] uint32 segmentation, where each pixel is a 32-bit integer encoding the
|
| 342 |
+
whether the
|
| 343 |
+
|
| 344 |
+
"""
|
| 345 |
+
|
| 346 |
+
seg = np.zeros((masks.shape[1], masks.shape[2]), dtype=np.uint32)
|
| 347 |
+
masks = masks.astype(np.uint32)
|
| 348 |
+
for mask, category_id, fragment_id in zip(masks, category_ids, fragment_ids):
|
| 349 |
+
seg = np.bitwise_or(seg, np.left_shift(mask, _shift(category_id, fragment_id)))
|
| 350 |
+
return seg
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def seg_to_masks(seg: np.ndarray) -> tuple[np.ndarray, list[int], list[int]]:
|
| 354 |
+
"""Convert a binary-encoded multi-label segmentation to masks."""
|
| 355 |
+
category_ids = []
|
| 356 |
+
fragment_ids = []
|
| 357 |
+
masks = []
|
| 358 |
+
for category_id in CATEGORIES.values():
|
| 359 |
+
for fragment_id in range(1, 11):
|
| 360 |
+
mask = np.right_shift(seg, _shift(category_id, fragment_id)) & 1
|
| 361 |
+
if mask.sum() > 0:
|
| 362 |
+
masks.append(mask)
|
| 363 |
+
category_ids.append(category_id)
|
| 364 |
+
fragment_ids.append(fragment_id)
|
| 365 |
+
|
| 366 |
+
return np.array(masks), category_ids, fragment_ids
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def load_masks(path: Path) -> tuple[np.ndarray, list[int], list[int]]:
|
| 370 |
+
seg = np.array(Image.open(path))
|
| 371 |
+
return seg_to_masks(seg)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def neglog_window(image: np.ndarray, epsilon: float = 0.01) -> np.ndarray:
|
| 375 |
+
"""Take the negative log transform of an intensity image.
|
| 376 |
+
|
| 377 |
+
Args:
|
| 378 |
+
image (np.ndarray): a single 2D image.
|
| 379 |
+
epsilon (float, optional): positive offset from 0 before taking the logarithm.
|
| 380 |
+
|
| 381 |
+
Returns:
|
| 382 |
+
np.ndarray: the image or images after a negative log transform, scaled to [0, 1]
|
| 383 |
+
"""
|
| 384 |
+
image = np.array(image)
|
| 385 |
+
shape = image.shape
|
| 386 |
+
if len(shape) == 2:
|
| 387 |
+
image = image[np.newaxis, :, :]
|
| 388 |
+
|
| 389 |
+
# shift image to avoid invalid values
|
| 390 |
+
image += image.min(axis=(1, 2), keepdims=True) + epsilon
|
| 391 |
+
|
| 392 |
+
# negative log transform
|
| 393 |
+
image = -np.log(image)
|
| 394 |
+
|
| 395 |
+
# linear interpolate to range [0, 1]
|
| 396 |
+
image_min = image.min(axis=(1, 2), keepdims=True)
|
| 397 |
+
image_max = image.max(axis=(1, 2), keepdims=True)
|
| 398 |
+
if np.any(image_max == image_min):
|
| 399 |
+
print(
|
| 400 |
+
f"mapping constant image to 0. This probably indicates the projector is pointed away from the volume."
|
| 401 |
+
)
|
| 402 |
+
image[:] = 0
|
| 403 |
+
if image.shape[0] > 1:
|
| 404 |
+
print("TODO: zeroed all images, even though only one might be bad.")
|
| 405 |
+
else:
|
| 406 |
+
image = (image - image_min) / (image_max - image_min)
|
| 407 |
+
|
| 408 |
+
if np.any(np.isnan(image)):
|
| 409 |
+
print(f"got NaN values from negative log transform.")
|
| 410 |
+
|
| 411 |
+
if len(shape) == 2:
|
| 412 |
+
return image[0]
|
| 413 |
+
else:
|
| 414 |
+
return image
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def as_uint8(image: np.ndarray) -> np.ndarray:
|
| 418 |
+
"""Convert the image to uint8.
|
| 419 |
+
|
| 420 |
+
Args:
|
| 421 |
+
image (np.ndarray): the image to convert.
|
| 422 |
+
|
| 423 |
+
Returns:
|
| 424 |
+
np.ndarray: the converted image.
|
| 425 |
+
"""
|
| 426 |
+
if image.dtype in [np.float16, np.float32, np.float64]:
|
| 427 |
+
image = np.clip(image * 255, 0, 255).astype(np.uint8)
|
| 428 |
+
elif image.dtype == bool:
|
| 429 |
+
image = image.astype(np.uint8) * 255
|
| 430 |
+
elif image.dtype != np.uint8:
|
| 431 |
+
print(f"Unknown image type {image.dtype}. Converting to uint8.")
|
| 432 |
+
image = image.astype(np.uint8)
|
| 433 |
+
return image
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
def as_float32(image: np.ndarray) -> np.ndarray:
|
| 437 |
+
"""Convert the image to float32.
|
| 438 |
+
|
| 439 |
+
Args:
|
| 440 |
+
image (np.ndarray): the image to convert.
|
| 441 |
+
|
| 442 |
+
Returns:
|
| 443 |
+
np.ndarray: the converted image.
|
| 444 |
+
"""
|
| 445 |
+
if image.dtype in [np.float16, np.float32, np.float64]:
|
| 446 |
+
image = image.astype(np.float32)
|
| 447 |
+
elif image.dtype == bool:
|
| 448 |
+
image = image.astype(np.float32)
|
| 449 |
+
elif image.dtype != np.uint8:
|
| 450 |
+
print(f"Unknown image type {image.dtype}. Converting to float32.")
|
| 451 |
+
image = image.astype(np.float32)
|
| 452 |
+
else:
|
| 453 |
+
image = image.astype(np.float32) / 255
|
| 454 |
+
return image
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def visualize_drr(image: np.ndarray) -> np.ndarray:
|
| 458 |
+
"""Process a raw DRR for visualization.
|
| 459 |
+
|
| 460 |
+
Args:
|
| 461 |
+
image (np.ndarray): The raw float32 DRR."""
|
| 462 |
+
# Cast to uint8
|
| 463 |
+
image = neglog_window(image)
|
| 464 |
+
image = as_uint8(image)
|
| 465 |
+
|
| 466 |
+
# apply clahe and invert
|
| 467 |
+
clahe = cv2.createCLAHE(clipLimit=4, tileGridSize=(8, 8))
|
| 468 |
+
image = clahe.apply(image)
|
| 469 |
+
image = 255 - image
|
| 470 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 471 |
+
return image
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def draw_masks(
|
| 475 |
+
image: np.ndarray,
|
| 476 |
+
masks: np.ndarray,
|
| 477 |
+
alpha: float = 0.3,
|
| 478 |
+
threshold: float = 0.5,
|
| 479 |
+
names: Optional[list[str]] = None,
|
| 480 |
+
colors: Optional[np.ndarray] = None,
|
| 481 |
+
palette: str = "hls",
|
| 482 |
+
seed: Optional[int] = None,
|
| 483 |
+
) -> np.ndarray:
|
| 484 |
+
"""Draw contours of masks on an image (copy).
|
| 485 |
+
|
| 486 |
+
Args:
|
| 487 |
+
image (np.ndarray): the image to draw on.
|
| 488 |
+
masks (np.ndarray): the masks to draw. [num_masks, H, W] array of masks.
|
| 489 |
+
"""
|
| 490 |
+
|
| 491 |
+
image = as_float32(image)
|
| 492 |
+
if image.ndim == 2:
|
| 493 |
+
image = np.stack([image] * 3, axis=-1)
|
| 494 |
+
|
| 495 |
+
if colors is None:
|
| 496 |
+
colors = np.array(sns.color_palette(palette, masks.shape[0]))
|
| 497 |
+
if seed is not None:
|
| 498 |
+
np.random.seed(seed)
|
| 499 |
+
colors = colors[np.random.permutation(colors.shape[0])]
|
| 500 |
+
|
| 501 |
+
image *= 1 - alpha
|
| 502 |
+
for i, mask in enumerate(masks):
|
| 503 |
+
bool_mask = mask > threshold
|
| 504 |
+
|
| 505 |
+
image[bool_mask] = colors[i] * alpha + image[bool_mask] * (1 - alpha)
|
| 506 |
+
|
| 507 |
+
contours, _ = cv2.findContours(
|
| 508 |
+
bool_mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
|
| 509 |
+
)
|
| 510 |
+
image = as_uint8(image)
|
| 511 |
+
cv2.drawContours(image, contours, -1, (255 * colors[i]).tolist(), 1)
|
| 512 |
+
image = as_float32(image)
|
| 513 |
+
|
| 514 |
+
image = as_uint8(image)
|
| 515 |
+
|
| 516 |
+
fontscale = 0.75 / 512 * image.shape[0]
|
| 517 |
+
thickness = max(int(1 / 256 * image.shape[0]), 1)
|
| 518 |
+
|
| 519 |
+
if names is not None:
|
| 520 |
+
for i, mask in enumerate(masks):
|
| 521 |
+
bool_mask = mask > threshold
|
| 522 |
+
ys, xs = np.argwhere(bool_mask).T
|
| 523 |
+
if len(ys) == 0:
|
| 524 |
+
continue
|
| 525 |
+
y = (np.min(ys) + np.max(ys)) / 2
|
| 526 |
+
x = (np.min(xs) + np.max(xs)) / 2
|
| 527 |
+
image = cv2.putText(
|
| 528 |
+
image,
|
| 529 |
+
names[i],
|
| 530 |
+
(int(x) + 5, int(y) - 5),
|
| 531 |
+
cv2.FONT_HERSHEY_SIMPLEX,
|
| 532 |
+
fontscale,
|
| 533 |
+
(255 * colors[i]).tolist(),
|
| 534 |
+
thickness,
|
| 535 |
+
cv2.LINE_AA,
|
| 536 |
+
)
|
| 537 |
+
|
| 538 |
+
return image
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def visualize_sample(image, masks, category_ids, fragment_ids):
|
| 542 |
+
"""Visualize the image and masks."""
|
| 543 |
+
names = [
|
| 544 |
+
f"{LABELS[category_id]}-{fragment_id}"
|
| 545 |
+
for category_id, fragment_id in zip(category_ids, fragment_ids)
|
| 546 |
+
]
|
| 547 |
+
image = visualize_drr(image)
|
| 548 |
+
return draw_masks(image, masks, names=names, seed=0)
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
class Dataset:
|
| 552 |
+
def __init__(self, root: Path, split: str, img_size: int = 448):
|
| 553 |
+
self.root = Path(root).expanduser()
|
| 554 |
+
self.split = split
|
| 555 |
+
self.img_size = img_size
|
| 556 |
+
assert self.split in ["train", "val", "test"]
|
| 557 |
+
|
| 558 |
+
self.input_dir = self.root / self.split / "input" / "images" / "x-ray"
|
| 559 |
+
self.output_dir = self.root / self.split / "output" / "images" / "x-ray"
|
| 560 |
+
|
| 561 |
+
self.image_paths = sorted(self.input_dir.glob("*.tif"))
|
| 562 |
+
|
| 563 |
+
def __len__(self, index: int):
|
| 564 |
+
image_path = self.image_paths[index]
|
| 565 |
+
seg_path = self.output_dir / image_path.name
|
| 566 |
+
|
| 567 |
+
image = load_image(image_path)
|
| 568 |
+
masks, category_ids, fragment_ids = load_masks(seg_path)
|
| 569 |
+
track_ids = [
|
| 570 |
+
1000 * cat_id + fragment_id for cat_id, fragment_id in zip(category_ids, fragment_ids)
|
| 571 |
+
]
|
| 572 |
+
|
| 573 |
+
# Augmentation
|
| 574 |
+
aug = build_augmentation(train=self.split == "train")
|
| 575 |
+
augmented = aug(image=image, masks=masks, category_ids=track_ids)
|
| 576 |
+
|
| 577 |
+
image = augmented["image"]
|
| 578 |
+
masks = augmented["masks"]
|
| 579 |
+
track_ids = augmented["category_ids"]
|
| 580 |
+
category_ids = [track_id // 1000 for track_id in track_ids]
|
| 581 |
+
fragment_ids = [track_id % 1000 for track_id in track_ids]
|
| 582 |
+
|
| 583 |
+
return image, masks, category_ids, fragment_ids
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
if __name__ == "__main__":
|
| 587 |
+
import shutil
|
| 588 |
+
import imageio.v3 as iio
|
| 589 |
+
|
| 590 |
+
root = Path("/home/killeen/datasets/OneDrive/datasets/PENGWIN")
|
| 591 |
+
image_path = root / Path("test/input/images/x-ray/122_0350.tif")
|
| 592 |
+
mask_path = root / Path("test/output/images/x-ray/122_0350.tif")
|
| 593 |
+
|
| 594 |
+
shutil.copy(str(mask_path), "images/seg1.tif")
|
| 595 |
+
|
| 596 |
+
# tiff to masks
|
| 597 |
+
image = load_image(image_path)
|
| 598 |
+
masks, category_ids, fragment_ids = load_masks(mask_path)
|
| 599 |
+
print(category_ids, fragment_ids)
|
| 600 |
+
print(masks.shape)
|
| 601 |
+
|
| 602 |
+
vis_image = visualize_sample(image, masks, category_ids, fragment_ids)
|
| 603 |
+
vis_path = Path("images/sample_original.png")
|
| 604 |
+
cv2.imwrite(str(vis_path), vis_image)
|
| 605 |
+
print(f"Wrote image to {vis_path}")
|
| 606 |
+
|
| 607 |
+
# masks to tiff
|
| 608 |
+
seg_cycle = masks_to_seg(masks, category_ids, fragment_ids)
|
| 609 |
+
seg_path = Path("images/seg2.tif")
|
| 610 |
+
iio.imwrite(seg_path, seg_cycle)
|
| 611 |
+
# Image.fromarray(seg_cycle).save(seg_path)
|
| 612 |
+
print(f"Wrote segmentation to {seg_path}")
|
| 613 |
+
|
| 614 |
+
# Images/seg2.tif and Images/seg1.tif should be the same
|
| 615 |
+
masks, category_ids, fragment_ids = load_masks(seg_path)
|
| 616 |
+
print(category_ids, fragment_ids)
|
| 617 |
+
vis_image = visualize_sample(image, masks, category_ids, fragment_ids)
|
| 618 |
+
cv2.imwrite("images/sample_cycle.png", vis_image)
|
| 619 |
+
print(f"Wrote image to images/sample_cycle.png")
|