micro_sam.object_classification
1import os 2from joblib import load 3from typing import List, Optional, Sequence, Tuple, Union 4 5import numpy as np 6import pandas as pd 7 8from skimage.transform import resize 9from skimage.measure import regionprops_table 10 11try: 12 from napari.utils import progress as tqdm 13except ImportError: 14 from tqdm import tqdm 15 16import torch 17 18from bioimage_cpp.transformation import resample 19from bioimage_cpp.utils import Blocking, take_dict 20 21from . import util 22from .v1.util import precompute_image_embeddings 23from .classical_features import compute_classical_object_features 24 25 26def _anyup_object_resize(embeds_chw, image_region, target_hw, upsampler): 27 # Upsample a (C, h, w) embedding to (target_h, target_w, C) with AnyUp, using the image region 28 # as guidance. The encoders pad the image to a square, so we square-pad the image here to match 29 # how the segmentation is padded. 30 import torch.nn.functional as F 31 from .pixel_classification import _to_anyup_image 32 33 # AnyUp's internal convolutions need at least 2 px per spatial dim. Fall back to plain 34 # interpolation for degenerate regions. 35 if min(embeds_chw.shape[-2:]) < 2 or min(target_hw) < 2 or min(image_region.shape[:2]) < 2: 36 return resize( 37 embeds_chw.transpose(1, 2, 0), tuple(target_hw) + (embeds_chw.shape[0],), preserve_range=True 38 ).astype("float32") 39 40 device = next(upsampler.parameters()).device 41 image_tensor = _to_anyup_image(image_region, device) # (1, 3, H, W) 42 h, w = image_tensor.shape[-2:] 43 image_tensor = F.pad(image_tensor, (0, max(h - w, 0), 0, max(w - h, 0))) 44 feature_tensor = torch.from_numpy(np.ascontiguousarray(embeds_chw)).to(device).float().unsqueeze(0) 45 from .pixel_classification import ANYUP_Q_CHUNK_SIZE 46 with torch.no_grad(): 47 upsampled = upsampler( 48 image_tensor, feature_tensor, output_size=tuple(target_hw), q_chunk_size=ANYUP_Q_CHUNK_SIZE 49 ) 50 return upsampled[0].permute(1, 2, 0).cpu().numpy().astype("float32") 51 52 53def _compute_object_features_impl( 54 embeddings, segmentation, resize_embedding_shape, image_region=None, upsampler=None, pbar_update=None, 55): 56 # Keep the raw (C, h, w) embedding for AnyUp, which needs the channel axis first. 57 embeddings_chw = embeddings 58 59 # Bring the segmentation to a square shape matching the (square) embedding. The encoders pad the 60 # image to a square, so we zero-pad the segmentation to match. 61 shape = segmentation.shape 62 if shape[0] == shape[1]: 63 segmentation_rescaled = segmentation 64 elif shape[0] > shape[1]: 65 segmentation_rescaled = np.pad(segmentation, ((0, 0), (0, shape[0] - shape[1]))) 66 else: 67 segmentation_rescaled = np.pad(segmentation, ((0, shape[1] - shape[0]), (0, 0))) 68 assert segmentation_rescaled.shape[0] == segmentation_rescaled.shape[1] 69 shape = segmentation_rescaled.shape 70 71 # Resize the segmentation and embeddings to be of the same size. 72 73 # We first resize the embedding, to an intermediate shape (passed as parameter). 74 # The motivation for this is to avoid loosing smaller segmented objects when resizing the segmentation 75 # to the original embedding shape. On the other hand, we avoid resizing the embeddings to the full segmentation 76 # shape for efficiency reasons. 77 resize_hw = tuple(min(rsh, sh) for rsh, sh in zip(resize_embedding_shape, shape)) 78 if upsampler is not None: 79 # AnyUp upsamples the embedding using the image region instead of plain interpolation. 80 embeddings = _anyup_object_resize(embeddings_chw, image_region, resize_hw, upsampler) 81 elif all(t >= s for t, s in zip(resize_hw, embeddings_chw.shape[1:])): 82 # Upsampling (the usual case): torch is much faster than skimage and matches it, except at the edge. 83 embeddings = torch.nn.functional.interpolate( 84 torch.from_numpy(np.ascontiguousarray(embeddings_chw, dtype="float32"))[None], size=resize_hw, 85 mode="bilinear", align_corners=False, 86 )[0].permute(1, 2, 0).numpy().astype(embeddings_chw.dtype, copy=False) # put the channel axis last 87 else: 88 # Downsampling (tiny images or corner tiles): bioimage-cpp matches the skimage anti-aliasing, torch does not. 89 scale = [s / t for s, t in zip(embeddings_chw.shape[1:], resize_hw)] 90 matrix = np.array([ 91 [1.0, 0.0, 0.0, 0.0], [0.0, scale[0], 0.0, (scale[0] - 1) / 2], [0.0, 0.0, scale[1], (scale[1] - 1) / 2] 92 ]) 93 bounding_box = (slice(0, embeddings_chw.shape[0]),) + tuple(slice(0, t) for t in resize_hw) 94 embeddings = resample( 95 np.ascontiguousarray(embeddings_chw, dtype="float32"), matrix, bounding_box=bounding_box 96 ).transpose(1, 2, 0).astype(embeddings_chw.dtype, copy=False) # put the channel axis last 97 98 segmentation_rescaled = resize( 99 segmentation_rescaled, embeddings.shape[:2], order=0, anti_aliasing=False, preserve_range=True 100 ).astype(segmentation.dtype) 101 102 # Which features do we use? 103 all_features = regionprops_table( 104 segmentation_rescaled, intensity_image=embeddings, properties=("label", "area", "mean_intensity"), 105 ) 106 seg_ids = all_features["label"] 107 features = pd.DataFrame(all_features)[ 108 ["area"] + [f"mean_intensity-{i}" for i in range(embeddings.shape[-1])] 109 ].values 110 111 if pbar_update is not None: 112 pbar_update(1) 113 return seg_ids, features 114 115 116def _create_seg_and_embed_generator(segmentation, image_embeddings, is_tiled, is_3d, image=None): 117 assert is_tiled or is_3d 118 119 if is_tiled: 120 tile_embeds = image_embeddings["features"] 121 tile_shape, halo = tile_embeds.attrs["tile_shape"], tile_embeds.attrs["halo"] 122 # A 3d volume stores (z, y, x), but the tiling is in-plane. 123 tiling = Blocking([0, 0], list(tile_embeds.attrs["shape"])[-2:], tile_shape) 124 length = tiling.number_of_blocks * segmentation.shape[0] if is_3d else tiling.number_of_blocks 125 else: 126 tiling = None 127 length = segmentation.shape[0] 128 129 # The generators yield (segmentation, embeddings, image_region) per slice / tile. The image 130 # region is None unless an image is given (only needed for AnyUp upsampling). 131 if is_3d and is_tiled: # 3d data with tiling 132 def generator(): 133 for z in range(segmentation.shape[0]): 134 seg_z = segmentation[z] 135 image_z = None if image is None else image[z] 136 for block_id in range(tiling.number_of_blocks): 137 block = tiling.get_block_with_halo(block_id, halo) 138 139 # Get the embeddings and segmentation for this block and slice. 140 embeds = tile_embeds[str(block_id)][z].squeeze() 141 142 bb = tuple(slice(beg, end) for beg, end in zip(block.outer_block.begin, block.outer_block.end)) 143 seg = seg_z[bb] 144 image_region = None if image_z is None else image_z[bb] 145 146 yield seg, embeds, image_region 147 148 elif is_3d: # 3d data no tiling 149 def generator(): 150 for z in range(length): 151 seg = segmentation[z] 152 embeds = image_embeddings["features"][z].squeeze() 153 image_region = None if image is None else image[z] 154 yield seg, embeds, image_region 155 156 else: # 2d data with tiling 157 def generator(): 158 for block_id in range(length): 159 block = tiling.get_block_with_halo(block_id, halo) 160 161 # Get the embeddings and segmentation for this block. 162 embeds = tile_embeds[str(block_id)][:].squeeze() 163 bb = tuple(slice(beg, end) for beg, end in zip(block.outer_block.begin, block.outer_block.end)) 164 seg = segmentation[bb] 165 image_region = None if image is None else image[bb] 166 167 yield seg, embeds, image_region 168 169 return generator, length 170 171 172def compute_object_features( 173 image_embeddings: util.ImageEmbeddings, 174 segmentation: np.ndarray, 175 resize_embedding_shape: Tuple[int, int] = (256, 256), 176 verbose: bool = True, 177 image: Optional[np.ndarray] = None, 178 upsampler=None, 179 classical_features: Optional[Sequence[str]] = None, 180) -> Tuple[np.ndarray, np.ndarray]: 181 """Compute object features based on SAM embeddings. 182 183 Args: 184 image_embeddings: The precomputed image embeddings. 185 segmentation: The segmentation for which to compute the features. 186 resize_embedding_shape: Shape for intermediate resizing of the embeddings. 187 verbose: Whether to print a progressbar for the computation. 188 image: The original image, required when `upsampler` or `classical_features` is given. 189 upsampler: An optional AnyUp model (see `pixel_classification.get_anyup_upsampler`). When 190 given, the embedding is upsampled with AnyUp using the image instead of plain interpolation. 191 classical_features: The classical object features to append to the embedding features, a subset 192 of `classical_features.OBJECT_FEATURES`. By default no classical features are used. 193 194 Returns: 195 The segmentation ids. 196 The object features. The first column is the object area in pixels. The next columns are the mean 197 of each embedding channel. The classical features follow, if you pass them. 198 """ 199 if upsampler is not None and image is None: 200 raise ValueError("An 'image' is required when an AnyUp 'upsampler' is given.") 201 if classical_features is not None and image is None: 202 raise ValueError("An 'image' is required when 'classical_features' are given.") 203 204 seg_ids, features = _compute_embedding_object_features( 205 image_embeddings, segmentation, resize_embedding_shape, verbose, 206 image=image if upsampler is not None else None, upsampler=upsampler, 207 ) 208 if classical_features is not None: 209 classical = compute_classical_object_features(image, segmentation, seg_ids, classical_features) 210 features = np.concatenate([features, classical], axis=1) 211 return seg_ids, features 212 213 214def _compute_embedding_object_features( 215 image_embeddings, segmentation, resize_embedding_shape, verbose, image=None, upsampler=None 216): 217 is_tiled = image_embeddings["input_size"] is None 218 is_3d = segmentation.ndim == 3 219 220 # The area feature is the pixel count. The resized areas only weight the merge of the means. 221 all_ids, sizes = np.unique(segmentation, return_counts=True) 222 223 # If we have simple embeddings, i.e. 2d without tiling, then we can directly compute the features. 224 if not is_tiled and not is_3d: 225 embeddings = image_embeddings["features"].squeeze() 226 # AnyUp is the slow part, so show a progress bar (which also drives napari's activity dots) 227 # for the single upsampling call. 228 anyup_pbar = util._progress_bar( 229 total=1, desc="Upsampling with AnyUp", disable=(not verbose) or (upsampler is None) 230 ) 231 seg_ids, features = _compute_object_features_impl( 232 embeddings, segmentation, resize_embedding_shape, image_region=image, upsampler=upsampler, 233 pbar_update=anyup_pbar.update if upsampler is not None else None, 234 ) 235 anyup_pbar.close() 236 # Small objects can vanish in the resized segmentation. Then 'seg_ids' is a subset of 'all_ids'. 237 areas = sizes[np.searchsorted(all_ids, seg_ids)] 238 return seg_ids, np.concatenate([areas[:, None], features[:, 1:]], axis=1) 239 240 # Otherwise, we compute the features by iterating over slices and/or tiles, 241 # compute the features for each slice / tile and accumulate them. 242 243 # First, we compute the segmentation ids and initialize the required data structures. 244 seg_ids = all_ids.tolist() 245 if seg_ids[0] == 0: 246 seg_ids = seg_ids[1:] 247 visited = {seg_id: False for seg_id in seg_ids} 248 249 # Then, we create a generator for iterating over the slices and / or tile. 250 # This generator returns the respective segmentation and embeddings. 251 seg_embed_generator, n_gen = _create_seg_and_embed_generator( 252 segmentation, image_embeddings, is_tiled=is_tiled, is_3d=is_3d, image=image 253 ) 254 255 # Feature vector = object area + per-channel embedding mean, so the width follows the embedding 256 # channel count (256 for SAM1/SAM2, larger for e.g. DINO encoders). 257 n_channels = int(next(seg_embed_generator())[1].shape[0]) 258 features = np.zeros((len(seg_ids), n_channels + 1), dtype="float32") 259 260 # With AnyUp, label the bar accordingly since the upsampling is the slow part. 261 desc = "Upsampling with AnyUp" if upsampler is not None else "Compute object features" 262 for seg, embeds, image_region in util._progress_bar( 263 seg_embed_generator(), total=n_gen, disable=not verbose, desc=desc 264 ): 265 # Compute this seg ids and features. 266 this_seg_ids, this_features = _compute_object_features_impl( 267 embeds, seg, resize_embedding_shape, image_region=image_region, upsampler=upsampler 268 ) 269 this_seg_ids = this_seg_ids.tolist() 270 271 # Find which of the seg ids are new (= processed for the first time). 272 # And the seg ids that were already visited. 273 new_idx = np.array([seg_ids.index(seg_id) for seg_id in this_seg_ids if not visited[seg_id]], dtype="int") 274 visited_idx = np.array([seg_ids.index(seg_id) for seg_id in this_seg_ids if visited[seg_id]], dtype="int") 275 276 # Get the corresponding feature indices. 277 this_new_idx = np.array( 278 [this_seg_ids.index(seg_id) for seg_id in this_seg_ids if not visited[seg_id]], dtype="int" 279 ) 280 this_visited_idx = np.array( 281 [this_seg_ids.index(seg_id) for seg_id in this_seg_ids if visited[seg_id]], dtype="int" 282 ) 283 284 # New features can be written directly. 285 features[new_idx] = this_features[this_new_idx] 286 287 # Features that were already visited can be merged. 288 if len(visited_idx) > 0: 289 # Get the sizes, which are needed for computing the mean. 290 prev_size = features[visited_idx, 0:1] 291 this_size = this_features[this_visited_idx, 0:1] 292 293 # The sizes themselve are merged by addition. 294 features[visited_idx, 0] += this_features[this_visited_idx, 0] 295 296 # Mean values are merged via weighted sum. 297 features[visited_idx, 1:] = ( 298 prev_size * features[visited_idx, 1:] + this_size * this_features[this_visited_idx, 1:] 299 ) / (prev_size + this_size) 300 301 # Set all seg ids from this block to visited. 302 visited.update({seg_id: True for seg_id in this_seg_ids}) 303 304 features[:, 0] = sizes[all_ids != 0] 305 return np.array(seg_ids), features 306 307 308def project_prediction_to_segmentation( 309 segmentation: np.ndarray, 310 object_prediction: np.ndarray, 311 seg_ids: np.ndarray 312) -> np.ndarray: 313 """Project object level prediction to the corresponding segmentation to obtain a pixel level prediction. 314 315 Args: 316 segmentation: The segmentation from which the object prediction is derived. 317 object_prediction: The object prediction. 318 seg_ids: The segmentation ids matching the object prediction. 319 320 Returns: 321 The pixel level object prediction, corresponding to a semantic segmentation. 322 """ 323 assert len(object_prediction) == len(seg_ids) 324 325 # bioimage_cpp.take_dict only accepts these integer label dtypes. Napari label layers can use 326 # smaller dtypes such as uint8, so cast only for the relabeling call. 327 if segmentation.dtype not in (np.uint32, np.uint64, np.int32, np.int64): 328 if segmentation.dtype == bool or np.issubdtype(segmentation.dtype, np.unsignedinteger): 329 segmentation_for_relabeling = segmentation.astype("uint32", copy=False) 330 elif np.issubdtype(segmentation.dtype, np.signedinteger): 331 segmentation_for_relabeling = segmentation.astype("int32", copy=False) 332 else: 333 raise TypeError(f"The segmentation must have an integer dtype, got dtype={segmentation.dtype}.") 334 else: 335 segmentation_for_relabeling = segmentation 336 337 prediction = {seg_id: class_pred for seg_id, class_pred in zip(seg_ids, object_prediction)} 338 # Find missing segmentation ids. This will include the background id, but may include other ids of small objects. 339 # Such objects may get removed in the resizing operations. 340 missing_ids = np.setdiff1d(np.unique(segmentation), seg_ids) 341 prediction.update({missing_id: 0 for missing_id in missing_ids}) 342 return take_dict(prediction, segmentation_for_relabeling) 343 344 345# TODO handle images / segmentations as file paths 346# TODO think about the function signature, specially how exactly we pass model and optional embedding path. 347# TODO halo and tile shape 348# TODO add heuristic for ndim 349def run_prediction_with_object_classifier( 350 images: Sequence[Union[str, os.PathLike, np.ndarray]], 351 segmentations: Sequence[Union[str, os.PathLike, np.ndarray]], 352 predictor, 353 rf_path: Union[str, os.PathLike], 354 image_key: Optional[str] = None, 355 segmentation_key: Optional[str] = None, 356 project_prediction: bool = True, 357 ndim: Optional[int] = None, 358 upsampler=None, 359 model_type: Optional[str] = None, 360 classical_features: Optional[Sequence[str]] = None, 361) -> List[np.ndarray]: 362 """Run prediction with a pretrained object classifier on a series of images. 363 364 Args: 365 images: The images, either given as a list of numpy array or filepaths. 366 segmentations: The segmentations, either given as a list of numpy array or filepaths. 367 predictor: 368 rf_path: 369 image_key: 370 segmentation_key: 371 project_prediction: 372 ndim: 373 upsampler: An optional AnyUp model (see `pixel_classification.get_anyup_upsampler`) to 374 upsample the embeddings with the image as guidance instead of plain interpolation. 375 Use the same setting that the classifier was trained with. 376 model_type: The model family of `predictor`, used to pick the matching embedding function. 377 classical_features: The classical object features to append to the embedding features. 378 Use the same features that the classifier was trained with. 379 380 Returns: 381 The predictions. 382 """ 383 assert len(images) == len(segmentations) 384 # Stored as {'rf': ..., 'model_spec': ...}; older files are a bare classifier. 385 obj = load(rf_path) 386 rf = obj["rf"] if isinstance(obj, dict) and "rf" in obj else obj 387 compute_embeddings = util.get_embedding_function(model_type) if model_type is not None \ 388 else precompute_image_embeddings 389 predictions = [] 390 for image, segmentation in tqdm( 391 zip(images, segmentations), total=len(images), desc="Run prediction with object classifier" 392 ): 393 if isinstance(image, (str, os.PathLike)): 394 image = util.load_image_data(image, key=image_key) 395 if isinstance(segmentation, (str, os.PathLike)): 396 segmentation = util.load_image_data(segmentation, key=segmentation_key) 397 # Prepared in the same way as in the annotator, so the features match those of the GUI. 398 image, this_ndim, _ = util.prepare_annotation_image(image, ndim=ndim) 399 segmentation = util.match_image_shape(segmentation, image.shape[:this_ndim]) 400 embeddings = compute_embeddings(predictor, image, verbose=False, ndim=this_ndim) 401 use_image = upsampler is not None or classical_features is not None 402 seg_ids, features = compute_object_features( 403 embeddings, segmentation, verbose=False, image=image if use_image else None, 404 upsampler=upsampler, classical_features=classical_features, 405 ) 406 prediction = rf.predict(features) 407 if project_prediction: 408 prediction = project_prediction_to_segmentation(segmentation, prediction, seg_ids) 409 predictions.append(prediction) 410 return predictions
def
compute_object_features( image_embeddings: Dict[str, Any], segmentation: numpy.ndarray, resize_embedding_shape: Tuple[int, int] = (256, 256), verbose: bool = True, image: Optional[numpy.ndarray] = None, upsampler=None, classical_features: Optional[Sequence[str]] = None) -> Tuple[numpy.ndarray, numpy.ndarray]:
173def compute_object_features( 174 image_embeddings: util.ImageEmbeddings, 175 segmentation: np.ndarray, 176 resize_embedding_shape: Tuple[int, int] = (256, 256), 177 verbose: bool = True, 178 image: Optional[np.ndarray] = None, 179 upsampler=None, 180 classical_features: Optional[Sequence[str]] = None, 181) -> Tuple[np.ndarray, np.ndarray]: 182 """Compute object features based on SAM embeddings. 183 184 Args: 185 image_embeddings: The precomputed image embeddings. 186 segmentation: The segmentation for which to compute the features. 187 resize_embedding_shape: Shape for intermediate resizing of the embeddings. 188 verbose: Whether to print a progressbar for the computation. 189 image: The original image, required when `upsampler` or `classical_features` is given. 190 upsampler: An optional AnyUp model (see `pixel_classification.get_anyup_upsampler`). When 191 given, the embedding is upsampled with AnyUp using the image instead of plain interpolation. 192 classical_features: The classical object features to append to the embedding features, a subset 193 of `classical_features.OBJECT_FEATURES`. By default no classical features are used. 194 195 Returns: 196 The segmentation ids. 197 The object features. The first column is the object area in pixels. The next columns are the mean 198 of each embedding channel. The classical features follow, if you pass them. 199 """ 200 if upsampler is not None and image is None: 201 raise ValueError("An 'image' is required when an AnyUp 'upsampler' is given.") 202 if classical_features is not None and image is None: 203 raise ValueError("An 'image' is required when 'classical_features' are given.") 204 205 seg_ids, features = _compute_embedding_object_features( 206 image_embeddings, segmentation, resize_embedding_shape, verbose, 207 image=image if upsampler is not None else None, upsampler=upsampler, 208 ) 209 if classical_features is not None: 210 classical = compute_classical_object_features(image, segmentation, seg_ids, classical_features) 211 features = np.concatenate([features, classical], axis=1) 212 return seg_ids, features
Compute object features based on SAM embeddings.
Arguments:
- image_embeddings: The precomputed image embeddings.
- segmentation: The segmentation for which to compute the features.
- resize_embedding_shape: Shape for intermediate resizing of the embeddings.
- verbose: Whether to print a progressbar for the computation.
- image: The original image, required when
upsamplerorclassical_featuresis given. - upsampler: An optional AnyUp model (see
pixel_classification.get_anyup_upsampler). When given, the embedding is upsampled with AnyUp using the image instead of plain interpolation. - classical_features: The classical object features to append to the embedding features, a subset
of
classical_features.OBJECT_FEATURES. By default no classical features are used.
Returns:
The segmentation ids. The object features. The first column is the object area in pixels. The next columns are the mean of each embedding channel. The classical features follow, if you pass them.
def
project_prediction_to_segmentation( segmentation: numpy.ndarray, object_prediction: numpy.ndarray, seg_ids: numpy.ndarray) -> numpy.ndarray:
309def project_prediction_to_segmentation( 310 segmentation: np.ndarray, 311 object_prediction: np.ndarray, 312 seg_ids: np.ndarray 313) -> np.ndarray: 314 """Project object level prediction to the corresponding segmentation to obtain a pixel level prediction. 315 316 Args: 317 segmentation: The segmentation from which the object prediction is derived. 318 object_prediction: The object prediction. 319 seg_ids: The segmentation ids matching the object prediction. 320 321 Returns: 322 The pixel level object prediction, corresponding to a semantic segmentation. 323 """ 324 assert len(object_prediction) == len(seg_ids) 325 326 # bioimage_cpp.take_dict only accepts these integer label dtypes. Napari label layers can use 327 # smaller dtypes such as uint8, so cast only for the relabeling call. 328 if segmentation.dtype not in (np.uint32, np.uint64, np.int32, np.int64): 329 if segmentation.dtype == bool or np.issubdtype(segmentation.dtype, np.unsignedinteger): 330 segmentation_for_relabeling = segmentation.astype("uint32", copy=False) 331 elif np.issubdtype(segmentation.dtype, np.signedinteger): 332 segmentation_for_relabeling = segmentation.astype("int32", copy=False) 333 else: 334 raise TypeError(f"The segmentation must have an integer dtype, got dtype={segmentation.dtype}.") 335 else: 336 segmentation_for_relabeling = segmentation 337 338 prediction = {seg_id: class_pred for seg_id, class_pred in zip(seg_ids, object_prediction)} 339 # Find missing segmentation ids. This will include the background id, but may include other ids of small objects. 340 # Such objects may get removed in the resizing operations. 341 missing_ids = np.setdiff1d(np.unique(segmentation), seg_ids) 342 prediction.update({missing_id: 0 for missing_id in missing_ids}) 343 return take_dict(prediction, segmentation_for_relabeling)
Project object level prediction to the corresponding segmentation to obtain a pixel level prediction.
Arguments:
- segmentation: The segmentation from which the object prediction is derived.
- object_prediction: The object prediction.
- seg_ids: The segmentation ids matching the object prediction.
Returns:
The pixel level object prediction, corresponding to a semantic segmentation.
def
run_prediction_with_object_classifier( images: Sequence[Union[str, os.PathLike, numpy.ndarray]], segmentations: Sequence[Union[str, os.PathLike, numpy.ndarray]], predictor, rf_path: Union[str, os.PathLike], image_key: Optional[str] = None, segmentation_key: Optional[str] = None, project_prediction: bool = True, ndim: Optional[int] = None, upsampler=None, model_type: Optional[str] = None, classical_features: Optional[Sequence[str]] = None) -> List[numpy.ndarray]:
350def run_prediction_with_object_classifier( 351 images: Sequence[Union[str, os.PathLike, np.ndarray]], 352 segmentations: Sequence[Union[str, os.PathLike, np.ndarray]], 353 predictor, 354 rf_path: Union[str, os.PathLike], 355 image_key: Optional[str] = None, 356 segmentation_key: Optional[str] = None, 357 project_prediction: bool = True, 358 ndim: Optional[int] = None, 359 upsampler=None, 360 model_type: Optional[str] = None, 361 classical_features: Optional[Sequence[str]] = None, 362) -> List[np.ndarray]: 363 """Run prediction with a pretrained object classifier on a series of images. 364 365 Args: 366 images: The images, either given as a list of numpy array or filepaths. 367 segmentations: The segmentations, either given as a list of numpy array or filepaths. 368 predictor: 369 rf_path: 370 image_key: 371 segmentation_key: 372 project_prediction: 373 ndim: 374 upsampler: An optional AnyUp model (see `pixel_classification.get_anyup_upsampler`) to 375 upsample the embeddings with the image as guidance instead of plain interpolation. 376 Use the same setting that the classifier was trained with. 377 model_type: The model family of `predictor`, used to pick the matching embedding function. 378 classical_features: The classical object features to append to the embedding features. 379 Use the same features that the classifier was trained with. 380 381 Returns: 382 The predictions. 383 """ 384 assert len(images) == len(segmentations) 385 # Stored as {'rf': ..., 'model_spec': ...}; older files are a bare classifier. 386 obj = load(rf_path) 387 rf = obj["rf"] if isinstance(obj, dict) and "rf" in obj else obj 388 compute_embeddings = util.get_embedding_function(model_type) if model_type is not None \ 389 else precompute_image_embeddings 390 predictions = [] 391 for image, segmentation in tqdm( 392 zip(images, segmentations), total=len(images), desc="Run prediction with object classifier" 393 ): 394 if isinstance(image, (str, os.PathLike)): 395 image = util.load_image_data(image, key=image_key) 396 if isinstance(segmentation, (str, os.PathLike)): 397 segmentation = util.load_image_data(segmentation, key=segmentation_key) 398 # Prepared in the same way as in the annotator, so the features match those of the GUI. 399 image, this_ndim, _ = util.prepare_annotation_image(image, ndim=ndim) 400 segmentation = util.match_image_shape(segmentation, image.shape[:this_ndim]) 401 embeddings = compute_embeddings(predictor, image, verbose=False, ndim=this_ndim) 402 use_image = upsampler is not None or classical_features is not None 403 seg_ids, features = compute_object_features( 404 embeddings, segmentation, verbose=False, image=image if use_image else None, 405 upsampler=upsampler, classical_features=classical_features, 406 ) 407 prediction = rf.predict(features) 408 if project_prediction: 409 prediction = project_prediction_to_segmentation(segmentation, prediction, seg_ids) 410 predictions.append(prediction) 411 return predictions
Run prediction with a pretrained object classifier on a series of images.
Arguments:
- images: The images, either given as a list of numpy array or filepaths.
- segmentations: The segmentations, either given as a list of numpy array or filepaths.
- predictor:
- rf_path:
- image_key:
- segmentation_key:
- project_prediction:
- ndim:
- upsampler: An optional AnyUp model (see
pixel_classification.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. - classical_features: The classical object features to append to the embedding features. Use the same features that the classifier was trained with.
Returns:
The predictions.