micro_sam.v2.transforms.resize

Shared resize-longest-side transforms for SAM2 training and inference.

  1"""Shared resize-longest-side transforms for SAM2 training and inference."""
  2
  3from typing import Iterable, Tuple
  4
  5import numpy as np
  6
  7import torch
  8import torch.nn.functional as F
  9
 10
 11def get_preprocess_shape(old_h: int, old_w: int, target_length: int) -> Tuple[int, int]:
 12    """Return the aspect-preserving shape whose longest side is ``target_length``."""
 13    scale = float(target_length) / max(old_h, old_w)
 14    return int(old_h * scale + 0.5), int(old_w * scale + 0.5)
 15
 16
 17def resize_longest_side_and_pad_tensor(
 18    x: torch.Tensor, target_length: int, mode: str = "bilinear", antialias: bool = True,
 19) -> Tuple[torch.Tensor, Tuple[int, int]]:
 20    """Resize trailing YX dimensions isotropically and zero-pad bottom/right.
 21
 22    Supports BCHW and BCZYX tensors. The Z dimension is never resized.
 23    Padding is applied in image space, before any caller-side normalization.
 24    """
 25    old_h, old_w = x.shape[-2:]
 26    new_h, new_w = get_preprocess_shape(old_h, old_w, target_length)
 27
 28    kwargs = {}
 29    if mode in ("linear", "bilinear", "bicubic", "trilinear"):
 30        kwargs["align_corners"] = False
 31    if mode == "bilinear":
 32        kwargs["antialias"] = antialias
 33
 34    if x.ndim == 4:
 35        x = F.interpolate(x, size=(new_h, new_w), mode=mode, **kwargs)
 36    elif x.ndim == 5:
 37        batch, channels, depth, _, _ = x.shape
 38        planes = x.permute(0, 2, 1, 3, 4).reshape(batch * depth, channels, old_h, old_w)
 39        planes = F.interpolate(planes, size=(new_h, new_w), mode=mode, **kwargs)
 40        x = planes.reshape(batch, depth, channels, new_h, new_w).permute(0, 2, 1, 3, 4)
 41    else:
 42        raise ValueError(f"Expected BCHW or BCZYX input, got shape {tuple(x.shape)}.")
 43
 44    return F.pad(x, (0, target_length - new_w, 0, target_length - new_h)), (new_h, new_w)
 45
 46
 47def resize_longest_side_and_pad_numpy(image: np.ndarray, target_length: int) -> Tuple[np.ndarray, Tuple[int, int]]:
 48    """Resize a channels-last image isotropically and zero-pad bottom/right."""
 49    from skimage.transform import resize
 50
 51    old_h, old_w = image.shape[:2]
 52    new_h, new_w = get_preprocess_shape(old_h, old_w, target_length)
 53    output_shape = (new_h, new_w) + image.shape[2:]
 54    image = resize(image, output_shape=output_shape, order=1, anti_aliasing=True, preserve_range=True)
 55    pad_width = ((0, target_length - new_h), (0, target_length - new_w)) + ((0, 0),) * (image.ndim - 2)
 56    return np.pad(image, pad_width), (new_h, new_w)
 57
 58
 59def resize_longest_side_and_pad_spatial_numpy(
 60    data: np.ndarray, target_length: int, is_label: bool = False,
 61) -> Tuple[np.ndarray, Tuple[int, int]]:
 62    """Resize trailing YX dimensions and zero-pad bottom/right."""
 63    from skimage.transform import resize
 64
 65    old_h, old_w = data.shape[-2:]
 66    new_h, new_w = get_preprocess_shape(old_h, old_w, target_length)
 67    kwargs = {"order": 0, "anti_aliasing": False} if is_label else {}
 68    output_shape = data.shape[:-2] + (new_h, new_w)
 69    data = resize(data, output_shape=output_shape, preserve_range=True, **kwargs).astype(data.dtype)
 70    pad_width = ((0, 0),) * (data.ndim - 2) + (
 71        (0, target_length - new_h), (0, target_length - new_w),
 72    )
 73    return np.pad(data, pad_width), (new_h, new_w)
 74
 75
 76class ResizeLongestSideAndPad(torch.nn.Module):
 77    """Resize a CHW tensor and pad it to a square."""
 78
 79    def __init__(self, resolution: int):
 80        super().__init__()
 81        self.resolution = resolution
 82
 83    def forward(self, image: torch.Tensor) -> torch.Tensor:
 84        batched = image.ndim == 4
 85        if not batched:
 86            image = image.unsqueeze(0)
 87        image = resize_longest_side_and_pad_tensor(image, self.resolution)[0]
 88        return image if batched else image[0]
 89
 90
 91def get_connected_components(mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
 92    """Label the 8-connected components of a binary mask and return the component area for each pixel.
 93
 94    Uses the compiled SAM2 extension for CUDA tensors if it is available. Otherwise, uses bioimage-cpp.
 95    The compiled extension is missing in pip installations and in CPU builds of SAM2.
 96
 97    Args:
 98        mask: The binary mask of shape (N, 1, H, W).
 99
100    Returns:
101        The component labels of shape (N, 1, H, W), 0 for the background.
102        The area of the component of each foreground pixel of shape (N, 1, H, W), 0 for the background.
103    """
104    if mask.is_cuda:
105        try:
106            from sam2 import _C
107            return _C.get_connected_componnets(mask.to(torch.uint8).contiguous())
108        except ImportError:
109            pass
110
111    from bioimage_cpp.segmentation import label
112
113    masks = mask.detach().cpu().numpy().astype(bool)
114    labels = np.zeros(masks.shape, dtype="int32")
115    areas = np.zeros(masks.shape, dtype="int32")
116    for i in range(masks.shape[0]):
117        labels[i, 0] = label(masks[i, 0], connectivity=2)
118        component_areas = np.bincount(labels[i, 0].ravel())
119        component_areas[0] = 0
120        areas[i, 0] = component_areas[labels[i, 0]]
121    return torch.from_numpy(labels).to(mask.device), torch.from_numpy(areas).to(mask.device)
122
123
124class ResizeLongestSideTransforms(torch.nn.Module):
125    """Drop-in replacement for ``SAM2Transforms`` using resize-longest + padding."""
126
127    def __init__(self, resolution, mask_threshold, max_hole_area=0.0, max_sprinkle_area=0.0):
128        super().__init__()
129        from torchvision.transforms import Normalize, ToTensor
130
131        self.resolution = resolution
132        self.mask_threshold = mask_threshold
133        self.max_hole_area = max_hole_area
134        self.max_sprinkle_area = max_sprinkle_area
135        self.mean = [0.485, 0.456, 0.406]
136        self.std = [0.229, 0.224, 0.225]
137        self.to_tensor = ToTensor()
138        self.transforms = torch.nn.Sequential(
139            ResizeLongestSideAndPad(resolution),
140            Normalize(self.mean, self.std),
141        )
142
143    def _transform_image(self, image):
144        return self.transforms(self.to_tensor(image))
145
146    def __call__(self, image):
147        return self._transform_image(image)
148
149    def forward_batch(self, image_list: Iterable):
150        return torch.stack([self._transform_image(image) for image in image_list], dim=0)
151
152    def transform_coords(self, coords: torch.Tensor, normalize=False, orig_hw=None) -> torch.Tensor:
153        coords = coords.clone()
154        if normalize:
155            if orig_hw is None:
156                raise ValueError("orig_hw is required when normalizing prompt coordinates.")
157            scale = float(self.resolution) / max(orig_hw)
158            coords[..., 0] *= scale
159            coords[..., 1] *= scale
160        else:
161            coords *= self.resolution
162        return coords
163
164    def transform_boxes(self, boxes: torch.Tensor, normalize=False, orig_hw=None) -> torch.Tensor:
165        return self.transform_coords(boxes.reshape(-1, 2, 2), normalize=normalize, orig_hw=orig_hw)
166
167    def postprocess_masks(self, masks: torch.Tensor, orig_hw) -> torch.Tensor:
168        """Upsample, remove bottom/right padding, and restore the original shape."""
169        masks = masks.float()
170        flat = masks.flatten(0, 1).unsqueeze(1)
171        if self.max_hole_area > 0:
172            labels, areas = get_connected_components(flat <= self.mask_threshold)
173            masks = torch.where(
174                ((labels > 0) & (areas <= self.max_hole_area)).reshape_as(masks),
175                self.mask_threshold + 10.0,
176                masks,
177            )
178        if self.max_sprinkle_area > 0:
179            labels, areas = get_connected_components(flat > self.mask_threshold)
180            masks = torch.where(
181                ((labels > 0) & (areas <= self.max_sprinkle_area)).reshape_as(masks),
182                self.mask_threshold - 10.0,
183                masks,
184            )
185
186        new_h, new_w = get_preprocess_shape(orig_hw[0], orig_hw[1], self.resolution)
187        masks = F.interpolate(
188            masks.float(), (self.resolution, self.resolution), mode="bilinear", align_corners=False,
189        )
190        masks = masks[..., :new_h, :new_w]
191        return F.interpolate(masks, orig_hw, mode="bilinear", align_corners=False)
def get_preprocess_shape(old_h: int, old_w: int, target_length: int) -> Tuple[int, int]:
12def get_preprocess_shape(old_h: int, old_w: int, target_length: int) -> Tuple[int, int]:
13    """Return the aspect-preserving shape whose longest side is ``target_length``."""
14    scale = float(target_length) / max(old_h, old_w)
15    return int(old_h * scale + 0.5), int(old_w * scale + 0.5)

Return the aspect-preserving shape whose longest side is target_length.

def resize_longest_side_and_pad_tensor( x: torch.Tensor, target_length: int, mode: str = 'bilinear', antialias: bool = True) -> Tuple[torch.Tensor, Tuple[int, int]]:
18def resize_longest_side_and_pad_tensor(
19    x: torch.Tensor, target_length: int, mode: str = "bilinear", antialias: bool = True,
20) -> Tuple[torch.Tensor, Tuple[int, int]]:
21    """Resize trailing YX dimensions isotropically and zero-pad bottom/right.
22
23    Supports BCHW and BCZYX tensors. The Z dimension is never resized.
24    Padding is applied in image space, before any caller-side normalization.
25    """
26    old_h, old_w = x.shape[-2:]
27    new_h, new_w = get_preprocess_shape(old_h, old_w, target_length)
28
29    kwargs = {}
30    if mode in ("linear", "bilinear", "bicubic", "trilinear"):
31        kwargs["align_corners"] = False
32    if mode == "bilinear":
33        kwargs["antialias"] = antialias
34
35    if x.ndim == 4:
36        x = F.interpolate(x, size=(new_h, new_w), mode=mode, **kwargs)
37    elif x.ndim == 5:
38        batch, channels, depth, _, _ = x.shape
39        planes = x.permute(0, 2, 1, 3, 4).reshape(batch * depth, channels, old_h, old_w)
40        planes = F.interpolate(planes, size=(new_h, new_w), mode=mode, **kwargs)
41        x = planes.reshape(batch, depth, channels, new_h, new_w).permute(0, 2, 1, 3, 4)
42    else:
43        raise ValueError(f"Expected BCHW or BCZYX input, got shape {tuple(x.shape)}.")
44
45    return F.pad(x, (0, target_length - new_w, 0, target_length - new_h)), (new_h, new_w)

Resize trailing YX dimensions isotropically and zero-pad bottom/right.

Supports BCHW and BCZYX tensors. The Z dimension is never resized. Padding is applied in image space, before any caller-side normalization.

def resize_longest_side_and_pad_numpy( image: numpy.ndarray, target_length: int) -> Tuple[numpy.ndarray, Tuple[int, int]]:
48def resize_longest_side_and_pad_numpy(image: np.ndarray, target_length: int) -> Tuple[np.ndarray, Tuple[int, int]]:
49    """Resize a channels-last image isotropically and zero-pad bottom/right."""
50    from skimage.transform import resize
51
52    old_h, old_w = image.shape[:2]
53    new_h, new_w = get_preprocess_shape(old_h, old_w, target_length)
54    output_shape = (new_h, new_w) + image.shape[2:]
55    image = resize(image, output_shape=output_shape, order=1, anti_aliasing=True, preserve_range=True)
56    pad_width = ((0, target_length - new_h), (0, target_length - new_w)) + ((0, 0),) * (image.ndim - 2)
57    return np.pad(image, pad_width), (new_h, new_w)

Resize a channels-last image isotropically and zero-pad bottom/right.

def resize_longest_side_and_pad_spatial_numpy( data: numpy.ndarray, target_length: int, is_label: bool = False) -> Tuple[numpy.ndarray, Tuple[int, int]]:
60def resize_longest_side_and_pad_spatial_numpy(
61    data: np.ndarray, target_length: int, is_label: bool = False,
62) -> Tuple[np.ndarray, Tuple[int, int]]:
63    """Resize trailing YX dimensions and zero-pad bottom/right."""
64    from skimage.transform import resize
65
66    old_h, old_w = data.shape[-2:]
67    new_h, new_w = get_preprocess_shape(old_h, old_w, target_length)
68    kwargs = {"order": 0, "anti_aliasing": False} if is_label else {}
69    output_shape = data.shape[:-2] + (new_h, new_w)
70    data = resize(data, output_shape=output_shape, preserve_range=True, **kwargs).astype(data.dtype)
71    pad_width = ((0, 0),) * (data.ndim - 2) + (
72        (0, target_length - new_h), (0, target_length - new_w),
73    )
74    return np.pad(data, pad_width), (new_h, new_w)

Resize trailing YX dimensions and zero-pad bottom/right.

class ResizeLongestSideAndPad(torch.nn.modules.module.Module):
77class ResizeLongestSideAndPad(torch.nn.Module):
78    """Resize a CHW tensor and pad it to a square."""
79
80    def __init__(self, resolution: int):
81        super().__init__()
82        self.resolution = resolution
83
84    def forward(self, image: torch.Tensor) -> torch.Tensor:
85        batched = image.ndim == 4
86        if not batched:
87            image = image.unsqueeze(0)
88        image = resize_longest_side_and_pad_tensor(image, self.resolution)[0]
89        return image if batched else image[0]

Resize a CHW tensor and pad it to a square.

ResizeLongestSideAndPad(resolution: int)
80    def __init__(self, resolution: int):
81        super().__init__()
82        self.resolution = resolution

Initialize internal Module state, shared by both nn.Module and ScriptModule.

resolution
def forward(self, image: torch.Tensor) -> torch.Tensor:
84    def forward(self, image: torch.Tensor) -> torch.Tensor:
85        batched = image.ndim == 4
86        if not batched:
87            image = image.unsqueeze(0)
88        image = resize_longest_side_and_pad_tensor(image, self.resolution)[0]
89        return image if batched else image[0]

Define the computation performed at every call.

Should be overridden by all subclasses.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

def get_connected_components(mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
 92def get_connected_components(mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
 93    """Label the 8-connected components of a binary mask and return the component area for each pixel.
 94
 95    Uses the compiled SAM2 extension for CUDA tensors if it is available. Otherwise, uses bioimage-cpp.
 96    The compiled extension is missing in pip installations and in CPU builds of SAM2.
 97
 98    Args:
 99        mask: The binary mask of shape (N, 1, H, W).
100
101    Returns:
102        The component labels of shape (N, 1, H, W), 0 for the background.
103        The area of the component of each foreground pixel of shape (N, 1, H, W), 0 for the background.
104    """
105    if mask.is_cuda:
106        try:
107            from sam2 import _C
108            return _C.get_connected_componnets(mask.to(torch.uint8).contiguous())
109        except ImportError:
110            pass
111
112    from bioimage_cpp.segmentation import label
113
114    masks = mask.detach().cpu().numpy().astype(bool)
115    labels = np.zeros(masks.shape, dtype="int32")
116    areas = np.zeros(masks.shape, dtype="int32")
117    for i in range(masks.shape[0]):
118        labels[i, 0] = label(masks[i, 0], connectivity=2)
119        component_areas = np.bincount(labels[i, 0].ravel())
120        component_areas[0] = 0
121        areas[i, 0] = component_areas[labels[i, 0]]
122    return torch.from_numpy(labels).to(mask.device), torch.from_numpy(areas).to(mask.device)

Label the 8-connected components of a binary mask and return the component area for each pixel.

Uses the compiled SAM2 extension for CUDA tensors if it is available. Otherwise, uses bioimage-cpp. The compiled extension is missing in pip installations and in CPU builds of SAM2.

Arguments:
  • mask: The binary mask of shape (N, 1, H, W).
Returns:

The component labels of shape (N, 1, H, W), 0 for the background. The area of the component of each foreground pixel of shape (N, 1, H, W), 0 for the background.

class ResizeLongestSideTransforms(torch.nn.modules.module.Module):
125class ResizeLongestSideTransforms(torch.nn.Module):
126    """Drop-in replacement for ``SAM2Transforms`` using resize-longest + padding."""
127
128    def __init__(self, resolution, mask_threshold, max_hole_area=0.0, max_sprinkle_area=0.0):
129        super().__init__()
130        from torchvision.transforms import Normalize, ToTensor
131
132        self.resolution = resolution
133        self.mask_threshold = mask_threshold
134        self.max_hole_area = max_hole_area
135        self.max_sprinkle_area = max_sprinkle_area
136        self.mean = [0.485, 0.456, 0.406]
137        self.std = [0.229, 0.224, 0.225]
138        self.to_tensor = ToTensor()
139        self.transforms = torch.nn.Sequential(
140            ResizeLongestSideAndPad(resolution),
141            Normalize(self.mean, self.std),
142        )
143
144    def _transform_image(self, image):
145        return self.transforms(self.to_tensor(image))
146
147    def __call__(self, image):
148        return self._transform_image(image)
149
150    def forward_batch(self, image_list: Iterable):
151        return torch.stack([self._transform_image(image) for image in image_list], dim=0)
152
153    def transform_coords(self, coords: torch.Tensor, normalize=False, orig_hw=None) -> torch.Tensor:
154        coords = coords.clone()
155        if normalize:
156            if orig_hw is None:
157                raise ValueError("orig_hw is required when normalizing prompt coordinates.")
158            scale = float(self.resolution) / max(orig_hw)
159            coords[..., 0] *= scale
160            coords[..., 1] *= scale
161        else:
162            coords *= self.resolution
163        return coords
164
165    def transform_boxes(self, boxes: torch.Tensor, normalize=False, orig_hw=None) -> torch.Tensor:
166        return self.transform_coords(boxes.reshape(-1, 2, 2), normalize=normalize, orig_hw=orig_hw)
167
168    def postprocess_masks(self, masks: torch.Tensor, orig_hw) -> torch.Tensor:
169        """Upsample, remove bottom/right padding, and restore the original shape."""
170        masks = masks.float()
171        flat = masks.flatten(0, 1).unsqueeze(1)
172        if self.max_hole_area > 0:
173            labels, areas = get_connected_components(flat <= self.mask_threshold)
174            masks = torch.where(
175                ((labels > 0) & (areas <= self.max_hole_area)).reshape_as(masks),
176                self.mask_threshold + 10.0,
177                masks,
178            )
179        if self.max_sprinkle_area > 0:
180            labels, areas = get_connected_components(flat > self.mask_threshold)
181            masks = torch.where(
182                ((labels > 0) & (areas <= self.max_sprinkle_area)).reshape_as(masks),
183                self.mask_threshold - 10.0,
184                masks,
185            )
186
187        new_h, new_w = get_preprocess_shape(orig_hw[0], orig_hw[1], self.resolution)
188        masks = F.interpolate(
189            masks.float(), (self.resolution, self.resolution), mode="bilinear", align_corners=False,
190        )
191        masks = masks[..., :new_h, :new_w]
192        return F.interpolate(masks, orig_hw, mode="bilinear", align_corners=False)

Drop-in replacement for SAM2Transforms using resize-longest + padding.

ResizeLongestSideTransforms(resolution, mask_threshold, max_hole_area=0.0, max_sprinkle_area=0.0)
128    def __init__(self, resolution, mask_threshold, max_hole_area=0.0, max_sprinkle_area=0.0):
129        super().__init__()
130        from torchvision.transforms import Normalize, ToTensor
131
132        self.resolution = resolution
133        self.mask_threshold = mask_threshold
134        self.max_hole_area = max_hole_area
135        self.max_sprinkle_area = max_sprinkle_area
136        self.mean = [0.485, 0.456, 0.406]
137        self.std = [0.229, 0.224, 0.225]
138        self.to_tensor = ToTensor()
139        self.transforms = torch.nn.Sequential(
140            ResizeLongestSideAndPad(resolution),
141            Normalize(self.mean, self.std),
142        )

Initialize internal Module state, shared by both nn.Module and ScriptModule.

resolution
mask_threshold
max_hole_area
max_sprinkle_area
mean
std
to_tensor
transforms
def forward_batch(self, image_list: Iterable):
150    def forward_batch(self, image_list: Iterable):
151        return torch.stack([self._transform_image(image) for image in image_list], dim=0)
def transform_coords( self, coords: torch.Tensor, normalize=False, orig_hw=None) -> torch.Tensor:
153    def transform_coords(self, coords: torch.Tensor, normalize=False, orig_hw=None) -> torch.Tensor:
154        coords = coords.clone()
155        if normalize:
156            if orig_hw is None:
157                raise ValueError("orig_hw is required when normalizing prompt coordinates.")
158            scale = float(self.resolution) / max(orig_hw)
159            coords[..., 0] *= scale
160            coords[..., 1] *= scale
161        else:
162            coords *= self.resolution
163        return coords
def transform_boxes(self, boxes: torch.Tensor, normalize=False, orig_hw=None) -> torch.Tensor:
165    def transform_boxes(self, boxes: torch.Tensor, normalize=False, orig_hw=None) -> torch.Tensor:
166        return self.transform_coords(boxes.reshape(-1, 2, 2), normalize=normalize, orig_hw=orig_hw)
def postprocess_masks(self, masks: torch.Tensor, orig_hw) -> torch.Tensor:
168    def postprocess_masks(self, masks: torch.Tensor, orig_hw) -> torch.Tensor:
169        """Upsample, remove bottom/right padding, and restore the original shape."""
170        masks = masks.float()
171        flat = masks.flatten(0, 1).unsqueeze(1)
172        if self.max_hole_area > 0:
173            labels, areas = get_connected_components(flat <= self.mask_threshold)
174            masks = torch.where(
175                ((labels > 0) & (areas <= self.max_hole_area)).reshape_as(masks),
176                self.mask_threshold + 10.0,
177                masks,
178            )
179        if self.max_sprinkle_area > 0:
180            labels, areas = get_connected_components(flat > self.mask_threshold)
181            masks = torch.where(
182                ((labels > 0) & (areas <= self.max_sprinkle_area)).reshape_as(masks),
183                self.mask_threshold - 10.0,
184                masks,
185            )
186
187        new_h, new_w = get_preprocess_shape(orig_hw[0], orig_hw[1], self.resolution)
188        masks = F.interpolate(
189            masks.float(), (self.resolution, self.resolution), mode="bilinear", align_corners=False,
190        )
191        masks = masks[..., :new_h, :new_w]
192        return F.interpolate(masks, orig_hw, mode="bilinear", align_corners=False)

Upsample, remove bottom/right padding, and restore the original shape.