micro_sam.pixel_classification
1import os 2from joblib import dump, load 3from multiprocessing import cpu_count 4from typing import List, Optional, Sequence, Tuple, Union 5 6import numpy as np 7from skimage.transform import resize 8 9from sklearn.decomposition import PCA 10from sklearn.pipeline import Pipeline 11from sklearn.ensemble import RandomForestClassifier 12 13import torch 14 15try: 16 from napari.utils import progress as tqdm 17except ImportError: 18 from tqdm import tqdm 19 20from bioimage_cpp.utils import Blocking 21 22from . import util 23from .v1.util import precompute_image_embeddings 24from .classical_features import compute_classical_pixel_features 25 26# Default in-plane grid size (longest side) for the per-pixel feature grid. 27# Non-tiled images use 'grid_size'. Tiled images use the larger 'max_grid_size', since tiling 28# yields more genuine embedding detail (n_tiles x the per-tile resolution). 29DEFAULT_GRID_SIZE = 256 30DEFAULT_MAX_GRID_SIZE = 512 31 32# AnyUp paper checkpoint (raw state_dict), loaded into a default AnyUp() (see anyup/hubconf.py). 33ANYUP_URL = "https://github.com/wimmerth/anyup/releases/download/checkpoint/anyup_paper.pth" 34# ImageNet statistics AnyUp was trained with, applied to the image after mapping it to [0, 1]. 35IMAGENET_MEAN = (0.485, 0.456, 0.406) 36IMAGENET_STD = (0.229, 0.224, 0.225) 37# Cap the number of query rows processed per AnyUp cross-attention chunk, to bound peak memory on 38# large (e.g. full, untiled) images. Does not change results, only memory/runtime. 39ANYUP_Q_CHUNK_SIZE = 4096 40 41 42def get_anyup_upsampler(checkpoint_path: Optional[Union[str, os.PathLike]] = None, device=None): 43 """Load the AnyUp feature upsampler. 44 45 AnyUp is an optional dependency. The weights are resolved from `checkpoint_path`, then the 46 `MICROSAM_ANYUP_CHECKPOINT` environment variable, and finally the released paper checkpoint 47 (downloaded to the 'anyup' folder of the micro-sam model cache). 48 49 Args: 50 checkpoint_path: Optional path to a local AnyUp state_dict. 51 device: The device to load the model on. By default, the best available device. 52 53 Returns: 54 The AnyUp model in eval mode. 55 """ 56 try: 57 from anyup.model import AnyUp 58 except ImportError as e: 59 raise ImportError( 60 "Upsampling with AnyUp requires the 'anyup' package. It is not available on PyPI or conda-forge. " 61 "Install it via 'pip install git+https://github.com/wimmerth/anyup'" 62 ) from e 63 64 device = util.get_device(device) 65 checkpoint_path = checkpoint_path or os.environ.get("MICROSAM_ANYUP_CHECKPOINT") 66 if checkpoint_path is not None: 67 state_dict = torch.load(checkpoint_path, map_location=device) 68 else: 69 model_dir = util.get_model_cache_directory("anyup") 70 state_dict = torch.hub.load_state_dict_from_url(ANYUP_URL, model_dir=model_dir, map_location=device) 71 72 model = AnyUp().to(device) 73 model.load_state_dict(state_dict) 74 return model.eval() 75 76 77def _to_anyup_image(image: np.ndarray, device) -> torch.Tensor: 78 """Convert an image to the AnyUp input tensor (1, 3, H, W). 79 80 The image is first mapped to the uint8 3-channel RGB that SAM itself consumed via 81 `util._to_image` (same channel mapping and per-channel min-max normalization), then scaled 82 to [0, 1] and ImageNet-normalized to match AnyUp's training distribution. 83 """ 84 rgb = util._to_image(image) # (H, W, 3) uint8, identical to what SAM saw 85 tensor = torch.from_numpy(np.ascontiguousarray(rgb)).to(device).float().permute(2, 0, 1).unsqueeze(0) / 255.0 86 mean = torch.tensor(IMAGENET_MEAN, device=device).view(1, -1, 1, 1) 87 std = torch.tensor(IMAGENET_STD, device=device).view(1, -1, 1, 1) 88 return (tensor - mean) / std 89 90 91def _anyup_to_grid(embeddings: np.ndarray, image_region: np.ndarray, target_hw: Tuple[int, int], upsampler): 92 """Upsample a (C, H, W) embedding to a (target_h, target_w, C) feature image with AnyUp. 93 94 Mirrors the contract of `_resize_to_grid`, but uses the matching `image_region` as guidance 95 instead of plain interpolation. The embedding is passed raw (AnyUp normalizes it internally). 96 """ 97 # AnyUp's internal convolutions need at least 2 px per spatial dim. Fall back to plain 98 # interpolation for degenerate sliver regions (e.g. a 1-px-tall edge tile). 99 if min(embeddings.shape[-2:]) < 2 or min(target_hw) < 2 or min(image_region.shape[:2]) < 2: 100 return _resize_to_grid(embeddings, target_hw) 101 102 device = next(upsampler.parameters()).device 103 image_tensor = _to_anyup_image(image_region, device) 104 feature_tensor = torch.from_numpy(np.ascontiguousarray(embeddings)).to(device).float().unsqueeze(0) 105 with torch.no_grad(): 106 upsampled = upsampler( 107 image_tensor, feature_tensor, output_size=tuple(target_hw), q_chunk_size=ANYUP_Q_CHUNK_SIZE 108 ) 109 return upsampled[0].permute(1, 2, 0).cpu().numpy().astype("float32") 110 111 112def _grid_shape(image_hw: Tuple[int, int], target_long: int) -> Tuple[Tuple[int, int], float]: 113 """Downsample an in-plane shape so the longest side equals 'target_long', preserving aspect.""" 114 height, width = image_hw 115 scale = target_long / max(height, width) 116 grid = (max(1, int(round(height * scale))), max(1, int(round(width * scale)))) 117 return grid, scale 118 119 120def _aspect_crop(embeddings: np.ndarray, block_hw: Tuple[int, int]) -> np.ndarray: 121 """Crop a square (C, H, W) embedding to the aspect ratio of the (non-square) block it covers. 122 123 SAM pads the input to a square before encoding, so the embedding is square even for 124 non-square images. We crop away the padded region to recover the image-aligned part. 125 """ 126 emb_h, emb_w = embeddings.shape[-2:] 127 block_h, block_w = block_hw 128 if block_h == block_w: 129 return embeddings 130 # Keep at least one pixel: a very oblong block can round the crop length down to zero. 131 if block_h > block_w: 132 return embeddings[:, :, :max(1, int(round((block_w / block_h) * emb_w)))] 133 return embeddings[:, :max(1, int(round((block_h / block_w) * emb_h))), :] 134 135 136def _resize_to_grid(embeddings: np.ndarray, target_hw: Tuple[int, int]) -> np.ndarray: 137 """Resize a (C, H, W) embedding to a (target_h, target_w, C) feature image.""" 138 n_channels = embeddings.shape[0] 139 # An empty target band (a sub-pixel-thin edge strip) has nothing to fill, and a degenerate 140 # zero-size source cannot be interpolated. In both cases return a zero-filled band so the caller's 141 # slice assignment does nothing instead of resizing to or from a zero-size shape (which raises a NaN). 142 if min(target_hw) == 0 or min(embeddings.shape[-2:]) == 0: 143 return np.zeros((target_hw[0], target_hw[1], n_channels), dtype="float32") 144 feature_image = embeddings.transpose(1, 2, 0) 145 resize_shape = (target_hw[0], target_hw[1], feature_image.shape[-1]) 146 return resize(feature_image, resize_shape, preserve_range=True).astype("float32") 147 148 149def _block_to_grid(embeddings, block_hw, target_hw, image_region=None, upsampler=None, pbar_update=None): 150 """Crop a block embedding to its aspect ratio and map it to the target grid shape. 151 152 The encoders pad the image to a square, so the square embedding has content in a sub-rectangle 153 that we crop out. With `upsampler`, AnyUp upsamples the embedding using `image_region` as 154 guidance; otherwise it is plainly interpolated. 155 """ 156 block = _aspect_crop(embeddings, block_hw) 157 if upsampler is not None: 158 result = _anyup_to_grid(block, image_region, target_hw, upsampler) 159 if pbar_update is not None: 160 pbar_update(1) 161 return result 162 return _resize_to_grid(block, target_hw) 163 164 165def _compute_tiled_feature_image( 166 features, image_hw, max_grid_size, z=None, image=None, upsampler=None, pbar_update=None 167): 168 """Assemble a downsampled (GH, GW, C) feature image for a single 2d (tiled) plane. 169 170 For 3d data 'z' selects the slice of each tile's embedding. For 2d data 'z' is None. 171 With `upsampler`, each tile's inner block is upsampled with AnyUp using the matching image crop. 172 """ 173 tile_shape, halo, shape = features.attrs["tile_shape"], features.attrs["halo"], features.attrs["shape"] 174 # A 3d volume stores (z, y, x), but the tiling is in-plane. 175 tiling = Blocking([0, 0], list(shape)[-2:], list(tile_shape)) 176 grid, scale = _grid_shape(image_hw, max_grid_size) 177 178 feature_image = None 179 for block_id in range(tiling.number_of_blocks): 180 tile_embeds = features[str(block_id)] 181 embeds = np.asarray(tile_embeds[:] if z is None else tile_embeds[z]).squeeze() 182 if feature_image is None: 183 feature_image = np.zeros(grid + (embeds.shape[0],), dtype="float32") 184 185 block = tiling.get_block_with_halo(block_id, list(halo)) 186 outer, inner_local = block.outer_block, block.inner_block_local 187 outer_hw = (outer.end[0] - outer.begin[0], outer.end[1] - outer.begin[1]) 188 189 # The tile is padded to a square, so crop to the outer block aspect. 190 embeds = _aspect_crop(embeds, outer_hw) 191 tile_scale = (embeds.shape[-2] / outer_hw[0], embeds.shape[-1] / outer_hw[1]) 192 iy0, iy1 = int(round(inner_local.begin[0] * tile_scale[0])), int(round(inner_local.end[0] * tile_scale[0])) 193 ix0, ix1 = int(round(inner_local.begin[1] * tile_scale[1])), int(round(inner_local.end[1] * tile_scale[1])) 194 # A thin edge tile can round its inner region to zero feature rows or columns. Keep at least one 195 # real row or column so the strip gets coarse (but valid) features instead of an empty, un-resizable block. 196 iy0, ix0 = min(iy0, embeds.shape[-2] - 1), min(ix0, embeds.shape[-1] - 1) 197 iy1, ix1 = max(iy1, iy0 + 1), max(ix1, ix0 + 1) 198 inner_embeds = embeds[:, iy0:iy1, ix0:ix1] 199 200 # Map the inner block to its position in the global grid and place the features there. 201 gy0, gy1 = outer.begin[0] + inner_local.begin[0], outer.begin[0] + inner_local.end[0] 202 gx0, gx1 = outer.begin[1] + inner_local.begin[1], outer.begin[1] + inner_local.end[1] 203 by0, by1 = int(round(gy0 * scale)), int(round(gy1 * scale)) 204 bx0, bx1 = int(round(gx0 * scale)), int(round(gx1 * scale)) 205 if upsampler is not None: 206 image_crop = image[gy0:gy1, gx0:gx1] if z is None else image[z, gy0:gy1, gx0:gx1] 207 feature_image[by0:by1, bx0:bx1] = _anyup_to_grid( 208 inner_embeds, image_crop, (by1 - by0, bx1 - bx0), upsampler 209 ) 210 if pbar_update is not None: 211 pbar_update(1) 212 else: 213 feature_image[by0:by1, bx0:bx1] = _resize_to_grid(inner_embeds, (by1 - by0, bx1 - bx0)) 214 215 return feature_image, grid 216 217 218def compute_pixel_features( 219 image_embeddings: util.ImageEmbeddings, 220 image_shape: Tuple[int, ...], 221 grid_size: int = DEFAULT_GRID_SIZE, 222 max_grid_size: int = DEFAULT_MAX_GRID_SIZE, 223 image: Optional[np.ndarray] = None, 224 upsampler=None, 225 verbose: bool = True, 226 classical_features: Optional[Sequence[str]] = None, 227) -> Tuple[np.ndarray, Tuple[int, ...]]: 228 """Compute per-pixel features from SAM embeddings for pixel classification. 229 230 Each spatial location of the SAM embedding becomes a feature vector. The features are 231 computed on a downsampled in-plane grid (preserving the image aspect ratio) to keep them 232 tractable, and the grid prediction is later projected back to the full image resolution. 233 234 Args: 235 image_embeddings: The precomputed image embeddings. 236 image_shape: The spatial shape of the image, (H, W) for 2d or (Z, H, W) for 3d. 237 grid_size: In-plane grid size (longest side) for non-tiled images. 238 max_grid_size: In-plane grid size (longest side) for tiled images. 239 image: The original image, required when `upsampler` or `classical_features` is given. 240 upsampler: An optional AnyUp model (see `get_anyup_upsampler`). When given, the embedding 241 is upsampled with AnyUp using the image instead of plain interpolation. 242 verbose: Whether to print a progressbar for the computation. 243 classical_features: The classical filter features to append to the embedding features, a subset 244 of `classical_features.PIXEL_FEATURES`. By default no classical features are used. 245 246 Returns: 247 The per-pixel features, of shape (N, C) flattened over the grid in row-major order. 248 The grid shape, (gh, gw) for 2d or (Z, gh, gw) for 3d. 249 """ 250 if upsampler is not None and image is None: 251 raise ValueError("An 'image' is required when an AnyUp 'upsampler' is given.") 252 if classical_features is not None and image is None: 253 raise ValueError("An 'image' is required when 'classical_features' are given.") 254 255 is_tiled = image_embeddings["input_size"] is None 256 is_3d = len(image_shape) == 3 257 features = image_embeddings["features"] 258 259 # AnyUp is the slow part, so when it is used we show a dedicated progress bar (which also drives 260 # napari's activity indicator) ticking once per AnyUp call, and silence the per-slice bar. 261 depth = image_shape[0] if is_3d else 1 262 anyup_pbar, pbar_update = None, None 263 if upsampler is not None: 264 if is_tiled: 265 n_blocks = Blocking( 266 [0, 0], list(features.attrs["shape"])[-2:], list(features.attrs["tile_shape"]) 267 ).number_of_blocks 268 else: 269 n_blocks = 1 270 anyup_pbar = util._progress_bar(total=n_blocks * depth, desc="Upsampling with AnyUp", disable=not verbose) 271 pbar_update = anyup_pbar.update 272 slice_disable = (not verbose) or (upsampler is not None) 273 274 if is_3d: 275 image_hw = (image_shape[1], image_shape[2]) 276 planes = [] 277 for z in util._progress_bar(range(depth), total=depth, disable=slice_disable, desc="Compute pixel features"): 278 if is_tiled: 279 plane, grid = _compute_tiled_feature_image( 280 features, image_hw, max_grid_size, z=z, image=image, upsampler=upsampler, pbar_update=pbar_update 281 ) 282 else: 283 embeds = np.asarray(features[z]).squeeze() 284 grid, _ = _grid_shape(image_hw, grid_size) 285 plane = _block_to_grid( 286 embeds, image_hw, grid, image_region=None if image is None else image[z], 287 upsampler=upsampler, pbar_update=pbar_update, 288 ) 289 planes.append(plane) 290 feature_image = np.stack(planes) 291 grid_shape = (depth,) + grid 292 else: 293 image_hw = (image_shape[0], image_shape[1]) 294 if is_tiled: 295 feature_image, grid = _compute_tiled_feature_image( 296 features, image_hw, max_grid_size, image=image, upsampler=upsampler, pbar_update=pbar_update 297 ) 298 else: 299 embeds = np.asarray(features).squeeze() 300 grid, _ = _grid_shape(image_hw, grid_size) 301 feature_image = _block_to_grid( 302 embeds, image_hw, grid, image_region=image, upsampler=upsampler, pbar_update=pbar_update, 303 ) 304 grid_shape = grid 305 306 if anyup_pbar is not None: 307 anyup_pbar.close() 308 309 features = feature_image.reshape(-1, feature_image.shape[-1]) 310 if classical_features is not None: 311 classical = compute_classical_pixel_features(image, grid_shape, classical_features) 312 features = np.concatenate([features, classical], axis=1) 313 return features, grid_shape 314 315 316def accumulate_pixel_labels(annotation: np.ndarray, grid_shape: Tuple[int, ...]) -> np.ndarray: 317 """Resize a full-resolution annotation onto the feature grid and flatten it. 318 319 Args: 320 annotation: The pixel annotations (scribbles), of shape (H, W) or (Z, H, W). 321 grid_shape: The feature grid shape returned by `compute_pixel_features`. 322 323 Returns: 324 The labels flattened over the grid, aligned row-wise with the features. 325 """ 326 def resize_plane(plane, target_hw): 327 # A grid cell takes the class that most of its annotated pixels have. A nearest-neighbour resize 328 # samples one pixel per cell, so it loses most thin scribbles. 329 grid_h, grid_w = target_hw 330 out = np.zeros(target_hw, dtype=annotation.dtype) 331 ys, xs = np.nonzero(plane) 332 if len(ys) == 0: 333 return out 334 cells = (ys * grid_h // plane.shape[0]) * grid_w + xs * grid_w // plane.shape[1] 335 values = plane[ys, xs].astype("int64") 336 n_classes = int(values.max()) + 1 337 counts = np.bincount(cells * n_classes + values, minlength=grid_h * grid_w * n_classes) 338 counts = counts.reshape(grid_h * grid_w, n_classes) 339 annotated = counts.sum(axis=1) > 0 340 out.reshape(-1)[annotated] = counts[annotated].argmax(axis=1) 341 return out 342 343 if len(grid_shape) == 2: 344 return resize_plane(annotation, grid_shape).reshape(-1) 345 346 depth, grid_h, grid_w = grid_shape 347 labels = np.empty((depth, grid_h, grid_w), dtype=annotation.dtype) 348 for z in range(depth): 349 labels[z] = resize_plane(annotation[z], (grid_h, grid_w)) 350 return labels.reshape(-1) 351 352 353def project_prediction_to_image( 354 grid_prediction: np.ndarray, grid_shape: Tuple[int, ...], image_shape: Tuple[int, ...] 355) -> np.ndarray: 356 """Project a per-grid-pixel prediction back to the full image resolution. 357 358 Args: 359 grid_prediction: The flat prediction over the grid (one entry per grid pixel). 360 grid_shape: The feature grid shape returned by `compute_pixel_features`. 361 image_shape: The full image spatial shape, (H, W) or (Z, H, W). 362 363 Returns: 364 The pixel level prediction at the image resolution, a semantic segmentation. 365 """ 366 grid = np.asarray(grid_prediction).reshape(grid_shape) 367 368 def resize_plane(plane, target_hw): 369 return resize(plane, target_hw, order=0, anti_aliasing=False, preserve_range=True).astype(grid.dtype) 370 371 if len(grid_shape) == 2: 372 return resize_plane(grid, image_shape) 373 374 prediction = np.empty(image_shape, dtype=grid.dtype) 375 for z in range(image_shape[0]): 376 prediction[z] = resize_plane(grid[z], image_shape[1:]) 377 return prediction 378 379 380def train_pixel_classifier( 381 features: np.ndarray, 382 labels: np.ndarray, 383 previous_features: Optional[np.ndarray] = None, 384 previous_labels: Optional[np.ndarray] = None, 385 n_estimators: int = 200, 386 max_depth: int = 10, 387 n_jobs: Optional[int] = None, 388 n_components: Optional[int] = None, 389 random_state: Optional[int] = 0, 390 **rf_kwargs, 391): 392 """Train a random forest on per-pixel features and labels. 393 394 Pixels with label 0 are treated as unlabeled and excluded from training. This is the 395 shared training core used by both the interactive annotator and the batch training 396 function `run_training_with_pixel_classifier`. 397 398 Args: 399 features: The per-pixel features, of shape (N, C). 400 labels: The per-pixel labels, of shape (N,). Label 0 is treated as unlabeled. 401 previous_features: Features accumulated from previously annotated images, to train on jointly. 402 previous_labels: Labels matching `previous_features`. 403 n_estimators: The number of trees in the random forest. 404 max_depth: The maximum depth of each tree. 405 n_jobs: The number of parallel jobs for training. By default uses all available cores. 406 n_components: If given and smaller than the feature dimension, reduce the features to this 407 many PCA components before training. If `None`, `0` or `>=` the feature dimension, all 408 features are used. The fitted PCA is part of the returned model, so prediction transforms 409 the features automatically. 410 random_state: Seed for the random forest (and PCA) so training is reproducible. Pass `None` 411 to leave it unseeded, in which case predictions vary slightly between runs. 412 rf_kwargs: Additional keyword arguments for the `RandomForestClassifier`. 413 414 Returns: 415 The trained classifier. A `RandomForestClassifier`, or a `Pipeline` of PCA and the random 416 forest when `n_components` triggers dimensionality reduction. 417 """ 418 assert len(features) == len(labels) 419 valid = labels != 0 420 X, y = features[valid], labels[valid] 421 422 if previous_features is not None: 423 assert previous_labels is not None and len(previous_features) == len(previous_labels) 424 X = np.concatenate([previous_features, X], axis=0) 425 y = np.concatenate([previous_labels, y], axis=0) 426 427 rf = RandomForestClassifier( 428 n_estimators=n_estimators, max_depth=max_depth, 429 n_jobs=cpu_count() if n_jobs is None else n_jobs, random_state=random_state, **rf_kwargs, 430 ) 431 432 # Optionally reduce the features to the top-n PCA components. We clamp n_components to the 433 # number of features and samples. If it covers all features, we skip PCA and use the plain RF. 434 n_features = X.shape[1] 435 k = min(int(n_components), n_features, len(X)) if n_components else 0 436 if 0 < k < n_features: 437 model = Pipeline([("pca", PCA(n_components=k, random_state=random_state)), ("rf", rf)]) 438 else: 439 model = rf 440 441 model.fit(X, y) 442 return model 443 444 445# TODO think about the function signature, specially how exactly we pass model and optional embedding path. 446# TODO halo and tile shape. 447def run_training_with_pixel_classifier( 448 images: Sequence[Union[str, os.PathLike, np.ndarray]], 449 annotations: Sequence[Union[str, os.PathLike, np.ndarray]], 450 predictor, 451 rf_path: Union[str, os.PathLike], 452 image_key: Optional[str] = None, 453 annotation_key: Optional[str] = None, 454 ndim: Optional[int] = None, 455 n_estimators: int = 200, 456 max_depth: int = 10, 457 n_jobs: Optional[int] = None, 458 n_components: Optional[int] = None, 459 random_state: Optional[int] = 0, 460 upsampler=None, 461 classical_features: Optional[Sequence[str]] = None, 462 model_type: Optional[str] = None, 463 **rf_kwargs, 464): 465 """Train a pixel classifier on a series of images and (sparse) annotations. 466 467 Object features are computed from the SAM embeddings for each image, the annotations 468 are mapped onto the corresponding feature grid, and a random forest is trained on all 469 annotated pixels (pixels with label 0 are treated as unlabeled and ignored). 470 471 Args: 472 images: The images, either given as a list of numpy arrays or filepaths. 473 annotations: The pixel annotations (scribbles), either as numpy arrays or filepaths. 474 Pixels with value 0 are treated as unlabeled. Must match the order of `images`. 475 predictor: The Segment Anything predictor used to compute the embeddings. 476 rf_path: The filepath where the trained random forest will be saved. 477 image_key: The key for the image data, for filepath inputs (e.g. an internal dataset path). 478 annotation_key: The key for the annotation data, for filepath inputs. 479 ndim: The dimensionality of the data. If not given will be derived from the data. 480 n_estimators: The number of trees in the random forest. 481 max_depth: The maximum depth of each tree. 482 n_jobs: The number of parallel jobs for training. By default uses all available cores. 483 n_components: If given, reduce the features to this many PCA components before training. 484 If `None`, `0` or `>=` the feature dimension, all embedding channels are used. 485 random_state: Seed for the random forest (and PCA) so training is reproducible. Pass `None` 486 to leave it unseeded, in which case predictions vary slightly between runs. 487 upsampler: An optional AnyUp model (see `get_anyup_upsampler`) to upsample the embeddings 488 with the image as guidance instead of plain interpolation. 489 classical_features: The classical filter features to append to the embedding features, a subset 490 of `classical_features.PIXEL_FEATURES`. By default no classical features are used. 491 model_type: The model family of `predictor`, used to pick the matching embedding function 492 (SAM1 / SAM2 / VFM). If not given, the SAM1 embedding function is used. 493 rf_kwargs: Additional keyword arguments for the `RandomForestClassifier`. 494 495 Returns: 496 The trained classifier. 497 """ 498 if len(images) != len(annotations): 499 raise ValueError( 500 f"Expect the same number of images and annotations, got {len(images)}, {len(annotations)}." 501 ) 502 503 compute_embeddings = util.get_embedding_function(model_type) if model_type is not None \ 504 else precompute_image_embeddings 505 all_features, all_labels = [], [] 506 for image, annotation in tqdm( 507 zip(images, annotations), total=len(images), desc="Compute features for pixel classifier training" 508 ): 509 if isinstance(image, (str, os.PathLike)): 510 image = util.load_image_data(image, key=image_key) 511 if isinstance(annotation, (str, os.PathLike)): 512 annotation = util.load_image_data(annotation, key=annotation_key) 513 514 # Prepared in the same way as in the annotator, so the features match those of the GUI. 515 image, this_ndim, _ = util.prepare_annotation_image(image, ndim=ndim) 516 image_shape = image.shape[:this_ndim] 517 annotation = util.match_image_shape(annotation, image_shape) 518 embeddings = compute_embeddings(predictor, image, verbose=False, ndim=this_ndim) 519 use_image = upsampler is not None or classical_features is not None 520 features, grid_shape = compute_pixel_features( 521 embeddings, image_shape, image=image if use_image else None, 522 upsampler=upsampler, verbose=False, classical_features=classical_features, 523 ) 524 labels = accumulate_pixel_labels(annotation, grid_shape) 525 526 valid = labels != 0 527 if valid.any(): 528 all_features.append(features[valid]) 529 all_labels.append(labels[valid]) 530 531 if not all_features: 532 raise ValueError("None of the provided annotations contain labeled pixels.") 533 534 features = np.concatenate(all_features, axis=0) 535 labels = np.concatenate(all_labels, axis=0) 536 537 rf = train_pixel_classifier( 538 features, labels, n_estimators=n_estimators, max_depth=max_depth, n_jobs=n_jobs, 539 n_components=n_components, random_state=random_state, **rf_kwargs, 540 ) 541 542 dump(rf, rf_path) 543 return rf 544 545 546# TODO handle images as file paths. 547# TODO think about the function signature, specially how exactly we pass model and optional embedding path. 548# TODO halo and tile shape. 549# TODO add heuristic for ndim. 550def run_prediction_with_pixel_classifier( 551 images: Sequence[Union[str, os.PathLike, np.ndarray]], 552 predictor, 553 rf_path: Union[str, os.PathLike], 554 image_key: Optional[str] = None, 555 ndim: Optional[int] = None, 556 upsampler=None, 557 model_type: Optional[str] = None, 558 classical_features: Optional[Sequence[str]] = None, 559) -> List[np.ndarray]: 560 """Run prediction with a pretrained pixel classifier on a series of images. 561 562 Args: 563 images: The images, either given as a list of numpy arrays or filepaths. 564 predictor: The Segment Anything predictor used to compute the embeddings. 565 rf_path: The filepath to the trained random forest. 566 image_key: The key for the image data, for filepath inputs (e.g. an internal dataset path). 567 ndim: The dimensionality of the data. If not given will be derived from the data. 568 upsampler: An optional AnyUp model (see `get_anyup_upsampler`) to upsample the embeddings 569 with the image as guidance instead of plain interpolation. Use the same setting that 570 the classifier was trained with. 571 model_type: The model family of `predictor`, used to pick the matching embedding function 572 (SAM1 / SAM2 / VFM). If not given, the SAM1 embedding function is used. 573 classical_features: The classical filter features to append to the embedding features. 574 Use the same features that the classifier was trained with. 575 576 Returns: 577 The pixel level predictions. 578 """ 579 # Stored as {'rf': ..., 'model_spec': ...} by the GUI. Older or backend files are a bare classifier. 580 obj = load(rf_path) 581 rf = obj["rf"] if isinstance(obj, dict) and "rf" in obj else obj 582 compute_embeddings = util.get_embedding_function(model_type) if model_type is not None \ 583 else precompute_image_embeddings 584 predictions = [] 585 for image in tqdm(images, total=len(images), desc="Run prediction with pixel classifier"): 586 if isinstance(image, (str, os.PathLike)): 587 image = util.load_image_data(image, key=image_key) 588 # Prepared in the same way as in the annotator, so the features match those of the GUI. 589 image, this_ndim, _ = util.prepare_annotation_image(image, ndim=ndim) 590 image_shape = image.shape[:this_ndim] 591 embeddings = compute_embeddings(predictor, image, verbose=False, ndim=this_ndim) 592 use_image = upsampler is not None or classical_features is not None 593 features, grid_shape = compute_pixel_features( 594 embeddings, image_shape, image=image if use_image else None, 595 upsampler=upsampler, verbose=False, classical_features=classical_features, 596 ) 597 prediction = rf.predict(features) 598 predictions.append(project_prediction_to_image(prediction, grid_shape, image_shape)) 599 return predictions
43def get_anyup_upsampler(checkpoint_path: Optional[Union[str, os.PathLike]] = None, device=None): 44 """Load the AnyUp feature upsampler. 45 46 AnyUp is an optional dependency. The weights are resolved from `checkpoint_path`, then the 47 `MICROSAM_ANYUP_CHECKPOINT` environment variable, and finally the released paper checkpoint 48 (downloaded to the 'anyup' folder of the micro-sam model cache). 49 50 Args: 51 checkpoint_path: Optional path to a local AnyUp state_dict. 52 device: The device to load the model on. By default, the best available device. 53 54 Returns: 55 The AnyUp model in eval mode. 56 """ 57 try: 58 from anyup.model import AnyUp 59 except ImportError as e: 60 raise ImportError( 61 "Upsampling with AnyUp requires the 'anyup' package. It is not available on PyPI or conda-forge. " 62 "Install it via 'pip install git+https://github.com/wimmerth/anyup'" 63 ) from e 64 65 device = util.get_device(device) 66 checkpoint_path = checkpoint_path or os.environ.get("MICROSAM_ANYUP_CHECKPOINT") 67 if checkpoint_path is not None: 68 state_dict = torch.load(checkpoint_path, map_location=device) 69 else: 70 model_dir = util.get_model_cache_directory("anyup") 71 state_dict = torch.hub.load_state_dict_from_url(ANYUP_URL, model_dir=model_dir, map_location=device) 72 73 model = AnyUp().to(device) 74 model.load_state_dict(state_dict) 75 return model.eval()
Load the AnyUp feature upsampler.
AnyUp is an optional dependency. The weights are resolved from checkpoint_path, then the
MICROSAM_ANYUP_CHECKPOINT environment variable, and finally the released paper checkpoint
(downloaded to the 'anyup' folder of the micro-sam model cache).
Arguments:
- checkpoint_path: Optional path to a local AnyUp state_dict.
- device: The device to load the model on. By default, the best available device.
Returns:
The AnyUp model in eval mode.
219def compute_pixel_features( 220 image_embeddings: util.ImageEmbeddings, 221 image_shape: Tuple[int, ...], 222 grid_size: int = DEFAULT_GRID_SIZE, 223 max_grid_size: int = DEFAULT_MAX_GRID_SIZE, 224 image: Optional[np.ndarray] = None, 225 upsampler=None, 226 verbose: bool = True, 227 classical_features: Optional[Sequence[str]] = None, 228) -> Tuple[np.ndarray, Tuple[int, ...]]: 229 """Compute per-pixel features from SAM embeddings for pixel classification. 230 231 Each spatial location of the SAM embedding becomes a feature vector. The features are 232 computed on a downsampled in-plane grid (preserving the image aspect ratio) to keep them 233 tractable, and the grid prediction is later projected back to the full image resolution. 234 235 Args: 236 image_embeddings: The precomputed image embeddings. 237 image_shape: The spatial shape of the image, (H, W) for 2d or (Z, H, W) for 3d. 238 grid_size: In-plane grid size (longest side) for non-tiled images. 239 max_grid_size: In-plane grid size (longest side) for tiled images. 240 image: The original image, required when `upsampler` or `classical_features` is given. 241 upsampler: An optional AnyUp model (see `get_anyup_upsampler`). When given, the embedding 242 is upsampled with AnyUp using the image instead of plain interpolation. 243 verbose: Whether to print a progressbar for the computation. 244 classical_features: The classical filter features to append to the embedding features, a subset 245 of `classical_features.PIXEL_FEATURES`. By default no classical features are used. 246 247 Returns: 248 The per-pixel features, of shape (N, C) flattened over the grid in row-major order. 249 The grid shape, (gh, gw) for 2d or (Z, gh, gw) for 3d. 250 """ 251 if upsampler is not None and image is None: 252 raise ValueError("An 'image' is required when an AnyUp 'upsampler' is given.") 253 if classical_features is not None and image is None: 254 raise ValueError("An 'image' is required when 'classical_features' are given.") 255 256 is_tiled = image_embeddings["input_size"] is None 257 is_3d = len(image_shape) == 3 258 features = image_embeddings["features"] 259 260 # AnyUp is the slow part, so when it is used we show a dedicated progress bar (which also drives 261 # napari's activity indicator) ticking once per AnyUp call, and silence the per-slice bar. 262 depth = image_shape[0] if is_3d else 1 263 anyup_pbar, pbar_update = None, None 264 if upsampler is not None: 265 if is_tiled: 266 n_blocks = Blocking( 267 [0, 0], list(features.attrs["shape"])[-2:], list(features.attrs["tile_shape"]) 268 ).number_of_blocks 269 else: 270 n_blocks = 1 271 anyup_pbar = util._progress_bar(total=n_blocks * depth, desc="Upsampling with AnyUp", disable=not verbose) 272 pbar_update = anyup_pbar.update 273 slice_disable = (not verbose) or (upsampler is not None) 274 275 if is_3d: 276 image_hw = (image_shape[1], image_shape[2]) 277 planes = [] 278 for z in util._progress_bar(range(depth), total=depth, disable=slice_disable, desc="Compute pixel features"): 279 if is_tiled: 280 plane, grid = _compute_tiled_feature_image( 281 features, image_hw, max_grid_size, z=z, image=image, upsampler=upsampler, pbar_update=pbar_update 282 ) 283 else: 284 embeds = np.asarray(features[z]).squeeze() 285 grid, _ = _grid_shape(image_hw, grid_size) 286 plane = _block_to_grid( 287 embeds, image_hw, grid, image_region=None if image is None else image[z], 288 upsampler=upsampler, pbar_update=pbar_update, 289 ) 290 planes.append(plane) 291 feature_image = np.stack(planes) 292 grid_shape = (depth,) + grid 293 else: 294 image_hw = (image_shape[0], image_shape[1]) 295 if is_tiled: 296 feature_image, grid = _compute_tiled_feature_image( 297 features, image_hw, max_grid_size, image=image, upsampler=upsampler, pbar_update=pbar_update 298 ) 299 else: 300 embeds = np.asarray(features).squeeze() 301 grid, _ = _grid_shape(image_hw, grid_size) 302 feature_image = _block_to_grid( 303 embeds, image_hw, grid, image_region=image, upsampler=upsampler, pbar_update=pbar_update, 304 ) 305 grid_shape = grid 306 307 if anyup_pbar is not None: 308 anyup_pbar.close() 309 310 features = feature_image.reshape(-1, feature_image.shape[-1]) 311 if classical_features is not None: 312 classical = compute_classical_pixel_features(image, grid_shape, classical_features) 313 features = np.concatenate([features, classical], axis=1) 314 return features, grid_shape
Compute per-pixel features from SAM embeddings for pixel classification.
Each spatial location of the SAM embedding becomes a feature vector. The features are computed on a downsampled in-plane grid (preserving the image aspect ratio) to keep them tractable, and the grid prediction is later projected back to the full image resolution.
Arguments:
- image_embeddings: The precomputed image embeddings.
- image_shape: The spatial shape of the image, (H, W) for 2d or (Z, H, W) for 3d.
- grid_size: In-plane grid size (longest side) for non-tiled images.
- max_grid_size: In-plane grid size (longest side) for tiled images.
- image: The original image, required when
upsamplerorclassical_featuresis given. - upsampler: An optional AnyUp model (see
get_anyup_upsampler). When given, the embedding is upsampled with AnyUp using the image instead of plain interpolation. - verbose: Whether to print a progressbar for the computation.
- classical_features: The classical filter features to append to the embedding features, a subset
of
classical_features.PIXEL_FEATURES. By default no classical features are used.
Returns:
The per-pixel features, of shape (N, C) flattened over the grid in row-major order. The grid shape, (gh, gw) for 2d or (Z, gh, gw) for 3d.
317def accumulate_pixel_labels(annotation: np.ndarray, grid_shape: Tuple[int, ...]) -> np.ndarray: 318 """Resize a full-resolution annotation onto the feature grid and flatten it. 319 320 Args: 321 annotation: The pixel annotations (scribbles), of shape (H, W) or (Z, H, W). 322 grid_shape: The feature grid shape returned by `compute_pixel_features`. 323 324 Returns: 325 The labels flattened over the grid, aligned row-wise with the features. 326 """ 327 def resize_plane(plane, target_hw): 328 # A grid cell takes the class that most of its annotated pixels have. A nearest-neighbour resize 329 # samples one pixel per cell, so it loses most thin scribbles. 330 grid_h, grid_w = target_hw 331 out = np.zeros(target_hw, dtype=annotation.dtype) 332 ys, xs = np.nonzero(plane) 333 if len(ys) == 0: 334 return out 335 cells = (ys * grid_h // plane.shape[0]) * grid_w + xs * grid_w // plane.shape[1] 336 values = plane[ys, xs].astype("int64") 337 n_classes = int(values.max()) + 1 338 counts = np.bincount(cells * n_classes + values, minlength=grid_h * grid_w * n_classes) 339 counts = counts.reshape(grid_h * grid_w, n_classes) 340 annotated = counts.sum(axis=1) > 0 341 out.reshape(-1)[annotated] = counts[annotated].argmax(axis=1) 342 return out 343 344 if len(grid_shape) == 2: 345 return resize_plane(annotation, grid_shape).reshape(-1) 346 347 depth, grid_h, grid_w = grid_shape 348 labels = np.empty((depth, grid_h, grid_w), dtype=annotation.dtype) 349 for z in range(depth): 350 labels[z] = resize_plane(annotation[z], (grid_h, grid_w)) 351 return labels.reshape(-1)
Resize a full-resolution annotation onto the feature grid and flatten it.
Arguments:
- annotation: The pixel annotations (scribbles), of shape (H, W) or (Z, H, W).
- grid_shape: The feature grid shape returned by
compute_pixel_features.
Returns:
The labels flattened over the grid, aligned row-wise with the features.
354def project_prediction_to_image( 355 grid_prediction: np.ndarray, grid_shape: Tuple[int, ...], image_shape: Tuple[int, ...] 356) -> np.ndarray: 357 """Project a per-grid-pixel prediction back to the full image resolution. 358 359 Args: 360 grid_prediction: The flat prediction over the grid (one entry per grid pixel). 361 grid_shape: The feature grid shape returned by `compute_pixel_features`. 362 image_shape: The full image spatial shape, (H, W) or (Z, H, W). 363 364 Returns: 365 The pixel level prediction at the image resolution, a semantic segmentation. 366 """ 367 grid = np.asarray(grid_prediction).reshape(grid_shape) 368 369 def resize_plane(plane, target_hw): 370 return resize(plane, target_hw, order=0, anti_aliasing=False, preserve_range=True).astype(grid.dtype) 371 372 if len(grid_shape) == 2: 373 return resize_plane(grid, image_shape) 374 375 prediction = np.empty(image_shape, dtype=grid.dtype) 376 for z in range(image_shape[0]): 377 prediction[z] = resize_plane(grid[z], image_shape[1:]) 378 return prediction
Project a per-grid-pixel prediction back to the full image resolution.
Arguments:
- grid_prediction: The flat prediction over the grid (one entry per grid pixel).
- grid_shape: The feature grid shape returned by
compute_pixel_features. - image_shape: The full image spatial shape, (H, W) or (Z, H, W).
Returns:
The pixel level prediction at the image resolution, a semantic segmentation.
381def train_pixel_classifier( 382 features: np.ndarray, 383 labels: np.ndarray, 384 previous_features: Optional[np.ndarray] = None, 385 previous_labels: Optional[np.ndarray] = None, 386 n_estimators: int = 200, 387 max_depth: int = 10, 388 n_jobs: Optional[int] = None, 389 n_components: Optional[int] = None, 390 random_state: Optional[int] = 0, 391 **rf_kwargs, 392): 393 """Train a random forest on per-pixel features and labels. 394 395 Pixels with label 0 are treated as unlabeled and excluded from training. This is the 396 shared training core used by both the interactive annotator and the batch training 397 function `run_training_with_pixel_classifier`. 398 399 Args: 400 features: The per-pixel features, of shape (N, C). 401 labels: The per-pixel labels, of shape (N,). Label 0 is treated as unlabeled. 402 previous_features: Features accumulated from previously annotated images, to train on jointly. 403 previous_labels: Labels matching `previous_features`. 404 n_estimators: The number of trees in the random forest. 405 max_depth: The maximum depth of each tree. 406 n_jobs: The number of parallel jobs for training. By default uses all available cores. 407 n_components: If given and smaller than the feature dimension, reduce the features to this 408 many PCA components before training. If `None`, `0` or `>=` the feature dimension, all 409 features are used. The fitted PCA is part of the returned model, so prediction transforms 410 the features automatically. 411 random_state: Seed for the random forest (and PCA) so training is reproducible. Pass `None` 412 to leave it unseeded, in which case predictions vary slightly between runs. 413 rf_kwargs: Additional keyword arguments for the `RandomForestClassifier`. 414 415 Returns: 416 The trained classifier. A `RandomForestClassifier`, or a `Pipeline` of PCA and the random 417 forest when `n_components` triggers dimensionality reduction. 418 """ 419 assert len(features) == len(labels) 420 valid = labels != 0 421 X, y = features[valid], labels[valid] 422 423 if previous_features is not None: 424 assert previous_labels is not None and len(previous_features) == len(previous_labels) 425 X = np.concatenate([previous_features, X], axis=0) 426 y = np.concatenate([previous_labels, y], axis=0) 427 428 rf = RandomForestClassifier( 429 n_estimators=n_estimators, max_depth=max_depth, 430 n_jobs=cpu_count() if n_jobs is None else n_jobs, random_state=random_state, **rf_kwargs, 431 ) 432 433 # Optionally reduce the features to the top-n PCA components. We clamp n_components to the 434 # number of features and samples. If it covers all features, we skip PCA and use the plain RF. 435 n_features = X.shape[1] 436 k = min(int(n_components), n_features, len(X)) if n_components else 0 437 if 0 < k < n_features: 438 model = Pipeline([("pca", PCA(n_components=k, random_state=random_state)), ("rf", rf)]) 439 else: 440 model = rf 441 442 model.fit(X, y) 443 return model
Train a random forest on per-pixel features and labels.
Pixels with label 0 are treated as unlabeled and excluded from training. This is the
shared training core used by both the interactive annotator and the batch training
function run_training_with_pixel_classifier.
Arguments:
- features: The per-pixel features, of shape (N, C).
- labels: The per-pixel labels, of shape (N,). Label 0 is treated as unlabeled.
- previous_features: Features accumulated from previously annotated images, to train on jointly.
- previous_labels: Labels matching
previous_features. - n_estimators: The number of trees in the random forest.
- max_depth: The maximum depth of each tree.
- n_jobs: The number of parallel jobs for training. By default uses all available cores.
- n_components: If given and smaller than the feature dimension, reduce the features to this
many PCA components before training. If
None,0or>=the feature dimension, all features are used. The fitted PCA is part of the returned model, so prediction transforms the features automatically. - random_state: Seed for the random forest (and PCA) so training is reproducible. Pass
Noneto leave it unseeded, in which case predictions vary slightly between runs. - rf_kwargs: Additional keyword arguments for the
RandomForestClassifier.
Returns:
The trained classifier. A
RandomForestClassifier, or aPipelineof PCA and the random forest whenn_componentstriggers dimensionality reduction.
448def run_training_with_pixel_classifier( 449 images: Sequence[Union[str, os.PathLike, np.ndarray]], 450 annotations: Sequence[Union[str, os.PathLike, np.ndarray]], 451 predictor, 452 rf_path: Union[str, os.PathLike], 453 image_key: Optional[str] = None, 454 annotation_key: Optional[str] = None, 455 ndim: Optional[int] = None, 456 n_estimators: int = 200, 457 max_depth: int = 10, 458 n_jobs: Optional[int] = None, 459 n_components: Optional[int] = None, 460 random_state: Optional[int] = 0, 461 upsampler=None, 462 classical_features: Optional[Sequence[str]] = None, 463 model_type: Optional[str] = None, 464 **rf_kwargs, 465): 466 """Train a pixel classifier on a series of images and (sparse) annotations. 467 468 Object features are computed from the SAM embeddings for each image, the annotations 469 are mapped onto the corresponding feature grid, and a random forest is trained on all 470 annotated pixels (pixels with label 0 are treated as unlabeled and ignored). 471 472 Args: 473 images: The images, either given as a list of numpy arrays or filepaths. 474 annotations: The pixel annotations (scribbles), either as numpy arrays or filepaths. 475 Pixels with value 0 are treated as unlabeled. Must match the order of `images`. 476 predictor: The Segment Anything predictor used to compute the embeddings. 477 rf_path: The filepath where the trained random forest will be saved. 478 image_key: The key for the image data, for filepath inputs (e.g. an internal dataset path). 479 annotation_key: The key for the annotation data, for filepath inputs. 480 ndim: The dimensionality of the data. If not given will be derived from the data. 481 n_estimators: The number of trees in the random forest. 482 max_depth: The maximum depth of each tree. 483 n_jobs: The number of parallel jobs for training. By default uses all available cores. 484 n_components: If given, reduce the features to this many PCA components before training. 485 If `None`, `0` or `>=` the feature dimension, all embedding channels are used. 486 random_state: Seed for the random forest (and PCA) so training is reproducible. Pass `None` 487 to leave it unseeded, in which case predictions vary slightly between runs. 488 upsampler: An optional AnyUp model (see `get_anyup_upsampler`) to upsample the embeddings 489 with the image as guidance instead of plain interpolation. 490 classical_features: The classical filter features to append to the embedding features, a subset 491 of `classical_features.PIXEL_FEATURES`. By default no classical features are used. 492 model_type: The model family of `predictor`, used to pick the matching embedding function 493 (SAM1 / SAM2 / VFM). If not given, the SAM1 embedding function is used. 494 rf_kwargs: Additional keyword arguments for the `RandomForestClassifier`. 495 496 Returns: 497 The trained classifier. 498 """ 499 if len(images) != len(annotations): 500 raise ValueError( 501 f"Expect the same number of images and annotations, got {len(images)}, {len(annotations)}." 502 ) 503 504 compute_embeddings = util.get_embedding_function(model_type) if model_type is not None \ 505 else precompute_image_embeddings 506 all_features, all_labels = [], [] 507 for image, annotation in tqdm( 508 zip(images, annotations), total=len(images), desc="Compute features for pixel classifier training" 509 ): 510 if isinstance(image, (str, os.PathLike)): 511 image = util.load_image_data(image, key=image_key) 512 if isinstance(annotation, (str, os.PathLike)): 513 annotation = util.load_image_data(annotation, key=annotation_key) 514 515 # Prepared in the same way as in the annotator, so the features match those of the GUI. 516 image, this_ndim, _ = util.prepare_annotation_image(image, ndim=ndim) 517 image_shape = image.shape[:this_ndim] 518 annotation = util.match_image_shape(annotation, image_shape) 519 embeddings = compute_embeddings(predictor, image, verbose=False, ndim=this_ndim) 520 use_image = upsampler is not None or classical_features is not None 521 features, grid_shape = compute_pixel_features( 522 embeddings, image_shape, image=image if use_image else None, 523 upsampler=upsampler, verbose=False, classical_features=classical_features, 524 ) 525 labels = accumulate_pixel_labels(annotation, grid_shape) 526 527 valid = labels != 0 528 if valid.any(): 529 all_features.append(features[valid]) 530 all_labels.append(labels[valid]) 531 532 if not all_features: 533 raise ValueError("None of the provided annotations contain labeled pixels.") 534 535 features = np.concatenate(all_features, axis=0) 536 labels = np.concatenate(all_labels, axis=0) 537 538 rf = train_pixel_classifier( 539 features, labels, n_estimators=n_estimators, max_depth=max_depth, n_jobs=n_jobs, 540 n_components=n_components, random_state=random_state, **rf_kwargs, 541 ) 542 543 dump(rf, rf_path) 544 return rf
Train a pixel classifier on a series of images and (sparse) annotations.
Object features are computed from the SAM embeddings for each image, the annotations are mapped onto the corresponding feature grid, and a random forest is trained on all annotated pixels (pixels with label 0 are treated as unlabeled and ignored).
Arguments:
- images: The images, either given as a list of numpy arrays or filepaths.
- annotations: The pixel annotations (scribbles), either as numpy arrays or filepaths.
Pixels with value 0 are treated as unlabeled. Must match the order of
images. - predictor: The Segment Anything predictor used to compute the embeddings.
- rf_path: The filepath where the trained random forest will be saved.
- image_key: The key for the image data, for filepath inputs (e.g. an internal dataset path).
- annotation_key: The key for the annotation data, for filepath inputs.
- ndim: The dimensionality of the data. If not given will be derived from the data.
- n_estimators: The number of trees in the random forest.
- max_depth: The maximum depth of each tree.
- n_jobs: The number of parallel jobs for training. By default uses all available cores.
- n_components: If given, reduce the features to this many PCA components before training.
If
None,0or>=the feature dimension, all embedding channels are used. - random_state: Seed for the random forest (and PCA) so training is reproducible. Pass
Noneto leave it unseeded, in which case predictions vary slightly between runs. - upsampler: An optional AnyUp model (see
get_anyup_upsampler) to upsample the embeddings with the image as guidance instead of plain interpolation. - classical_features: The classical filter features to append to the embedding features, a subset
of
classical_features.PIXEL_FEATURES. By default no classical features are used. - model_type: The model family of
predictor, used to pick the matching embedding function (SAM1 / SAM2 / VFM). If not given, the SAM1 embedding function is used. - rf_kwargs: Additional keyword arguments for the
RandomForestClassifier.
Returns:
The trained classifier.
551def run_prediction_with_pixel_classifier( 552 images: Sequence[Union[str, os.PathLike, np.ndarray]], 553 predictor, 554 rf_path: Union[str, os.PathLike], 555 image_key: Optional[str] = None, 556 ndim: Optional[int] = None, 557 upsampler=None, 558 model_type: Optional[str] = None, 559 classical_features: Optional[Sequence[str]] = None, 560) -> List[np.ndarray]: 561 """Run prediction with a pretrained pixel classifier on a series of images. 562 563 Args: 564 images: The images, either given as a list of numpy arrays or filepaths. 565 predictor: The Segment Anything predictor used to compute the embeddings. 566 rf_path: The filepath to the trained random forest. 567 image_key: The key for the image data, for filepath inputs (e.g. an internal dataset path). 568 ndim: The dimensionality of the data. If not given will be derived from the data. 569 upsampler: An optional AnyUp model (see `get_anyup_upsampler`) to upsample the embeddings 570 with the image as guidance instead of plain interpolation. Use the same setting that 571 the classifier was trained with. 572 model_type: The model family of `predictor`, used to pick the matching embedding function 573 (SAM1 / SAM2 / VFM). If not given, the SAM1 embedding function is used. 574 classical_features: The classical filter features to append to the embedding features. 575 Use the same features that the classifier was trained with. 576 577 Returns: 578 The pixel level predictions. 579 """ 580 # Stored as {'rf': ..., 'model_spec': ...} by the GUI. Older or backend files are a bare classifier. 581 obj = load(rf_path) 582 rf = obj["rf"] if isinstance(obj, dict) and "rf" in obj else obj 583 compute_embeddings = util.get_embedding_function(model_type) if model_type is not None \ 584 else precompute_image_embeddings 585 predictions = [] 586 for image in tqdm(images, total=len(images), desc="Run prediction with pixel classifier"): 587 if isinstance(image, (str, os.PathLike)): 588 image = util.load_image_data(image, key=image_key) 589 # Prepared in the same way as in the annotator, so the features match those of the GUI. 590 image, this_ndim, _ = util.prepare_annotation_image(image, ndim=ndim) 591 image_shape = image.shape[:this_ndim] 592 embeddings = compute_embeddings(predictor, image, verbose=False, ndim=this_ndim) 593 use_image = upsampler is not None or classical_features is not None 594 features, grid_shape = compute_pixel_features( 595 embeddings, image_shape, image=image if use_image else None, 596 upsampler=upsampler, verbose=False, classical_features=classical_features, 597 ) 598 prediction = rf.predict(features) 599 predictions.append(project_prediction_to_image(prediction, grid_shape, image_shape)) 600 return predictions
Run prediction with a pretrained pixel classifier on a series of images.
Arguments:
- images: The images, either given as a list of numpy arrays or filepaths.
- predictor: The Segment Anything predictor used to compute the embeddings.
- rf_path: The filepath to the trained random forest.
- image_key: The key for the image data, for filepath inputs (e.g. an internal dataset path).
- ndim: The dimensionality of the data. If not given will be derived from the data.
- upsampler: An optional AnyUp model (see
get_anyup_upsampler) to upsample the embeddings with the image as guidance instead of plain interpolation. Use the same setting that the classifier was trained with. - model_type: The model family of
predictor, used to pick the matching embedding function (SAM1 / SAM2 / VFM). If not given, the SAM1 embedding function is used. - classical_features: The classical filter features to append to the embedding features. Use the same features that the classifier was trained with.
Returns:
The pixel level predictions.