micro_sam.v2.transforms.raw
1import random 2from functools import partial 3from typing import Callable, Dict, Optional, Tuple 4 5import numpy as np 6 7import torch 8import torchvision.transforms.functional as TF 9from torchvision.transforms import ColorJitter 10 11from torch_em.transform.generic import Compose 12from torch_em.transform.raw import RandomPercentileNormalization, RawTransform 13 14from .labels import _em_cell_label_trafo # noqa 15from .labels import _plantseg_label_trafo # noqa 16from micro_sam.v2.normalization import normalize_raw 17from .labels import _axondeepseg_pre_label_transform # noqa 18 19 20# NOTE: This is a legacy function: we will keep this for now for unpickling checkpoints saved before the refactor. 21def _axondeepseg_label_transform(y): # noqa 22 from bioimage_cpp.segmentation import label as connected_components 23 return connected_components(y == 2).astype("uint32") 24 25 26def to_rgb(image): 27 if image.ndim == 2: # Simple triplication with channels first. 28 image = np.concatenate([image[None]] * 3, axis=0) 29 30 if image.ndim == 3 and image.shape[-1] == 3: # Make channels first for RGB images. 31 image = image.transpose(2, 0, 1) 32 33 assert image.ndim == 3 34 return image 35 36 37def _prepare_to_8bit(raw): 38 """Prepare raw inputs for ``_to_8bit`` without changing their dynamic range.""" 39 if raw.ndim == 3 and raw.shape[0] == 1: # If the inputs have 1 channel, we triplicate it. 40 raw = np.concatenate([raw] * 3, axis=0) 41 42 return to_rgb(raw) # Ensure channel-first RGB without rescaling the original intensities. 43 44 45def _to_8bit(raw): 46 "Ensures three channels for inputs and percentile-normalizes them to [0, 1]." 47 raw = _prepare_to_8bit(raw) 48 raw = normalize_raw(raw, axis=(1, 2)) 49 return raw 50 51 52def _prepare_identity(x): 53 """Prepare raw inputs for ``_identity`` without changing their dynamic range.""" 54 return to_rgb(x) 55 56 57def _identity(x): 58 "Ensures three channels for inputs and percentile-normalizes them to [0, 1]." 59 x = _prepare_identity(x) 60 x = normalize_raw(x, axis=(1, 2)) 61 return x 62 63 64def _prepare_cellpose_raw(x): 65 """Prepare CellPose inputs without changing their dynamic range. 66 67 NOTE: The input channel logic is arranged a bit strangely in `cyto` dataset. 68 This function takes care of it here. 69 """ 70 r, g, b = x 71 72 assert g.max() != 0 73 if r.max() == 0: 74 # The image is 1 channel and exists in green channel only. 75 assert b.max() == 0 76 x = np.concatenate([g[None]] * 3, axis=0) 77 78 elif r.max() != 0 and g.max() != 0: 79 # The image is 2 channels and we sort the channels such that - 0: cell, 1: nucleus 80 x = np.stack([g, r, np.zeros_like(b)], axis=0) 81 82 return to_rgb(x) # Ensures three channels for inputs and avoids rescaling inputs. 83 84 85def _cellpose_raw_trafo(x): 86 """Prepare and percentile-normalize CellPose inputs.""" 87 x = _prepare_cellpose_raw(x) 88 x = normalize_raw(x, axis=(1, 2)) 89 return x 90 91 92def _prepare_select_channel(raw, channel): 93 """Keep one channel of a multi-channel image and triplicate it, without normalizing.""" 94 plane = raw[channel] if raw.shape[0] <= 8 else raw[..., channel] 95 return np.stack([plane] * 3).astype("float32") 96 97 98def _drop_alpha_channel(raw): 99 """Drop the alpha channel of a channel-first RGBA image (NuInsSeg stores one png that way).""" 100 return raw[:3] if raw.ndim == 3 and raw.shape[0] == 4 else raw 101 102 103def _prepare_enseg_green_channel(raw): 104 """enseg is stored RGB but only the green channel carries signal.""" 105 return _prepare_select_channel(raw, 1) 106 107 108def _enseg_green_channel(raw): 109 return normalize_raw(_prepare_enseg_green_channel(raw), axis=(1, 2)) 110 111 112def _prepare_xenium_cell_channels(raw): 113 """Xenium cell target: drop the DAPI channel (0) and keep the three morphology stains the cells were grown from.""" 114 return np.asarray(raw[1:4], dtype="float32") 115 116 117def _xenium_cell_channels(raw): 118 return normalize_raw(_prepare_xenium_cell_channels(raw), axis=(1, 2)) 119 120 121def _prepare_pan_multiplex_tissuenet_order(raw): 122 """Reorder pan_multiplex from (nuclei, membrane) to TissueNet's membrane, nucleus, zeros.""" 123 nuclei, membrane = raw[0], raw[1] 124 return np.stack([membrane, nuclei, np.zeros_like(membrane)]).astype("float32") 125 126 127def _pan_multiplex_tissuenet_order(raw): 128 return normalize_raw(_prepare_pan_multiplex_tissuenet_order(raw), axis=(1, 2)) 129 130 131def _prepare_cvz_cell_channels(raw): 132 """Reorder the CVZ cell composite from (membrane, membrane, DAPI) to membrane, DAPI, membrane.""" 133 raw = to_rgb(raw) 134 return np.stack([raw[0], raw[2], raw[1]]).astype("float32") 135 136 137def _cvz_cell_channels(raw): 138 return normalize_raw(_prepare_cvz_cell_channels(raw), axis=(1, 2)) 139 140 141def _minmax_normalize(raw): 142 """Scale every channel to [0, 1] by its minimum and maximum.""" 143 raw = raw.astype("float32") 144 lo = raw.min(axis=(1, 2), keepdims=True) 145 hi = raw.max(axis=(1, 2), keepdims=True) 146 return (raw - lo) / (hi - lo + 1e-7) 147 148 149def _minmax_raw_trafo(raw): 150 """Min-max normalization for images whose background covers almost the whole percentile range (BBBC030).""" 151 return _minmax_normalize(_prepare_to_8bit(raw)) 152 153 154def _resize_to_512(x, is_label=False): 155 """Resize trailing spatial dimensions to longest side 512 and pad bottom/right.""" 156 from micro_sam.v2.transforms.resize import resize_longest_side_and_pad_spatial_numpy 157 return resize_longest_side_and_pad_spatial_numpy(x, target_length=512, is_label=is_label)[0] 158 159 160def _resize_raw_to_512(x): 161 """Resize small raw volume patch to 512×512 and normalize.""" 162 x = _prepare_resize_raw_to_512(x) 163 return normalize_raw(x, axis=(1, 2)) 164 165 166def _prepare_resize_raw_to_512(x): 167 """Resize a raw patch without normalizing it.""" 168 return _prepare_identity(_resize_to_512(x, is_label=False)) 169 170 171class VideoAugment: 172 """Consistent spatial + color augmentation for (B, C, [Z,] H, W) tensors in [0, 1]. 173 174 Mirrors the SAM2 MOSE finetune augmentation pipeline. Spatial transforms and 175 the first ColorJitter are applied with the same random parameters across all Z-frames 176 (consistent_transform=True in the original YAML). The second ColorJitter is applied 177 independently per frame (consistent_transform=False). 178 179 Spatial transforms are applied to the instance labels as well, with nearest-neighbour 180 interpolation, so image and label stay registered. Color transforms touch the raw only. 181 182 Args: 183 p_hflip: Probability of horizontal flip. 184 degrees: Max rotation magnitude for RandomAffine. 185 shear: Max shear magnitude for RandomAffine. 186 brightness: Per-video brightness jitter bound. 187 contrast: Per-video contrast jitter bound. 188 saturation: Per-video saturation jitter bound. 189 p_grayscale: Probability of converting the video to grayscale (consistent). 190 per_frame_brightness: Per-frame brightness jitter bound. 191 per_frame_contrast: Per-frame contrast jitter bound. 192 per_frame_saturation: Per-frame saturation jitter bound. 193 """ 194 195 def __init__( 196 self, 197 p_hflip: float = 0.5, 198 degrees: float = 25.0, 199 shear: float = 20.0, 200 brightness: float = 0.1, 201 contrast: float = 0.03, 202 saturation: float = 0.03, 203 p_grayscale: float = 0.05, 204 per_frame_brightness: float = 0.1, 205 per_frame_contrast: float = 0.05, 206 per_frame_saturation: float = 0.05, 207 ): 208 self.p_hflip = p_hflip 209 self.degrees = degrees 210 self.shear = shear 211 self.p_grayscale = p_grayscale 212 self._cj_vol = ColorJitter(brightness=brightness, contrast=contrast, saturation=saturation) 213 self._cj_frame = ColorJitter( 214 brightness=per_frame_brightness, contrast=per_frame_contrast, saturation=per_frame_saturation, 215 ) 216 217 @staticmethod 218 def _cj_apply(frame, fn_idx, b_f, c_f, s_f): 219 for fn_id in fn_idx: 220 if fn_id == 0 and b_f is not None: 221 frame = TF.adjust_brightness(frame, b_f) 222 elif fn_id == 1 and c_f is not None: 223 frame = TF.adjust_contrast(frame, c_f) 224 elif fn_id == 2 and s_f is not None: 225 frame = TF.adjust_saturation(frame, s_f) 226 return frame 227 228 def _augment_frames(self, frames, label_frames): 229 """Apply consistent-then-per-frame augmentation to lists of (C, H, W) raw and label frames. 230 231 Returns the augmented (raw frames, label frames). The spatial parameters are drawn once 232 and reused for every frame and for the labels. 233 """ 234 do_flip = random.random() < self.p_hflip 235 angle = random.uniform(-self.degrees, self.degrees) 236 shear_x = random.uniform(-self.shear, self.shear) 237 fn_idx_v, b_f_v, c_f_v, s_f_v, _ = self._cj_vol.get_params( 238 self._cj_vol.brightness, self._cj_vol.contrast, self._cj_vol.saturation, self._cj_vol.hue, 239 ) 240 do_gray = random.random() < self.p_grayscale 241 242 out, label_out = [], [] 243 for frame, label in zip(frames, label_frames): 244 if do_flip: 245 frame = TF.hflip(frame) 246 label = TF.hflip(label) 247 frame = TF.affine( 248 frame, angle=angle, translate=[0, 0], scale=1.0, shear=[shear_x, 0.0], 249 interpolation=TF.InterpolationMode.BILINEAR, 250 ) 251 # affine needs a float tensor; NEAREST keeps the instance IDs exact. 252 label = TF.affine( 253 label.float(), angle=angle, translate=[0, 0], scale=1.0, shear=[shear_x, 0.0], 254 interpolation=TF.InterpolationMode.NEAREST, 255 ).to(label.dtype) 256 frame = self._cj_apply(frame, fn_idx_v, b_f_v, c_f_v, s_f_v) 257 if do_gray: 258 frame = TF.rgb_to_grayscale(frame, num_output_channels=frame.shape[0]) 259 fn_idx_f, b_f_f, c_f_f, s_f_f, _ = self._cj_frame.get_params( 260 self._cj_frame.brightness, self._cj_frame.contrast, self._cj_frame.saturation, self._cj_frame.hue, 261 ) 262 frame = self._cj_apply(frame, fn_idx_f, b_f_f, c_f_f, s_f_f) 263 out.append(frame.clamp(0.0, 1.0)) 264 label_out.append(label) 265 return out, label_out 266 267 def __call__(self, x: torch.Tensor, y: torch.Tensor): 268 """ 269 Args: 270 x: (B, C, H, W) or (B, C, Z, H, W) float tensor in [0, 1]. 271 y: (B, 1, H, W) or (B, 1, Z, H, W) integer instance labels. 272 Returns: 273 Augmented (x, y) with the same shapes and dtypes. Spatial transforms are shared 274 between the two, so the labels stay registered to the image. 275 """ 276 is_3d = x.ndim == 5 277 B = x.shape[0] 278 out, label_out = [], [] 279 for b in range(B): 280 if is_3d: 281 Z = x.shape[2] 282 frames = [x[b, :, z] for z in range(Z)] 283 labels = [y[b, :, z] for z in range(Z)] 284 aug, aug_label = self._augment_frames(frames, labels) 285 out.append(torch.stack(aug, dim=1)) # (C, Z, H, W) 286 label_out.append(torch.stack(aug_label, dim=1)) # (1, Z, H, W) 287 else: 288 aug, aug_label = self._augment_frames([x[b]], [y[b]]) 289 out.append(aug[0]) # (C, H, W) 290 label_out.append(aug_label[0]) # (1, H, W) 291 return torch.stack(out), torch.stack(label_out) 292 293 294class VideoAugmentTransform: 295 """torch-em dataset transform with MOSE-style augmentation for 3D microscopy. 296 297 Unlike VideoAugment (which runs in the training loop, on whole batches), this class 298 is designed for the dataloader transform argument and therefore: 299 - Runs in DataLoader workers, in parallel with the GPU forward pass. 300 - Operates on a single sample rather than a batch. 301 Both apply spatial transforms to raw and labels consistently, and color only to raw. 302 303 Designed for (C, Z, H, W) raw arrays and (1, Z, H, W) label arrays 304 from torch-em 3D segmentation datasets. 305 306 Args: 307 p_hflip: Horizontal flip probability. 308 p_vflip: Vertical flip probability. 309 p_zflip: Z-axis (depth) flip probability. Reverses frame order, teaching the model 310 to propagate in both directions. Default 0.0; set to 0.5 for bidirectional training. 311 brightness: Volume-consistent brightness jitter bound. 312 contrast: Volume-consistent contrast jitter bound. 313 saturation: Volume-consistent saturation jitter bound. 314 per_frame_brightness: Per-frame brightness jitter bound. 315 per_frame_contrast: Per-frame contrast jitter bound. 316 per_frame_saturation: Per-frame saturation jitter bound. 317 """ 318 319 def __init__( 320 self, 321 p_hflip: float = 0.5, 322 p_vflip: float = 0.5, 323 p_zflip: float = 0.0, 324 brightness: float = 0.1, 325 contrast: float = 0.03, 326 saturation: float = 0.03, 327 per_frame_brightness: float = 0.1, 328 per_frame_contrast: float = 0.05, 329 per_frame_saturation: float = 0.05, 330 ): 331 self.p_hflip = p_hflip 332 self.p_vflip = p_vflip 333 self.p_zflip = p_zflip 334 self._cj_vol = ColorJitter(brightness=brightness, contrast=contrast, saturation=saturation) 335 self._cj_frame = ColorJitter( 336 brightness=per_frame_brightness, contrast=per_frame_contrast, saturation=per_frame_saturation, 337 ) 338 339 def __call__(self, raw, labels): 340 """Apply augmentation to a single 3D sample. 341 342 Args: 343 raw: (Z, H, W) or (C, Z, H, W) float array in [0, 1]. 344 labels: integer array with the same spatial shape as raw. 345 346 Returns: 347 Tuple of (augmented raw, augmented labels). 348 """ 349 # ascontiguousarray with explicit dtype converts byte order (TIFF and HDF5 sources 350 # can use big-endian, which torch.from_numpy cannot handle without conversion). 351 raw_t = torch.from_numpy(np.ascontiguousarray(raw, dtype=np.float32)) 352 labels_t = torch.from_numpy(np.ascontiguousarray(labels, dtype=np.int64)) 353 354 if random.random() < self.p_hflip: 355 raw_t = TF.hflip(raw_t) 356 labels_t = TF.hflip(labels_t) 357 if random.random() < self.p_vflip: 358 raw_t = TF.vflip(raw_t) 359 labels_t = TF.vflip(labels_t) 360 if random.random() < self.p_zflip: 361 z_dim = 1 if raw_t.ndim == 4 else 0 362 raw_t = torch.flip(raw_t, dims=[z_dim]) 363 labels_t = torch.flip(labels_t, dims=[z_dim]) 364 365 # Color jitter on raw only. TF functions expect (C, H, W), so we iterate over Z. 366 # For (Z, H, W) input, treat each Z-slice as a (1, H, W) single-channel frame. 367 is_4d = raw_t.ndim == 4 368 frames = [raw_t[:, z] for z in range(raw_t.shape[1])] if is_4d else [ 369 raw_t[z].unsqueeze(0) for z in range(raw_t.shape[0]) 370 ] 371 fn_idx_v, b_f_v, c_f_v, s_f_v, _ = self._cj_vol.get_params( 372 self._cj_vol.brightness, self._cj_vol.contrast, self._cj_vol.saturation, self._cj_vol.hue, 373 ) 374 out = [] 375 for frame in frames: 376 frame = VideoAugment._cj_apply(frame, fn_idx_v, b_f_v, c_f_v, s_f_v) 377 fn_idx_f, b_f_f, c_f_f, s_f_f, _ = self._cj_frame.get_params( 378 self._cj_frame.brightness, self._cj_frame.contrast, self._cj_frame.saturation, self._cj_frame.hue, 379 ) 380 frame = VideoAugment._cj_apply(frame, fn_idx_f, b_f_f, c_f_f, s_f_f) 381 out.append(frame.clamp(0.0, 1.0)) 382 383 if is_4d: 384 raw_t = torch.stack(out, dim=1) # (C, Z, H, W) 385 else: 386 raw_t = torch.stack([f.squeeze(0) for f in out]) # (Z, H, W) 387 388 return raw_t.numpy(), labels_t.numpy() 389 390 391class ImageAugmentTransform: 392 """torch-em dataset transform with flips + ColorJitter for 2D microscopy images. 393 394 The 2D analogue of VideoAugmentTransform: horizontal/vertical flips are applied 395 to both raw and labels, and two-stage ColorJitter (matching the MOSE finetune 396 bounds) to the raw image only. Expects (C, H, W) raw in [0, 1] - i.e. it runs 397 after the raw_transform - and an integer label of matching spatial shape. 398 399 Args: 400 p_hflip: Horizontal flip probability. 401 p_vflip: Vertical flip probability. 402 brightness: First-stage brightness jitter bound. 403 contrast: First-stage contrast jitter bound. 404 saturation: First-stage saturation jitter bound. 405 per_frame_brightness: Second-stage brightness jitter bound. 406 per_frame_contrast: Second-stage contrast jitter bound. 407 per_frame_saturation: Second-stage saturation jitter bound. 408 """ 409 410 def __init__( 411 self, 412 p_hflip: float = 0.5, 413 p_vflip: float = 0.5, 414 brightness: float = 0.1, 415 contrast: float = 0.03, 416 saturation: float = 0.03, 417 per_frame_brightness: float = 0.1, 418 per_frame_contrast: float = 0.05, 419 per_frame_saturation: float = 0.05, 420 ): 421 self.p_hflip = p_hflip 422 self.p_vflip = p_vflip 423 self._cj_1 = ColorJitter(brightness=brightness, contrast=contrast, saturation=saturation) 424 self._cj_2 = ColorJitter( 425 brightness=per_frame_brightness, contrast=per_frame_contrast, saturation=per_frame_saturation, 426 ) 427 428 def __call__(self, raw, labels): 429 """Apply augmentation to a single 2D sample. 430 431 Args: 432 raw: (C, H, W) float array in [0, 1]. 433 labels: integer array with the same spatial shape as raw. 434 435 Returns: 436 Tuple of (augmented raw, augmented labels). 437 """ 438 raw_t = torch.from_numpy(np.ascontiguousarray(raw, dtype=np.float32)) 439 labels_t = torch.from_numpy(np.ascontiguousarray(labels, dtype=np.int64)) 440 441 if random.random() < self.p_hflip: 442 raw_t = TF.hflip(raw_t) 443 labels_t = TF.hflip(labels_t) 444 if random.random() < self.p_vflip: 445 raw_t = TF.vflip(raw_t) 446 labels_t = TF.vflip(labels_t) 447 448 for cj in (self._cj_1, self._cj_2): 449 fn_idx, b, c, s, _ = cj.get_params(cj.brightness, cj.contrast, cj.saturation, cj.hue) 450 raw_t = VideoAugment._cj_apply(raw_t, fn_idx, b, c, s) 451 raw_t = raw_t.clamp(0.0, 1.0) 452 453 return raw_t.numpy(), labels_t.numpy() 454 455 456def _normalize_percentile(x, axis=None): 457 """Transforms input images with percentile normalization. 458 459 NOTE: For example, this is a specific input transformation for 460 'rgb' format of TissueNet image data for the expected axes. 461 """ 462 return normalize_raw(x, axis=axis) 463 464 465def get_random_percentile_normalization( 466 raw_transform: Callable, 467 lower_percentile_bounds: Tuple[float, float] = (0.0, 5.0), 468 distribution: str = "uniform", 469 distribution_kwargs: Optional[Dict[str, float]] = None, 470) -> RawTransform: 471 """Convert a generalist raw transform to random percentile normalization. 472 473 The data-specific shape/channel preparation is retained as ``RawTransform.augmentation1``, so the 474 normalizer receives data in its original intensity range. An existing ``augmentation2`` is preserved. 475 """ 476 augmentation2 = None 477 if isinstance(raw_transform, Compose): 478 # torch-em datasets such as ifnuclei and hela_cytonuc prepend a channel selection to the given transform. 479 *prepare, inner = raw_transform.transforms 480 base = get_random_percentile_normalization(inner, lower_percentile_bounds, distribution, distribution_kwargs) 481 steps = prepare + ([base.augmentation1] if base.augmentation1 is not None else []) 482 augmentation1 = Compose(*steps, is_multi_tensor=False) 483 return RawTransform(normalizer=base.normalizer, augmentation1=augmentation1, augmentation2=base.augmentation2) 484 if isinstance(raw_transform, RawTransform): 485 augmentation1, augmentation2 = raw_transform.augmentation1, raw_transform.augmentation2 486 if isinstance(raw_transform.normalizer, RandomPercentileNormalization): 487 axis = raw_transform.normalizer.axis 488 elif raw_transform.normalizer is _identity: 489 # Defect-augmented EM datasets (CREMI): the defect pipeline lives in augmentation1 with an 490 # identity normalizer. Preserve it and apply per-channel percentile normalization. 491 axis = (1, 2) 492 else: 493 raise ValueError(f"Unsupported normalizer in generalist raw transform: {raw_transform.normalizer!r}") 494 elif isinstance(raw_transform, RandomPercentileNormalization): 495 augmentation1, axis = None, raw_transform.axis 496 elif raw_transform is _identity: 497 augmentation1, axis = _prepare_identity, (1, 2) 498 elif raw_transform is _to_8bit: 499 augmentation1, axis = _prepare_to_8bit, (1, 2) 500 elif raw_transform is _cellpose_raw_trafo: 501 augmentation1, axis = _prepare_cellpose_raw, (1, 2) 502 elif raw_transform is _resize_raw_to_512: 503 augmentation1, axis = _prepare_resize_raw_to_512, (1, 2) 504 elif raw_transform is _enseg_green_channel: 505 augmentation1, axis = _prepare_enseg_green_channel, (1, 2) 506 elif raw_transform is _xenium_cell_channels: 507 augmentation1, axis = _prepare_xenium_cell_channels, (1, 2) 508 elif raw_transform is _pan_multiplex_tissuenet_order: 509 augmentation1, axis = _prepare_pan_multiplex_tissuenet_order, (1, 2) 510 elif raw_transform is _cvz_cell_channels: 511 augmentation1, axis = _prepare_cvz_cell_channels, (1, 2) 512 elif raw_transform is _minmax_raw_trafo: 513 # BBBC030's background spans about 4 % of the intensity range, so any percentile normalization saturates 514 # the cells; this transform stays min-max and is not randomized. 515 return RawTransform(normalizer=_minmax_normalize, augmentation1=_prepare_to_8bit) 516 elif raw_transform is _normalize_percentile: 517 augmentation1, axis = None, None 518 elif isinstance(raw_transform, partial) and raw_transform.func is _normalize_percentile: 519 if raw_transform.args: 520 raise ValueError("Positional arguments are not supported for _normalize_percentile transforms.") 521 unexpected_kwargs = set(raw_transform.keywords) - {"axis"} 522 if unexpected_kwargs: 523 raise ValueError(f"Unsupported _normalize_percentile arguments: {sorted(unexpected_kwargs)}") 524 augmentation1, axis = None, raw_transform.keywords.get("axis") 525 else: 526 raise ValueError(f"Unsupported generalist raw transform: {raw_transform!r}") 527 528 normalizer = RandomPercentileNormalization( 529 lower_percentile_bounds=lower_percentile_bounds, 530 distribution=distribution, 531 distribution_kwargs=distribution_kwargs, 532 rounding_decimals=1, 533 axis=axis, 534 ) 535 return RawTransform(normalizer=normalizer, augmentation1=augmentation1, augmentation2=augmentation2)
27def to_rgb(image): 28 if image.ndim == 2: # Simple triplication with channels first. 29 image = np.concatenate([image[None]] * 3, axis=0) 30 31 if image.ndim == 3 and image.shape[-1] == 3: # Make channels first for RGB images. 32 image = image.transpose(2, 0, 1) 33 34 assert image.ndim == 3 35 return image
172class VideoAugment: 173 """Consistent spatial + color augmentation for (B, C, [Z,] H, W) tensors in [0, 1]. 174 175 Mirrors the SAM2 MOSE finetune augmentation pipeline. Spatial transforms and 176 the first ColorJitter are applied with the same random parameters across all Z-frames 177 (consistent_transform=True in the original YAML). The second ColorJitter is applied 178 independently per frame (consistent_transform=False). 179 180 Spatial transforms are applied to the instance labels as well, with nearest-neighbour 181 interpolation, so image and label stay registered. Color transforms touch the raw only. 182 183 Args: 184 p_hflip: Probability of horizontal flip. 185 degrees: Max rotation magnitude for RandomAffine. 186 shear: Max shear magnitude for RandomAffine. 187 brightness: Per-video brightness jitter bound. 188 contrast: Per-video contrast jitter bound. 189 saturation: Per-video saturation jitter bound. 190 p_grayscale: Probability of converting the video to grayscale (consistent). 191 per_frame_brightness: Per-frame brightness jitter bound. 192 per_frame_contrast: Per-frame contrast jitter bound. 193 per_frame_saturation: Per-frame saturation jitter bound. 194 """ 195 196 def __init__( 197 self, 198 p_hflip: float = 0.5, 199 degrees: float = 25.0, 200 shear: float = 20.0, 201 brightness: float = 0.1, 202 contrast: float = 0.03, 203 saturation: float = 0.03, 204 p_grayscale: float = 0.05, 205 per_frame_brightness: float = 0.1, 206 per_frame_contrast: float = 0.05, 207 per_frame_saturation: float = 0.05, 208 ): 209 self.p_hflip = p_hflip 210 self.degrees = degrees 211 self.shear = shear 212 self.p_grayscale = p_grayscale 213 self._cj_vol = ColorJitter(brightness=brightness, contrast=contrast, saturation=saturation) 214 self._cj_frame = ColorJitter( 215 brightness=per_frame_brightness, contrast=per_frame_contrast, saturation=per_frame_saturation, 216 ) 217 218 @staticmethod 219 def _cj_apply(frame, fn_idx, b_f, c_f, s_f): 220 for fn_id in fn_idx: 221 if fn_id == 0 and b_f is not None: 222 frame = TF.adjust_brightness(frame, b_f) 223 elif fn_id == 1 and c_f is not None: 224 frame = TF.adjust_contrast(frame, c_f) 225 elif fn_id == 2 and s_f is not None: 226 frame = TF.adjust_saturation(frame, s_f) 227 return frame 228 229 def _augment_frames(self, frames, label_frames): 230 """Apply consistent-then-per-frame augmentation to lists of (C, H, W) raw and label frames. 231 232 Returns the augmented (raw frames, label frames). The spatial parameters are drawn once 233 and reused for every frame and for the labels. 234 """ 235 do_flip = random.random() < self.p_hflip 236 angle = random.uniform(-self.degrees, self.degrees) 237 shear_x = random.uniform(-self.shear, self.shear) 238 fn_idx_v, b_f_v, c_f_v, s_f_v, _ = self._cj_vol.get_params( 239 self._cj_vol.brightness, self._cj_vol.contrast, self._cj_vol.saturation, self._cj_vol.hue, 240 ) 241 do_gray = random.random() < self.p_grayscale 242 243 out, label_out = [], [] 244 for frame, label in zip(frames, label_frames): 245 if do_flip: 246 frame = TF.hflip(frame) 247 label = TF.hflip(label) 248 frame = TF.affine( 249 frame, angle=angle, translate=[0, 0], scale=1.0, shear=[shear_x, 0.0], 250 interpolation=TF.InterpolationMode.BILINEAR, 251 ) 252 # affine needs a float tensor; NEAREST keeps the instance IDs exact. 253 label = TF.affine( 254 label.float(), angle=angle, translate=[0, 0], scale=1.0, shear=[shear_x, 0.0], 255 interpolation=TF.InterpolationMode.NEAREST, 256 ).to(label.dtype) 257 frame = self._cj_apply(frame, fn_idx_v, b_f_v, c_f_v, s_f_v) 258 if do_gray: 259 frame = TF.rgb_to_grayscale(frame, num_output_channels=frame.shape[0]) 260 fn_idx_f, b_f_f, c_f_f, s_f_f, _ = self._cj_frame.get_params( 261 self._cj_frame.brightness, self._cj_frame.contrast, self._cj_frame.saturation, self._cj_frame.hue, 262 ) 263 frame = self._cj_apply(frame, fn_idx_f, b_f_f, c_f_f, s_f_f) 264 out.append(frame.clamp(0.0, 1.0)) 265 label_out.append(label) 266 return out, label_out 267 268 def __call__(self, x: torch.Tensor, y: torch.Tensor): 269 """ 270 Args: 271 x: (B, C, H, W) or (B, C, Z, H, W) float tensor in [0, 1]. 272 y: (B, 1, H, W) or (B, 1, Z, H, W) integer instance labels. 273 Returns: 274 Augmented (x, y) with the same shapes and dtypes. Spatial transforms are shared 275 between the two, so the labels stay registered to the image. 276 """ 277 is_3d = x.ndim == 5 278 B = x.shape[0] 279 out, label_out = [], [] 280 for b in range(B): 281 if is_3d: 282 Z = x.shape[2] 283 frames = [x[b, :, z] for z in range(Z)] 284 labels = [y[b, :, z] for z in range(Z)] 285 aug, aug_label = self._augment_frames(frames, labels) 286 out.append(torch.stack(aug, dim=1)) # (C, Z, H, W) 287 label_out.append(torch.stack(aug_label, dim=1)) # (1, Z, H, W) 288 else: 289 aug, aug_label = self._augment_frames([x[b]], [y[b]]) 290 out.append(aug[0]) # (C, H, W) 291 label_out.append(aug_label[0]) # (1, H, W) 292 return torch.stack(out), torch.stack(label_out)
Consistent spatial + color augmentation for (B, C, [Z,] H, W) tensors in [0, 1].
Mirrors the SAM2 MOSE finetune augmentation pipeline. Spatial transforms and the first ColorJitter are applied with the same random parameters across all Z-frames (consistent_transform=True in the original YAML). The second ColorJitter is applied independently per frame (consistent_transform=False).
Spatial transforms are applied to the instance labels as well, with nearest-neighbour interpolation, so image and label stay registered. Color transforms touch the raw only.
Arguments:
- p_hflip: Probability of horizontal flip.
- degrees: Max rotation magnitude for RandomAffine.
- shear: Max shear magnitude for RandomAffine.
- brightness: Per-video brightness jitter bound.
- contrast: Per-video contrast jitter bound.
- saturation: Per-video saturation jitter bound.
- p_grayscale: Probability of converting the video to grayscale (consistent).
- per_frame_brightness: Per-frame brightness jitter bound.
- per_frame_contrast: Per-frame contrast jitter bound.
- per_frame_saturation: Per-frame saturation jitter bound.
196 def __init__( 197 self, 198 p_hflip: float = 0.5, 199 degrees: float = 25.0, 200 shear: float = 20.0, 201 brightness: float = 0.1, 202 contrast: float = 0.03, 203 saturation: float = 0.03, 204 p_grayscale: float = 0.05, 205 per_frame_brightness: float = 0.1, 206 per_frame_contrast: float = 0.05, 207 per_frame_saturation: float = 0.05, 208 ): 209 self.p_hflip = p_hflip 210 self.degrees = degrees 211 self.shear = shear 212 self.p_grayscale = p_grayscale 213 self._cj_vol = ColorJitter(brightness=brightness, contrast=contrast, saturation=saturation) 214 self._cj_frame = ColorJitter( 215 brightness=per_frame_brightness, contrast=per_frame_contrast, saturation=per_frame_saturation, 216 )
295class VideoAugmentTransform: 296 """torch-em dataset transform with MOSE-style augmentation for 3D microscopy. 297 298 Unlike VideoAugment (which runs in the training loop, on whole batches), this class 299 is designed for the dataloader transform argument and therefore: 300 - Runs in DataLoader workers, in parallel with the GPU forward pass. 301 - Operates on a single sample rather than a batch. 302 Both apply spatial transforms to raw and labels consistently, and color only to raw. 303 304 Designed for (C, Z, H, W) raw arrays and (1, Z, H, W) label arrays 305 from torch-em 3D segmentation datasets. 306 307 Args: 308 p_hflip: Horizontal flip probability. 309 p_vflip: Vertical flip probability. 310 p_zflip: Z-axis (depth) flip probability. Reverses frame order, teaching the model 311 to propagate in both directions. Default 0.0; set to 0.5 for bidirectional training. 312 brightness: Volume-consistent brightness jitter bound. 313 contrast: Volume-consistent contrast jitter bound. 314 saturation: Volume-consistent saturation jitter bound. 315 per_frame_brightness: Per-frame brightness jitter bound. 316 per_frame_contrast: Per-frame contrast jitter bound. 317 per_frame_saturation: Per-frame saturation jitter bound. 318 """ 319 320 def __init__( 321 self, 322 p_hflip: float = 0.5, 323 p_vflip: float = 0.5, 324 p_zflip: float = 0.0, 325 brightness: float = 0.1, 326 contrast: float = 0.03, 327 saturation: float = 0.03, 328 per_frame_brightness: float = 0.1, 329 per_frame_contrast: float = 0.05, 330 per_frame_saturation: float = 0.05, 331 ): 332 self.p_hflip = p_hflip 333 self.p_vflip = p_vflip 334 self.p_zflip = p_zflip 335 self._cj_vol = ColorJitter(brightness=brightness, contrast=contrast, saturation=saturation) 336 self._cj_frame = ColorJitter( 337 brightness=per_frame_brightness, contrast=per_frame_contrast, saturation=per_frame_saturation, 338 ) 339 340 def __call__(self, raw, labels): 341 """Apply augmentation to a single 3D sample. 342 343 Args: 344 raw: (Z, H, W) or (C, Z, H, W) float array in [0, 1]. 345 labels: integer array with the same spatial shape as raw. 346 347 Returns: 348 Tuple of (augmented raw, augmented labels). 349 """ 350 # ascontiguousarray with explicit dtype converts byte order (TIFF and HDF5 sources 351 # can use big-endian, which torch.from_numpy cannot handle without conversion). 352 raw_t = torch.from_numpy(np.ascontiguousarray(raw, dtype=np.float32)) 353 labels_t = torch.from_numpy(np.ascontiguousarray(labels, dtype=np.int64)) 354 355 if random.random() < self.p_hflip: 356 raw_t = TF.hflip(raw_t) 357 labels_t = TF.hflip(labels_t) 358 if random.random() < self.p_vflip: 359 raw_t = TF.vflip(raw_t) 360 labels_t = TF.vflip(labels_t) 361 if random.random() < self.p_zflip: 362 z_dim = 1 if raw_t.ndim == 4 else 0 363 raw_t = torch.flip(raw_t, dims=[z_dim]) 364 labels_t = torch.flip(labels_t, dims=[z_dim]) 365 366 # Color jitter on raw only. TF functions expect (C, H, W), so we iterate over Z. 367 # For (Z, H, W) input, treat each Z-slice as a (1, H, W) single-channel frame. 368 is_4d = raw_t.ndim == 4 369 frames = [raw_t[:, z] for z in range(raw_t.shape[1])] if is_4d else [ 370 raw_t[z].unsqueeze(0) for z in range(raw_t.shape[0]) 371 ] 372 fn_idx_v, b_f_v, c_f_v, s_f_v, _ = self._cj_vol.get_params( 373 self._cj_vol.brightness, self._cj_vol.contrast, self._cj_vol.saturation, self._cj_vol.hue, 374 ) 375 out = [] 376 for frame in frames: 377 frame = VideoAugment._cj_apply(frame, fn_idx_v, b_f_v, c_f_v, s_f_v) 378 fn_idx_f, b_f_f, c_f_f, s_f_f, _ = self._cj_frame.get_params( 379 self._cj_frame.brightness, self._cj_frame.contrast, self._cj_frame.saturation, self._cj_frame.hue, 380 ) 381 frame = VideoAugment._cj_apply(frame, fn_idx_f, b_f_f, c_f_f, s_f_f) 382 out.append(frame.clamp(0.0, 1.0)) 383 384 if is_4d: 385 raw_t = torch.stack(out, dim=1) # (C, Z, H, W) 386 else: 387 raw_t = torch.stack([f.squeeze(0) for f in out]) # (Z, H, W) 388 389 return raw_t.numpy(), labels_t.numpy()
torch-em dataset transform with MOSE-style augmentation for 3D microscopy.
Unlike VideoAugment (which runs in the training loop, on whole batches), this class is designed for the dataloader transform argument and therefore:
- Runs in DataLoader workers, in parallel with the GPU forward pass.
- Operates on a single sample rather than a batch. Both apply spatial transforms to raw and labels consistently, and color only to raw.
Designed for (C, Z, H, W) raw arrays and (1, Z, H, W) label arrays from torch-em 3D segmentation datasets.
Arguments:
- p_hflip: Horizontal flip probability.
- p_vflip: Vertical flip probability.
- p_zflip: Z-axis (depth) flip probability. Reverses frame order, teaching the model to propagate in both directions. Default 0.0; set to 0.5 for bidirectional training.
- brightness: Volume-consistent brightness jitter bound.
- contrast: Volume-consistent contrast jitter bound.
- saturation: Volume-consistent saturation jitter bound.
- per_frame_brightness: Per-frame brightness jitter bound.
- per_frame_contrast: Per-frame contrast jitter bound.
- per_frame_saturation: Per-frame saturation jitter bound.
320 def __init__( 321 self, 322 p_hflip: float = 0.5, 323 p_vflip: float = 0.5, 324 p_zflip: float = 0.0, 325 brightness: float = 0.1, 326 contrast: float = 0.03, 327 saturation: float = 0.03, 328 per_frame_brightness: float = 0.1, 329 per_frame_contrast: float = 0.05, 330 per_frame_saturation: float = 0.05, 331 ): 332 self.p_hflip = p_hflip 333 self.p_vflip = p_vflip 334 self.p_zflip = p_zflip 335 self._cj_vol = ColorJitter(brightness=brightness, contrast=contrast, saturation=saturation) 336 self._cj_frame = ColorJitter( 337 brightness=per_frame_brightness, contrast=per_frame_contrast, saturation=per_frame_saturation, 338 )
392class ImageAugmentTransform: 393 """torch-em dataset transform with flips + ColorJitter for 2D microscopy images. 394 395 The 2D analogue of VideoAugmentTransform: horizontal/vertical flips are applied 396 to both raw and labels, and two-stage ColorJitter (matching the MOSE finetune 397 bounds) to the raw image only. Expects (C, H, W) raw in [0, 1] - i.e. it runs 398 after the raw_transform - and an integer label of matching spatial shape. 399 400 Args: 401 p_hflip: Horizontal flip probability. 402 p_vflip: Vertical flip probability. 403 brightness: First-stage brightness jitter bound. 404 contrast: First-stage contrast jitter bound. 405 saturation: First-stage saturation jitter bound. 406 per_frame_brightness: Second-stage brightness jitter bound. 407 per_frame_contrast: Second-stage contrast jitter bound. 408 per_frame_saturation: Second-stage saturation jitter bound. 409 """ 410 411 def __init__( 412 self, 413 p_hflip: float = 0.5, 414 p_vflip: float = 0.5, 415 brightness: float = 0.1, 416 contrast: float = 0.03, 417 saturation: float = 0.03, 418 per_frame_brightness: float = 0.1, 419 per_frame_contrast: float = 0.05, 420 per_frame_saturation: float = 0.05, 421 ): 422 self.p_hflip = p_hflip 423 self.p_vflip = p_vflip 424 self._cj_1 = ColorJitter(brightness=brightness, contrast=contrast, saturation=saturation) 425 self._cj_2 = ColorJitter( 426 brightness=per_frame_brightness, contrast=per_frame_contrast, saturation=per_frame_saturation, 427 ) 428 429 def __call__(self, raw, labels): 430 """Apply augmentation to a single 2D sample. 431 432 Args: 433 raw: (C, H, W) float array in [0, 1]. 434 labels: integer array with the same spatial shape as raw. 435 436 Returns: 437 Tuple of (augmented raw, augmented labels). 438 """ 439 raw_t = torch.from_numpy(np.ascontiguousarray(raw, dtype=np.float32)) 440 labels_t = torch.from_numpy(np.ascontiguousarray(labels, dtype=np.int64)) 441 442 if random.random() < self.p_hflip: 443 raw_t = TF.hflip(raw_t) 444 labels_t = TF.hflip(labels_t) 445 if random.random() < self.p_vflip: 446 raw_t = TF.vflip(raw_t) 447 labels_t = TF.vflip(labels_t) 448 449 for cj in (self._cj_1, self._cj_2): 450 fn_idx, b, c, s, _ = cj.get_params(cj.brightness, cj.contrast, cj.saturation, cj.hue) 451 raw_t = VideoAugment._cj_apply(raw_t, fn_idx, b, c, s) 452 raw_t = raw_t.clamp(0.0, 1.0) 453 454 return raw_t.numpy(), labels_t.numpy()
torch-em dataset transform with flips + ColorJitter for 2D microscopy images.
The 2D analogue of VideoAugmentTransform: horizontal/vertical flips are applied to both raw and labels, and two-stage ColorJitter (matching the MOSE finetune bounds) to the raw image only. Expects (C, H, W) raw in [0, 1] - i.e. it runs after the raw_transform - and an integer label of matching spatial shape.
Arguments:
- p_hflip: Horizontal flip probability.
- p_vflip: Vertical flip probability.
- brightness: First-stage brightness jitter bound.
- contrast: First-stage contrast jitter bound.
- saturation: First-stage saturation jitter bound.
- per_frame_brightness: Second-stage brightness jitter bound.
- per_frame_contrast: Second-stage contrast jitter bound.
- per_frame_saturation: Second-stage saturation jitter bound.
411 def __init__( 412 self, 413 p_hflip: float = 0.5, 414 p_vflip: float = 0.5, 415 brightness: float = 0.1, 416 contrast: float = 0.03, 417 saturation: float = 0.03, 418 per_frame_brightness: float = 0.1, 419 per_frame_contrast: float = 0.05, 420 per_frame_saturation: float = 0.05, 421 ): 422 self.p_hflip = p_hflip 423 self.p_vflip = p_vflip 424 self._cj_1 = ColorJitter(brightness=brightness, contrast=contrast, saturation=saturation) 425 self._cj_2 = ColorJitter( 426 brightness=per_frame_brightness, contrast=per_frame_contrast, saturation=per_frame_saturation, 427 )
466def get_random_percentile_normalization( 467 raw_transform: Callable, 468 lower_percentile_bounds: Tuple[float, float] = (0.0, 5.0), 469 distribution: str = "uniform", 470 distribution_kwargs: Optional[Dict[str, float]] = None, 471) -> RawTransform: 472 """Convert a generalist raw transform to random percentile normalization. 473 474 The data-specific shape/channel preparation is retained as ``RawTransform.augmentation1``, so the 475 normalizer receives data in its original intensity range. An existing ``augmentation2`` is preserved. 476 """ 477 augmentation2 = None 478 if isinstance(raw_transform, Compose): 479 # torch-em datasets such as ifnuclei and hela_cytonuc prepend a channel selection to the given transform. 480 *prepare, inner = raw_transform.transforms 481 base = get_random_percentile_normalization(inner, lower_percentile_bounds, distribution, distribution_kwargs) 482 steps = prepare + ([base.augmentation1] if base.augmentation1 is not None else []) 483 augmentation1 = Compose(*steps, is_multi_tensor=False) 484 return RawTransform(normalizer=base.normalizer, augmentation1=augmentation1, augmentation2=base.augmentation2) 485 if isinstance(raw_transform, RawTransform): 486 augmentation1, augmentation2 = raw_transform.augmentation1, raw_transform.augmentation2 487 if isinstance(raw_transform.normalizer, RandomPercentileNormalization): 488 axis = raw_transform.normalizer.axis 489 elif raw_transform.normalizer is _identity: 490 # Defect-augmented EM datasets (CREMI): the defect pipeline lives in augmentation1 with an 491 # identity normalizer. Preserve it and apply per-channel percentile normalization. 492 axis = (1, 2) 493 else: 494 raise ValueError(f"Unsupported normalizer in generalist raw transform: {raw_transform.normalizer!r}") 495 elif isinstance(raw_transform, RandomPercentileNormalization): 496 augmentation1, axis = None, raw_transform.axis 497 elif raw_transform is _identity: 498 augmentation1, axis = _prepare_identity, (1, 2) 499 elif raw_transform is _to_8bit: 500 augmentation1, axis = _prepare_to_8bit, (1, 2) 501 elif raw_transform is _cellpose_raw_trafo: 502 augmentation1, axis = _prepare_cellpose_raw, (1, 2) 503 elif raw_transform is _resize_raw_to_512: 504 augmentation1, axis = _prepare_resize_raw_to_512, (1, 2) 505 elif raw_transform is _enseg_green_channel: 506 augmentation1, axis = _prepare_enseg_green_channel, (1, 2) 507 elif raw_transform is _xenium_cell_channels: 508 augmentation1, axis = _prepare_xenium_cell_channels, (1, 2) 509 elif raw_transform is _pan_multiplex_tissuenet_order: 510 augmentation1, axis = _prepare_pan_multiplex_tissuenet_order, (1, 2) 511 elif raw_transform is _cvz_cell_channels: 512 augmentation1, axis = _prepare_cvz_cell_channels, (1, 2) 513 elif raw_transform is _minmax_raw_trafo: 514 # BBBC030's background spans about 4 % of the intensity range, so any percentile normalization saturates 515 # the cells; this transform stays min-max and is not randomized. 516 return RawTransform(normalizer=_minmax_normalize, augmentation1=_prepare_to_8bit) 517 elif raw_transform is _normalize_percentile: 518 augmentation1, axis = None, None 519 elif isinstance(raw_transform, partial) and raw_transform.func is _normalize_percentile: 520 if raw_transform.args: 521 raise ValueError("Positional arguments are not supported for _normalize_percentile transforms.") 522 unexpected_kwargs = set(raw_transform.keywords) - {"axis"} 523 if unexpected_kwargs: 524 raise ValueError(f"Unsupported _normalize_percentile arguments: {sorted(unexpected_kwargs)}") 525 augmentation1, axis = None, raw_transform.keywords.get("axis") 526 else: 527 raise ValueError(f"Unsupported generalist raw transform: {raw_transform!r}") 528 529 normalizer = RandomPercentileNormalization( 530 lower_percentile_bounds=lower_percentile_bounds, 531 distribution=distribution, 532 distribution_kwargs=distribution_kwargs, 533 rounding_decimals=1, 534 axis=axis, 535 ) 536 return RawTransform(normalizer=normalizer, augmentation1=augmentation1, augmentation2=augmentation2)
Convert a generalist raw transform to random percentile normalization.
The data-specific shape/channel preparation is retained as RawTransform.augmentation1, so the
normalizer receives data in its original intensity range. An existing augmentation2 is preserved.