micro_sam.v2.bioimageio.predictor_adaptor
The micro-sam2 model for the BioImage.IO model format.
BioImage.IO tools build this module, load the exported weights into it and call it.
1"""The micro-sam2 model for the BioImage.IO model format. 2 3BioImage.IO tools build this module, load the exported weights into it and call it. 4""" 5from typing import Optional, Tuple 6 7import numpy as np 8 9import torch 10from torch import nn 11 12 13class SAM2PredictorAdaptor(nn.Module): 14 """A micro-sam2 model that does interactive and automatic instance segmentation. 15 16 The module segments one object per prompt when you give box, point or mask prompts. 17 It does automatic instance segmentation (AIS) when you give no prompts and the weights hold 18 a UniSAM2 decoder. The module needs the 'micro_sam' and 'sam2' packages. 19 20 Args: 21 model_type: The SAM2 backbone, one of 'hvit_t', 'hvit_s', 'hvit_b' or 'hvit_l'. 22 """ 23 def __init__(self, model_type: str) -> None: 24 super().__init__() 25 from micro_sam.v2.util import CFG_PATHS, _build_sam2_backbone 26 27 self.model_type = model_type 28 # The weights come from 'load_state_dict', so the base weights are not loaded. 29 self.sam2 = _build_sam2_backbone(CFG_PATHS[model_type], None, "cpu", "images") 30 self.decoder = None 31 self._predictor = None 32 self._segmenter = None 33 self._cached_image = None 34 35 def load_state_dict(self, state, strict: bool = True, **kwargs): 36 """Load the weights of the SAM2 model and, if the state has one, of the UniSAM2 decoder. 37 38 Args: 39 state: The SAM2 weights under 'model_state' and the decoder weights under 'decoder_state'. 40 The state can also hold only the SAM2 weights. 41 strict: Whether the keys must match the model exactly. 42 kwargs: Other arguments for `torch.nn.Module.load_state_dict`. 43 44 Returns: 45 The missing and unexpected keys of the SAM2 model. 46 """ 47 model_state = state.get("model_state", state) 48 result = self.sam2.load_state_dict(model_state, strict=strict, **kwargs) 49 50 decoder_state = state.get("decoder_state") 51 if decoder_state is None: 52 self.decoder = None 53 else: 54 from micro_sam.v2.models.util import UniSAM2, joint_unetr_state 55 output_channels, initial_features = decoder_state["out_conv.weight"].shape[:2] 56 # The decoder reuses the image encoder of the SAM2 model. 57 self.decoder = UniSAM2( 58 encoder=self.sam2.image_encoder, output_channels=int(output_channels), 59 initial_features=int(initial_features), device=self._device, 60 ) 61 self.decoder.load_state_dict(joint_unetr_state(state), strict=strict) 62 self.decoder.eval() 63 self.decoder.model_type = self.model_type 64 self._predictor = None 65 self._segmenter = None 66 self._cached_image = None 67 return result 68 69 @property 70 def _device(self) -> torch.device: 71 return next(self.sam2.parameters()).device 72 73 def _get_predictor(self): 74 from micro_sam.v2.util import get_sam2_image_predictor 75 if self._predictor is None or self._predictor.device != self._device: 76 self.sam2.model_type = self.model_type 77 self.sam2.model_name = self.model_type 78 self.sam2._hash = None 79 self._predictor = get_sam2_image_predictor(self.sam2) 80 self._cached_image = None 81 return self._predictor 82 83 def _set_image(self, image: np.ndarray) -> None: 84 """Compute the image embeddings, but only if the image changed since the last call.""" 85 if self._cached_image is not None and np.array_equal(self._cached_image, image): 86 return 87 from micro_sam.v2.normalization import to_image 88 from micro_sam.v2.util import encode_image 89 encode_image(self._get_predictor(), to_image(image)) 90 self._cached_image = image.copy() 91 92 def _automatic_instance_segmentation(self, image: np.ndarray) -> Tuple[torch.Tensor, torch.Tensor]: 93 """Segment all objects with the decoder and return one binary mask per object.""" 94 if self.decoder is None: 95 raise ValueError( 96 "These weights have no decoder for automatic instance segmentation, because the model " 97 "was trained for interactive segmentation only. Give box, point or mask prompts." 98 ) 99 from micro_sam.v2.automatic_segmentation import automatic_instance_segmentation 100 from micro_sam.v2.instance_segmentation import get_instance_segmentation_generator 101 102 predictor = self._get_predictor() 103 if self._segmenter is None: 104 self._segmenter = get_instance_segmentation_generator( 105 model=self.sam2, decoder=self.decoder, segmentation_mode="ais", device=self._device, 106 ) 107 segmentation = automatic_instance_segmentation( 108 predictor, self._segmenter, image, ndim=2, verbose=False, device=self._device, 109 ) 110 111 seg_ids = np.unique(segmentation) 112 seg_ids = seg_ids[seg_ids != 0] 113 if len(seg_ids) == 0: 114 masks = np.zeros((1, 0, 1) + segmentation.shape, dtype="uint8") 115 else: 116 masks = np.stack([segmentation == seg_id for seg_id in seg_ids])[None, :, None].astype("uint8") 117 # AIS does not predict a mask quality, so all scores are 1. 118 scores = np.ones((1, masks.shape[1], 1), dtype="float32") 119 return torch.from_numpy(masks), torch.from_numpy(scores) 120 121 @torch.no_grad() 122 def forward( 123 self, 124 image: torch.Tensor, 125 box_prompts: Optional[torch.Tensor] = None, 126 point_prompts: Optional[torch.Tensor] = None, 127 point_labels: Optional[torch.Tensor] = None, 128 mask_prompts: Optional[torch.Tensor] = None, 129 ) -> Tuple[torch.Tensor, torch.Tensor]: 130 """Segment objects in an image, with prompts or automatically. 131 132 All prompts of one object are in the same position of the object axis. Each prompt type that you 133 give must have the same number of objects. 134 135 Args: 136 image: The image, with shape 1 x C x H x W and 1 or 3 channels. The module normalizes the intensities. 137 box_prompts: The boxes, with shape 1 x OBJECTS x 4, in the order x_min, y_min, x_max, y_max. 138 point_prompts: The point coordinates, with shape 1 x OBJECTS x POINTS x 2, in the order x, y. 139 point_labels: The point labels, with shape 1 x OBJECTS x POINTS: 1 is positive, 0 is negative. 140 mask_prompts: The mask logits, with shape 1 x OBJECTS x 1 x 256 x 256. 141 142 Returns: 143 The masks, with shape 1 x OBJECTS x 1 x H x W. 144 The predicted mask quality scores, with shape 1 x OBJECTS x 1. 145 """ 146 if image.shape[0] != 1: 147 raise ValueError(f"The batch size must be 1, got {image.shape[0]}.") 148 if image.shape[1] not in (1, 3): 149 raise ValueError(f"The image must have 1 or 3 channels, got {image.shape[1]}.") 150 if (point_prompts is None) != (point_labels is None): 151 raise ValueError("Give 'point_prompts' and 'point_labels' together.") 152 153 # The micro-sam2 functions expect a channel-last numpy image. 154 image_np = image[0].permute(1, 2, 0).float().cpu().numpy() 155 if image_np.shape[-1] == 1: 156 image_np = image_np[..., 0] 157 158 if box_prompts is None and point_prompts is None and mask_prompts is None: 159 return self._automatic_instance_segmentation(image_np) 160 161 self._set_image(image_np) 162 kwargs = {} 163 if box_prompts is not None: 164 kwargs["box"] = box_prompts[0].float().cpu().numpy() 165 if point_prompts is not None: 166 kwargs["point_coords"] = point_prompts[0].float().cpu().numpy() 167 kwargs["point_labels"] = point_labels[0].cpu().numpy() 168 if mask_prompts is not None: 169 kwargs["mask_input"] = mask_prompts[0].float().cpu().numpy() 170 171 n_objects = {len(value) for value in kwargs.values()} 172 if len(n_objects) != 1: 173 raise ValueError(f"All prompts must have the same number of objects, got {sorted(n_objects)}.") 174 175 from micro_sam.v2.util import autocast 176 predictor = self._get_predictor() 177 with autocast(predictor.device): 178 masks, scores, _ = predictor.predict(multimask_output=False, **kwargs) 179 180 # SAM2 removes the object axis for one object. 181 masks = np.asarray(masks).reshape((-1,) + image_np.shape[:2]) 182 scores = np.asarray(scores, dtype="float32").reshape(-1) 183 masks = torch.from_numpy(masks[None, :, None].astype("uint8")) 184 scores = torch.from_numpy(scores[None, :, None]) 185 return masks, scores
14class SAM2PredictorAdaptor(nn.Module): 15 """A micro-sam2 model that does interactive and automatic instance segmentation. 16 17 The module segments one object per prompt when you give box, point or mask prompts. 18 It does automatic instance segmentation (AIS) when you give no prompts and the weights hold 19 a UniSAM2 decoder. The module needs the 'micro_sam' and 'sam2' packages. 20 21 Args: 22 model_type: The SAM2 backbone, one of 'hvit_t', 'hvit_s', 'hvit_b' or 'hvit_l'. 23 """ 24 def __init__(self, model_type: str) -> None: 25 super().__init__() 26 from micro_sam.v2.util import CFG_PATHS, _build_sam2_backbone 27 28 self.model_type = model_type 29 # The weights come from 'load_state_dict', so the base weights are not loaded. 30 self.sam2 = _build_sam2_backbone(CFG_PATHS[model_type], None, "cpu", "images") 31 self.decoder = None 32 self._predictor = None 33 self._segmenter = None 34 self._cached_image = None 35 36 def load_state_dict(self, state, strict: bool = True, **kwargs): 37 """Load the weights of the SAM2 model and, if the state has one, of the UniSAM2 decoder. 38 39 Args: 40 state: The SAM2 weights under 'model_state' and the decoder weights under 'decoder_state'. 41 The state can also hold only the SAM2 weights. 42 strict: Whether the keys must match the model exactly. 43 kwargs: Other arguments for `torch.nn.Module.load_state_dict`. 44 45 Returns: 46 The missing and unexpected keys of the SAM2 model. 47 """ 48 model_state = state.get("model_state", state) 49 result = self.sam2.load_state_dict(model_state, strict=strict, **kwargs) 50 51 decoder_state = state.get("decoder_state") 52 if decoder_state is None: 53 self.decoder = None 54 else: 55 from micro_sam.v2.models.util import UniSAM2, joint_unetr_state 56 output_channels, initial_features = decoder_state["out_conv.weight"].shape[:2] 57 # The decoder reuses the image encoder of the SAM2 model. 58 self.decoder = UniSAM2( 59 encoder=self.sam2.image_encoder, output_channels=int(output_channels), 60 initial_features=int(initial_features), device=self._device, 61 ) 62 self.decoder.load_state_dict(joint_unetr_state(state), strict=strict) 63 self.decoder.eval() 64 self.decoder.model_type = self.model_type 65 self._predictor = None 66 self._segmenter = None 67 self._cached_image = None 68 return result 69 70 @property 71 def _device(self) -> torch.device: 72 return next(self.sam2.parameters()).device 73 74 def _get_predictor(self): 75 from micro_sam.v2.util import get_sam2_image_predictor 76 if self._predictor is None or self._predictor.device != self._device: 77 self.sam2.model_type = self.model_type 78 self.sam2.model_name = self.model_type 79 self.sam2._hash = None 80 self._predictor = get_sam2_image_predictor(self.sam2) 81 self._cached_image = None 82 return self._predictor 83 84 def _set_image(self, image: np.ndarray) -> None: 85 """Compute the image embeddings, but only if the image changed since the last call.""" 86 if self._cached_image is not None and np.array_equal(self._cached_image, image): 87 return 88 from micro_sam.v2.normalization import to_image 89 from micro_sam.v2.util import encode_image 90 encode_image(self._get_predictor(), to_image(image)) 91 self._cached_image = image.copy() 92 93 def _automatic_instance_segmentation(self, image: np.ndarray) -> Tuple[torch.Tensor, torch.Tensor]: 94 """Segment all objects with the decoder and return one binary mask per object.""" 95 if self.decoder is None: 96 raise ValueError( 97 "These weights have no decoder for automatic instance segmentation, because the model " 98 "was trained for interactive segmentation only. Give box, point or mask prompts." 99 ) 100 from micro_sam.v2.automatic_segmentation import automatic_instance_segmentation 101 from micro_sam.v2.instance_segmentation import get_instance_segmentation_generator 102 103 predictor = self._get_predictor() 104 if self._segmenter is None: 105 self._segmenter = get_instance_segmentation_generator( 106 model=self.sam2, decoder=self.decoder, segmentation_mode="ais", device=self._device, 107 ) 108 segmentation = automatic_instance_segmentation( 109 predictor, self._segmenter, image, ndim=2, verbose=False, device=self._device, 110 ) 111 112 seg_ids = np.unique(segmentation) 113 seg_ids = seg_ids[seg_ids != 0] 114 if len(seg_ids) == 0: 115 masks = np.zeros((1, 0, 1) + segmentation.shape, dtype="uint8") 116 else: 117 masks = np.stack([segmentation == seg_id for seg_id in seg_ids])[None, :, None].astype("uint8") 118 # AIS does not predict a mask quality, so all scores are 1. 119 scores = np.ones((1, masks.shape[1], 1), dtype="float32") 120 return torch.from_numpy(masks), torch.from_numpy(scores) 121 122 @torch.no_grad() 123 def forward( 124 self, 125 image: torch.Tensor, 126 box_prompts: Optional[torch.Tensor] = None, 127 point_prompts: Optional[torch.Tensor] = None, 128 point_labels: Optional[torch.Tensor] = None, 129 mask_prompts: Optional[torch.Tensor] = None, 130 ) -> Tuple[torch.Tensor, torch.Tensor]: 131 """Segment objects in an image, with prompts or automatically. 132 133 All prompts of one object are in the same position of the object axis. Each prompt type that you 134 give must have the same number of objects. 135 136 Args: 137 image: The image, with shape 1 x C x H x W and 1 or 3 channels. The module normalizes the intensities. 138 box_prompts: The boxes, with shape 1 x OBJECTS x 4, in the order x_min, y_min, x_max, y_max. 139 point_prompts: The point coordinates, with shape 1 x OBJECTS x POINTS x 2, in the order x, y. 140 point_labels: The point labels, with shape 1 x OBJECTS x POINTS: 1 is positive, 0 is negative. 141 mask_prompts: The mask logits, with shape 1 x OBJECTS x 1 x 256 x 256. 142 143 Returns: 144 The masks, with shape 1 x OBJECTS x 1 x H x W. 145 The predicted mask quality scores, with shape 1 x OBJECTS x 1. 146 """ 147 if image.shape[0] != 1: 148 raise ValueError(f"The batch size must be 1, got {image.shape[0]}.") 149 if image.shape[1] not in (1, 3): 150 raise ValueError(f"The image must have 1 or 3 channels, got {image.shape[1]}.") 151 if (point_prompts is None) != (point_labels is None): 152 raise ValueError("Give 'point_prompts' and 'point_labels' together.") 153 154 # The micro-sam2 functions expect a channel-last numpy image. 155 image_np = image[0].permute(1, 2, 0).float().cpu().numpy() 156 if image_np.shape[-1] == 1: 157 image_np = image_np[..., 0] 158 159 if box_prompts is None and point_prompts is None and mask_prompts is None: 160 return self._automatic_instance_segmentation(image_np) 161 162 self._set_image(image_np) 163 kwargs = {} 164 if box_prompts is not None: 165 kwargs["box"] = box_prompts[0].float().cpu().numpy() 166 if point_prompts is not None: 167 kwargs["point_coords"] = point_prompts[0].float().cpu().numpy() 168 kwargs["point_labels"] = point_labels[0].cpu().numpy() 169 if mask_prompts is not None: 170 kwargs["mask_input"] = mask_prompts[0].float().cpu().numpy() 171 172 n_objects = {len(value) for value in kwargs.values()} 173 if len(n_objects) != 1: 174 raise ValueError(f"All prompts must have the same number of objects, got {sorted(n_objects)}.") 175 176 from micro_sam.v2.util import autocast 177 predictor = self._get_predictor() 178 with autocast(predictor.device): 179 masks, scores, _ = predictor.predict(multimask_output=False, **kwargs) 180 181 # SAM2 removes the object axis for one object. 182 masks = np.asarray(masks).reshape((-1,) + image_np.shape[:2]) 183 scores = np.asarray(scores, dtype="float32").reshape(-1) 184 masks = torch.from_numpy(masks[None, :, None].astype("uint8")) 185 scores = torch.from_numpy(scores[None, :, None]) 186 return masks, scores
A micro-sam2 model that does interactive and automatic instance segmentation.
The module segments one object per prompt when you give box, point or mask prompts. It does automatic instance segmentation (AIS) when you give no prompts and the weights hold a UniSAM2 decoder. The module needs the 'micro_sam' and 'sam2' packages.
Arguments:
- model_type: The SAM2 backbone, one of 'hvit_t', 'hvit_s', 'hvit_b' or 'hvit_l'.
24 def __init__(self, model_type: str) -> None: 25 super().__init__() 26 from micro_sam.v2.util import CFG_PATHS, _build_sam2_backbone 27 28 self.model_type = model_type 29 # The weights come from 'load_state_dict', so the base weights are not loaded. 30 self.sam2 = _build_sam2_backbone(CFG_PATHS[model_type], None, "cpu", "images") 31 self.decoder = None 32 self._predictor = None 33 self._segmenter = None 34 self._cached_image = None
Initialize internal Module state, shared by both nn.Module and ScriptModule.
36 def load_state_dict(self, state, strict: bool = True, **kwargs): 37 """Load the weights of the SAM2 model and, if the state has one, of the UniSAM2 decoder. 38 39 Args: 40 state: The SAM2 weights under 'model_state' and the decoder weights under 'decoder_state'. 41 The state can also hold only the SAM2 weights. 42 strict: Whether the keys must match the model exactly. 43 kwargs: Other arguments for `torch.nn.Module.load_state_dict`. 44 45 Returns: 46 The missing and unexpected keys of the SAM2 model. 47 """ 48 model_state = state.get("model_state", state) 49 result = self.sam2.load_state_dict(model_state, strict=strict, **kwargs) 50 51 decoder_state = state.get("decoder_state") 52 if decoder_state is None: 53 self.decoder = None 54 else: 55 from micro_sam.v2.models.util import UniSAM2, joint_unetr_state 56 output_channels, initial_features = decoder_state["out_conv.weight"].shape[:2] 57 # The decoder reuses the image encoder of the SAM2 model. 58 self.decoder = UniSAM2( 59 encoder=self.sam2.image_encoder, output_channels=int(output_channels), 60 initial_features=int(initial_features), device=self._device, 61 ) 62 self.decoder.load_state_dict(joint_unetr_state(state), strict=strict) 63 self.decoder.eval() 64 self.decoder.model_type = self.model_type 65 self._predictor = None 66 self._segmenter = None 67 self._cached_image = None 68 return result
Load the weights of the SAM2 model and, if the state has one, of the UniSAM2 decoder.
Arguments:
- state: The SAM2 weights under 'model_state' and the decoder weights under 'decoder_state'. The state can also hold only the SAM2 weights.
- strict: Whether the keys must match the model exactly.
- kwargs: Other arguments for
torch.nn.Module.load_state_dict.
Returns:
The missing and unexpected keys of the SAM2 model.
122 @torch.no_grad() 123 def forward( 124 self, 125 image: torch.Tensor, 126 box_prompts: Optional[torch.Tensor] = None, 127 point_prompts: Optional[torch.Tensor] = None, 128 point_labels: Optional[torch.Tensor] = None, 129 mask_prompts: Optional[torch.Tensor] = None, 130 ) -> Tuple[torch.Tensor, torch.Tensor]: 131 """Segment objects in an image, with prompts or automatically. 132 133 All prompts of one object are in the same position of the object axis. Each prompt type that you 134 give must have the same number of objects. 135 136 Args: 137 image: The image, with shape 1 x C x H x W and 1 or 3 channels. The module normalizes the intensities. 138 box_prompts: The boxes, with shape 1 x OBJECTS x 4, in the order x_min, y_min, x_max, y_max. 139 point_prompts: The point coordinates, with shape 1 x OBJECTS x POINTS x 2, in the order x, y. 140 point_labels: The point labels, with shape 1 x OBJECTS x POINTS: 1 is positive, 0 is negative. 141 mask_prompts: The mask logits, with shape 1 x OBJECTS x 1 x 256 x 256. 142 143 Returns: 144 The masks, with shape 1 x OBJECTS x 1 x H x W. 145 The predicted mask quality scores, with shape 1 x OBJECTS x 1. 146 """ 147 if image.shape[0] != 1: 148 raise ValueError(f"The batch size must be 1, got {image.shape[0]}.") 149 if image.shape[1] not in (1, 3): 150 raise ValueError(f"The image must have 1 or 3 channels, got {image.shape[1]}.") 151 if (point_prompts is None) != (point_labels is None): 152 raise ValueError("Give 'point_prompts' and 'point_labels' together.") 153 154 # The micro-sam2 functions expect a channel-last numpy image. 155 image_np = image[0].permute(1, 2, 0).float().cpu().numpy() 156 if image_np.shape[-1] == 1: 157 image_np = image_np[..., 0] 158 159 if box_prompts is None and point_prompts is None and mask_prompts is None: 160 return self._automatic_instance_segmentation(image_np) 161 162 self._set_image(image_np) 163 kwargs = {} 164 if box_prompts is not None: 165 kwargs["box"] = box_prompts[0].float().cpu().numpy() 166 if point_prompts is not None: 167 kwargs["point_coords"] = point_prompts[0].float().cpu().numpy() 168 kwargs["point_labels"] = point_labels[0].cpu().numpy() 169 if mask_prompts is not None: 170 kwargs["mask_input"] = mask_prompts[0].float().cpu().numpy() 171 172 n_objects = {len(value) for value in kwargs.values()} 173 if len(n_objects) != 1: 174 raise ValueError(f"All prompts must have the same number of objects, got {sorted(n_objects)}.") 175 176 from micro_sam.v2.util import autocast 177 predictor = self._get_predictor() 178 with autocast(predictor.device): 179 masks, scores, _ = predictor.predict(multimask_output=False, **kwargs) 180 181 # SAM2 removes the object axis for one object. 182 masks = np.asarray(masks).reshape((-1,) + image_np.shape[:2]) 183 scores = np.asarray(scores, dtype="float32").reshape(-1) 184 masks = torch.from_numpy(masks[None, :, None].astype("uint8")) 185 scores = torch.from_numpy(scores[None, :, None]) 186 return masks, scores
Segment objects in an image, with prompts or automatically.
All prompts of one object are in the same position of the object axis. Each prompt type that you give must have the same number of objects.
Arguments:
- image: The image, with shape 1 x C x H x W and 1 or 3 channels. The module normalizes the intensities.
- box_prompts: The boxes, with shape 1 x OBJECTS x 4, in the order x_min, y_min, x_max, y_max.
- point_prompts: The point coordinates, with shape 1 x OBJECTS x POINTS x 2, in the order x, y.
- point_labels: The point labels, with shape 1 x OBJECTS x POINTS: 1 is positive, 0 is negative.
- mask_prompts: The mask logits, with shape 1 x OBJECTS x 1 x 256 x 256.
Returns:
The masks, with shape 1 x OBJECTS x 1 x H x W. The predicted mask quality scores, with shape 1 x OBJECTS x 1.