micro_sam.v2.bioimageio.model_export

Export micro-sam2 models to the BioImage.IO model format.

An exported model does interactive segmentation with box, point or mask prompts. If the weights hold a UniSAM2 decoder, it also does automatic instance segmentation (AIS) when you give no prompts.

  1"""Export micro-sam2 models to the BioImage.IO model format.
  2
  3An exported model does interactive segmentation with box, point or mask prompts. If the weights hold
  4a UniSAM2 decoder, it also does automatic instance segmentation (AIS) when you give no prompts.
  5"""
  6import os
  7import tempfile
  8from pathlib import Path
  9from typing import Optional, Union
 10
 11import numpy as np
 12import matplotlib.pyplot as plt
 13from skimage.segmentation import find_boundaries
 14
 15import bioimageio.core
 16import bioimageio.spec.model.v0_5 as spec
 17from bioimageio.spec import save_bioimageio_package
 18from bioimageio.core.digest_spec import create_sample_for_model
 19
 20import torch
 21
 22from ...util import load_checkpoint
 23from ...v1.prompt_based_segmentation import _compute_logits_from_mask
 24from ..util import FINETUNED_MODELS, _download_finetuned_sam2_model, _read_sam2_checkpoint, detect_sam2_backbone
 25from .predictor_adaptor import SAM2PredictorAdaptor
 26
 27
 28DEFAULTS = {
 29    "authors": [
 30        spec.Author(name="Anwai Archit", affiliation="University Goettingen", github_user="anwai98"),
 31        spec.Author(name="Constantin Pape", affiliation="University Goettingen", github_user="constantinpape"),
 32    ],
 33    "description": "Segment Anything 2 for Microscopy (micro-sam2), for interactive and automatic segmentation",
 34    "cite": [
 35        spec.CiteEntry(
 36            text="Archit et al. Segment Anything for Microscopy 2", doi=spec.Doi("10.64898/2026.11.12.766082"),
 37        ),
 38        spec.CiteEntry(
 39            text="Archit et al. Segment Anything for Microscopy", doi=spec.Doi("10.1038/s41592-024-02580-4"),
 40        ),
 41    ],
 42    "tags": [
 43        "segment-anything", "segment-anything-2", "micro-sam", "instance-segmentation", "interactive-segmentation",
 44    ],
 45}
 46
 47ANY_SIZE = spec.ParameterizedSize(min=1, step=1)
 48# The SAM2 mask decoder takes mask prompts as logits of this size.
 49MASK_PROMPT_SIZE = 256
 50
 51
 52def _get_weights(model_type, checkpoint_path, decoder_path, tmp_dir):
 53    """Save the SAM2 weights and the decoder weights in one file, as the adaptor loads them.
 54
 55    Returns:
 56        The path of the weights, the SAM2 backbone name and whether the weights hold a decoder.
 57    """
 58    if checkpoint_path is None:
 59        if model_type not in FINETUNED_MODELS:
 60            raise ValueError(f"'{model_type}' is not a finetuned micro-sam2 model. Give a 'checkpoint_path'.")
 61        checkpoint_path, _, decoder_path = _download_finetuned_sam2_model(model_type)
 62
 63    state, model_state, encoder_only = _read_sam2_checkpoint(checkpoint_path)
 64    if encoder_only:
 65        raise ValueError(f"'{checkpoint_path}' holds only an image encoder. Give the checkpoint of the SAM2 model.")
 66    if isinstance(state, dict) and state.get("peft_kwargs") is not None:
 67        raise ValueError("The export does not support PEFT checkpoints. Merge the PEFT weights first.")
 68
 69    # A joint checkpoint holds the decoder together with the SAM2 weights.
 70    decoder_state = state.get("decoder_state") if isinstance(state, dict) else None
 71    if decoder_path is not None:
 72        decoder_state = load_checkpoint(decoder_path)
 73        decoder_state = decoder_state.get("model_state", decoder_state)
 74    if decoder_state is not None:
 75        if "out_conv.weight" not in decoder_state:
 76            raise ValueError("The decoder weights hold no UniSAM2 decoder.")
 77        # The decoder reuses the SAM2 image encoder, so the encoder weights are saved only once.
 78        encoder_state = {k: v for k, v in decoder_state.items() if k.startswith("encoder.inner.")}
 79        for key, value in encoder_state.items():
 80            if not torch.equal(value, model_state["image_encoder." + key[len("encoder.inner."):]]):
 81                raise ValueError("The image encoder of the decoder weights differs from the SAM2 model.")
 82        decoder_state = {k: v for k, v in decoder_state.items() if not k.startswith("encoder.inner.")}
 83
 84    weights = {"model_state": model_state}
 85    if decoder_state is not None:
 86        weights["decoder_state"] = decoder_state
 87    weight_path = os.path.join(tmp_dir, f"{model_type}.pt")
 88    torch.save(weights, weight_path)
 89    return weight_path, detect_sam2_backbone(model_state), decoder_state is not None
 90
 91
 92def _to_image_tensor(image):
 93    """Bring a 2d or channel-last image to the input layout: batch x channel x y x x."""
 94    image = np.asarray(image, dtype="float32")
 95    if image.ndim == 2:
 96        image = image[..., None]
 97    if image.ndim != 3 or image.shape[-1] not in (1, 3):
 98        raise ValueError(f"The image must be 2d or channel-last with 1 or 3 channels, got shape {image.shape}.")
 99    return image.transpose(2, 0, 1)[None]
100
101
102def _create_test_inputs(image, label_image, tmp_dir):
103    """Save the test image and a box, a point and a mask prompt for each of the two largest objects."""
104    inputs = {"image": os.path.join(tmp_dir, "image.npy")}
105    np.save(inputs["image"], _to_image_tensor(image))
106
107    seg_ids, sizes = np.unique(label_image[label_image != 0], return_counts=True)
108    if len(seg_ids) == 0:
109        raise ValueError("The label image has no objects to derive the test prompts from.")
110    boxes, points, masks = [], [], []
111    for seg_id in seg_ids[np.argsort(sizes)[::-1][:2]]:
112        masks.append(_compute_logits_from_mask(label_image == seg_id))
113        coords = np.argwhere(label_image == seg_id)
114        (y0, x0), (y1, x1) = coords.min(axis=0), coords.max(axis=0)
115        boxes.append([x0, y0, x1, y1])
116        # The object pixel that is nearest to the center, so that the point is inside the object.
117        y, x = coords[np.argmin(((coords - coords.mean(axis=0)) ** 2).sum(axis=1))]
118        points.append([[x, y]])
119
120    prompts = {
121        "box_prompts": np.array(boxes, dtype="int64")[None],
122        "point_prompts": np.array(points, dtype="int64")[None],
123        "point_labels": np.ones((1, len(points), 1), dtype="int64"),
124        "mask_prompts": np.stack(masks).astype("float32")[None],
125    }
126    for name, prompt in prompts.items():
127        inputs[name] = os.path.join(tmp_dir, f"{name}.npy")
128        np.save(inputs[name], prompt)
129    return inputs
130
131
132def _to_label_image(masks):
133    """Merge the binary masks of the objects (1 x OBJECTS x 1 x H x W) into one label image."""
134    labels = np.zeros(masks.shape[-2:], dtype="uint32")
135    for seg_id, mask in enumerate(masks[0, :, 0], start=1):
136        labels[mask > 0] = seg_id
137    return labels
138
139
140def _write_documentation(documentation, model_type, with_decoder, tmp_dir):
141    if documentation is not None and os.path.exists(documentation):
142        return documentation
143
144    doc_path = os.path.join(tmp_dir, "documentation.md")
145    if documentation is None:
146        automatic = (
147            "Automatic instance segmentation: give only the image. The model segments all objects with its "
148            "UniSAM2 decoder (AIS) and returns one mask per object.\n"
149        ) if with_decoder else (
150            "This model has no decoder for automatic instance segmentation, so you must give prompts.\n"
151        )
152        documentation = (
153            f"# Segment Anything 2 for Microscopy: {model_type}\n\n"
154            "micro-sam2 finetunes Segment Anything 2 (SAM2) for microscopy. This model does interactive "
155            "segmentation with prompts and, if it has a decoder, automatic instance segmentation.\n\n"
156            "## How to use the model\n\n"
157            "- The image has 1 or 3 channels and any intensity range. The model normalizes it.\n"
158            "- Interactive segmentation: give box prompts (x_min, y_min, x_max, y_max), point prompts (x, y) "
159            "with point labels (1 positive, 0 negative), or mask prompts (logits of size 256 x 256). The model "
160            "returns one mask and one quality score per object.\n"
161            f"- {automatic}\n"
162            "The tool [micro_sam](https://github.com/computational-cell-analytics/micro-sam) also loads the "
163            "weights of this model, for the napari annotation tools, the command line and the python library.\n"
164        )
165    with open(doc_path, "w") as f:
166        f.write(documentation)
167    return doc_path
168
169
170def _write_dependencies(tmp_dir):
171    dependency_file = os.path.join(tmp_dir, "environment.yaml")
172    with open(dependency_file, "w") as f:
173        f.write(
174            "name: micro-sam2\nchannels:\n    - conda-forge\ndependencies:\n    - micro_sam >=2.0\n    - pip\n"
175            "    - pip:\n        - git+https://github.com/facebookresearch/sam2.git\n"
176        )
177    return dependency_file
178
179
180def _generate_cover(input_paths, masks, show_boxes, tmp_dir):
181    """Show the image and the outlines of the predicted objects side by side."""
182    image = np.load(input_paths["image"])[0].transpose(1, 2, 0).astype("float32")
183    low, high = np.percentile(image, (1, 99))
184    image = np.clip((image - low) / max(high - low, 1e-6), 0, 1)
185    if image.shape[-1] == 1:
186        image = np.repeat(image, 3, axis=-1)
187
188    overlay = image.copy()
189    for mask in masks[0, :, 0]:
190        overlay[find_boundaries(mask > 0, mode="thick")] = (1.0, 0.8, 0.0)
191    if show_boxes:
192        for x0, y0, x1, y1 in np.load(input_paths["box_prompts"])[0]:
193            overlay[y0:y1 + 1, [x0, x1]] = overlay[[y0, y1], x0:x1 + 1] = (0.0, 0.6, 1.0)
194
195    fig, axes = plt.subplots(1, 2, figsize=(10, 5))
196    for ax, data in zip(axes, (image, overlay)):
197        ax.imshow(data)
198        ax.axis("off")
199    cover_path = os.path.join(tmp_dir, "cover.png")
200    plt.savefig(cover_path, bbox_inches="tight", dpi=100)
201    plt.close()
202    return cover_path
203
204
205def _build_model_description(name, input_paths, output_paths, weights, doc_path, covers, **kwargs):
206    image_shape = np.load(input_paths["image"], mmap_mode="r").shape
207    channel_names = ["gray"] if image_shape[1] == 1 else ["red", "green", "blue"]
208
209    def _test_tensor(name):
210        return spec.FileDescr(source=input_paths[name])
211
212    object_axis = spec.IndexInputAxis(id=spec.AxisId("object"), size=ANY_SIZE)
213    point_axis = spec.IndexInputAxis(id=spec.AxisId("point"), size=ANY_SIZE)
214    inputs = [
215        spec.InputTensorDescr(
216            id=spec.TensorId("image"),
217            description="The image. The model normalizes the intensities.",
218            axes=[
219                spec.BatchAxis(size=1),
220                spec.ChannelAxis(channel_names=[spec.Identifier(c) for c in channel_names]),
221                spec.SpaceInputAxis(id=spec.AxisId("y"), size=ANY_SIZE),
222                spec.SpaceInputAxis(id=spec.AxisId("x"), size=ANY_SIZE),
223            ],
224            test_tensor=_test_tensor("image"),
225            data=spec.IntervalOrRatioDataDescr(type="float32"),
226        ),
227        spec.InputTensorDescr(
228            id=spec.TensorId("box_prompts"),
229            description="One box per object: x_min, y_min, x_max, y_max.",
230            optional=True,
231            axes=[
232                spec.BatchAxis(size=1), object_axis,
233                spec.ChannelAxis(channel_names=[spec.Identifier(c) for c in ("x_min", "y_min", "x_max", "y_max")]),
234            ],
235            test_tensor=_test_tensor("box_prompts"),
236            data=spec.IntervalOrRatioDataDescr(type="int64"),
237        ),
238        spec.InputTensorDescr(
239            id=spec.TensorId("point_prompts"),
240            description="The point coordinates per object: x, y.",
241            optional=True,
242            axes=[
243                spec.BatchAxis(size=1), object_axis, point_axis,
244                spec.ChannelAxis(channel_names=[spec.Identifier(c) for c in "xy"]),
245            ],
246            test_tensor=_test_tensor("point_prompts"),
247            data=spec.IntervalOrRatioDataDescr(type="int64"),
248        ),
249        spec.InputTensorDescr(
250            id=spec.TensorId("point_labels"),
251            description="The label of each point: 1 is positive, 0 is negative.",
252            optional=True,
253            axes=[spec.BatchAxis(size=1), object_axis, point_axis],
254            test_tensor=_test_tensor("point_labels"),
255            data=spec.IntervalOrRatioDataDescr(type="int64"),
256        ),
257        spec.InputTensorDescr(
258            id=spec.TensorId("mask_prompts"),
259            description="One mask prompt per object, as logits.",
260            optional=True,
261            axes=[
262                spec.BatchAxis(size=1), object_axis,
263                spec.ChannelAxis(channel_names=[spec.Identifier("mask")]),
264                spec.SpaceInputAxis(id=spec.AxisId("y"), size=MASK_PROMPT_SIZE),
265                spec.SpaceInputAxis(id=spec.AxisId("x"), size=MASK_PROMPT_SIZE),
266            ],
267            test_tensor=_test_tensor("mask_prompts"),
268            data=spec.IntervalOrRatioDataDescr(type="float32"),
269        ),
270    ]
271
272    object_out_axis = spec.IndexOutputAxis(id=spec.AxisId("object"), size=spec.DataDependentSize())
273    outputs = [
274        spec.OutputTensorDescr(
275            id=spec.TensorId("masks"),
276            description="One binary mask per object.",
277            axes=[
278                spec.BatchAxis(size=1), object_out_axis,
279                spec.ChannelAxis(channel_names=[spec.Identifier("mask")]),
280                spec.SpaceOutputAxis(
281                    id=spec.AxisId("y"),
282                    size=spec.SizeReference(tensor_id=spec.TensorId("image"), axis_id=spec.AxisId("y")),
283                ),
284                spec.SpaceOutputAxis(
285                    id=spec.AxisId("x"),
286                    size=spec.SizeReference(tensor_id=spec.TensorId("image"), axis_id=spec.AxisId("x")),
287                ),
288            ],
289            data=spec.IntervalOrRatioDataDescr(type="uint8"),
290            test_tensor=spec.FileDescr(source=output_paths["masks"]),
291        ),
292        spec.OutputTensorDescr(
293            id=spec.TensorId("scores"),
294            description="The predicted quality of each mask. The scores are 1 for automatic segmentation.",
295            axes=[spec.BatchAxis(size=1), object_out_axis, spec.ChannelAxis(channel_names=[spec.Identifier("score")])],
296            data=spec.IntervalOrRatioDataDescr(type="float32"),
297            test_tensor=spec.FileDescr(source=output_paths["scores"]),
298        ),
299    ]
300
301    extra_kwargs = {key: kwargs[key] for key in ("id", "id_emoji", "uploader", "version") if key in kwargs}
302    return spec.ModelDescr(
303        name=name,
304        description=kwargs.get("description", DEFAULTS["description"]),
305        authors=kwargs.get("authors", DEFAULTS["authors"]),
306        cite=kwargs.get("cite", DEFAULTS["cite"]),
307        license=spec.LicenseId(kwargs.get("license", "CC-BY-4.0")),
308        documentation=spec.FileDescr(source=Path(doc_path)),
309        git_repo=spec.HttpUrl("https://github.com/computational-cell-analytics/micro-sam"),
310        tags=kwargs.get("tags", DEFAULTS["tags"]),
311        covers=[spec.FileDescr(source=Path(cover)) for cover in covers],
312        inputs=inputs,
313        outputs=outputs,
314        weights=weights,
315        **extra_kwargs,
316    )
317
318
319def _predict(model_description, inputs):
320    """Run the model through BioImage.IO on the CPU."""
321    sample = create_sample_for_model(model=model_description, inputs=inputs)
322    with bioimageio.core.create_prediction_pipeline(model_description, devices=["cpu"]) as pp:
323        prediction = pp.predict_sample_without_blocking(sample)
324    return {name: np.asarray(prediction.members[name].data) for name in ("masks", "scores")}
325
326
327def _check_automatic(model_description, image_path, expected_masks):
328    """Check that BioImage.IO runs AIS when it gets only the image, with the expected objects."""
329    result = _predict(model_description, {"image": np.load(image_path)})
330    if result["masks"].shape != expected_masks.shape or not np.array_equal(result["masks"], expected_masks):
331        raise RuntimeError(
332            f"Automatic segmentation through BioImage.IO gives {result['masks'].shape[1]} objects, "
333            f"but the model gives {expected_masks.shape[1]} objects."
334        )
335
336
337def export_sam2_model(
338    image: np.ndarray,
339    label_image: Optional[np.ndarray],
340    model_type: str,
341    name: str,
342    output_path: Union[str, os.PathLike],
343    checkpoint_path: Optional[Union[str, os.PathLike]] = None,
344    decoder_path: Optional[Union[str, os.PathLike]] = None,
345    **kwargs,
346) -> None:
347    """Export a micro-sam2 model to the BioImage.IO model format.
348
349    The exported model does interactive segmentation with box, point and mask prompts. If the weights
350    hold a UniSAM2 decoder, it also does automatic instance segmentation (AIS) when you give only the image.
351    The package test runs box and point prompts. For weights with a decoder, the function also checks
352    AIS through BioImage.IO before it saves the package.
353
354    Args:
355        image: The test image, 2d or channel-last with 1 or 3 channels.
356        label_image: The segmentation of the test image. The function derives the test prompts from it.
357            For weights with a decoder, the AIS result of the model is used by default.
358        model_type: The name of a finetuned micro-sam2 model, e.g. 'hvit_t_cells'. With `checkpoint_path`,
359            the name of your model.
360        name: The name of the exported model.
361        output_path: The path of the exported package, a zip file.
362        checkpoint_path: The path of your SAM2 checkpoint. By default the weights of `model_type` are downloaded.
363            A joint checkpoint with 'model_state' and 'decoder_state' also gives the decoder.
364        decoder_path: The path of your UniSAM2 decoder checkpoint.
365        kwargs: Optional metadata: 'description', 'authors', 'cite', 'tags', 'license', 'documentation'
366            (text or a file path), 'covers' (file paths), 'id', 'id_emoji', 'uploader' and 'version'.
367
368    Raises:
369        RuntimeError: If the exported model fails a check.
370    """
371    with tempfile.TemporaryDirectory() as tmp_dir:
372        weight_path, backbone, with_decoder = _get_weights(model_type, checkpoint_path, decoder_path, tmp_dir)
373        if not with_decoder and label_image is None:
374            raise ValueError("Give a 'label_image' to derive the test prompts for weights without a decoder.")
375
376        # The reference outputs come from the adaptor on the CPU, as BioImage.IO runs it in the test.
377        adaptor = SAM2PredictorAdaptor(backbone)
378        adaptor.load_state_dict(torch.load(weight_path, map_location="cpu", weights_only=True))
379        adaptor.eval()
380        image_tensor = torch.from_numpy(_to_image_tensor(image))
381        automatic_masks = None
382        if with_decoder:
383            automatic_masks, _ = adaptor(image_tensor)
384            automatic_masks = automatic_masks.numpy()
385            if automatic_masks.shape[1] == 0:
386                raise RuntimeError("AIS finds no objects in the test image. Use an image with objects.")
387            if label_image is None:
388                label_image = _to_label_image(automatic_masks)
389
390        input_paths = _create_test_inputs(image, label_image, tmp_dir)
391        masks, scores = adaptor(**{key: torch.from_numpy(np.load(path)) for key, path in input_paths.items()})
392        output_paths = {key: os.path.join(tmp_dir, f"{key}.npy") for key in ("masks", "scores")}
393        np.save(output_paths["masks"], masks.numpy())
394        np.save(output_paths["scores"], scores.numpy())
395        del adaptor
396
397        weights = spec.WeightsDescr(
398            pytorch_state_dict=spec.PytorchStateDictWeightsDescr(
399                source=Path(weight_path),
400                architecture=spec.ArchitectureFromFileDescr(
401                    source=Path(os.path.join(os.path.dirname(__file__), "predictor_adaptor.py")),
402                    callable="SAM2PredictorAdaptor",
403                    kwargs={"model_type": backbone},
404                ),
405                pytorch_version=spec.Version(torch.__version__),
406                dependencies=spec.FileDescr(source=Path(_write_dependencies(tmp_dir))),
407            )
408        )
409        doc_path = _write_documentation(kwargs.pop("documentation", None), model_type, with_decoder, tmp_dir)
410        covers = kwargs.pop("covers", None)
411        if covers is None:
412            # The cover shows all objects for AIS, and the prompted objects otherwise.
413            cover_masks = masks.numpy() if automatic_masks is None else automatic_masks
414            covers = [_generate_cover(input_paths, cover_masks, automatic_masks is None, tmp_dir)]
415        model_description = _build_model_description(
416            name, input_paths, output_paths, weights, doc_path, covers, **kwargs,
417        )
418
419        summary = bioimageio.core.test_model(model_description, devices=["cpu"])
420        if summary.status != "passed":
421            summary.display()
422            raise RuntimeError(f"The exported model '{name}' fails the BioImage.IO test.")
423        # The package test runs only the prompts, so the function checks AIS here.
424        if with_decoder:
425            _check_automatic(model_description, input_paths["image"], automatic_masks)
426
427        save_bioimageio_package(model_description, output_path=output_path)
DEFAULTS = {'authors': [Author(affiliation='University Goettingen', email=None, orcid=None, name='Anwai Archit', github_user='anwai98'), Author(affiliation='University Goettingen', email=None, orcid=None, name='Constantin Pape', github_user='constantinpape')], 'description': 'Segment Anything 2 for Microscopy (micro-sam2), for interactive and automatic segmentation', 'cite': [CiteEntry(text='Archit et al. Segment Anything for Microscopy 2', doi='10.64898/2026.11.12.766082', url=None), CiteEntry(text='Archit et al. Segment Anything for Microscopy', doi='10.1038/s41592-024-02580-4', url=None)], 'tags': ['segment-anything', 'segment-anything-2', 'micro-sam', 'instance-segmentation', 'interactive-segmentation']}
ANY_SIZE = ParameterizedSize(min=1, step=1)
MASK_PROMPT_SIZE = 256
def export_sam2_model( image: numpy.ndarray, label_image: Optional[numpy.ndarray], model_type: str, name: str, output_path: Union[str, os.PathLike], checkpoint_path: Union[str, os.PathLike, NoneType] = None, decoder_path: Union[str, os.PathLike, NoneType] = None, **kwargs) -> None:
338def export_sam2_model(
339    image: np.ndarray,
340    label_image: Optional[np.ndarray],
341    model_type: str,
342    name: str,
343    output_path: Union[str, os.PathLike],
344    checkpoint_path: Optional[Union[str, os.PathLike]] = None,
345    decoder_path: Optional[Union[str, os.PathLike]] = None,
346    **kwargs,
347) -> None:
348    """Export a micro-sam2 model to the BioImage.IO model format.
349
350    The exported model does interactive segmentation with box, point and mask prompts. If the weights
351    hold a UniSAM2 decoder, it also does automatic instance segmentation (AIS) when you give only the image.
352    The package test runs box and point prompts. For weights with a decoder, the function also checks
353    AIS through BioImage.IO before it saves the package.
354
355    Args:
356        image: The test image, 2d or channel-last with 1 or 3 channels.
357        label_image: The segmentation of the test image. The function derives the test prompts from it.
358            For weights with a decoder, the AIS result of the model is used by default.
359        model_type: The name of a finetuned micro-sam2 model, e.g. 'hvit_t_cells'. With `checkpoint_path`,
360            the name of your model.
361        name: The name of the exported model.
362        output_path: The path of the exported package, a zip file.
363        checkpoint_path: The path of your SAM2 checkpoint. By default the weights of `model_type` are downloaded.
364            A joint checkpoint with 'model_state' and 'decoder_state' also gives the decoder.
365        decoder_path: The path of your UniSAM2 decoder checkpoint.
366        kwargs: Optional metadata: 'description', 'authors', 'cite', 'tags', 'license', 'documentation'
367            (text or a file path), 'covers' (file paths), 'id', 'id_emoji', 'uploader' and 'version'.
368
369    Raises:
370        RuntimeError: If the exported model fails a check.
371    """
372    with tempfile.TemporaryDirectory() as tmp_dir:
373        weight_path, backbone, with_decoder = _get_weights(model_type, checkpoint_path, decoder_path, tmp_dir)
374        if not with_decoder and label_image is None:
375            raise ValueError("Give a 'label_image' to derive the test prompts for weights without a decoder.")
376
377        # The reference outputs come from the adaptor on the CPU, as BioImage.IO runs it in the test.
378        adaptor = SAM2PredictorAdaptor(backbone)
379        adaptor.load_state_dict(torch.load(weight_path, map_location="cpu", weights_only=True))
380        adaptor.eval()
381        image_tensor = torch.from_numpy(_to_image_tensor(image))
382        automatic_masks = None
383        if with_decoder:
384            automatic_masks, _ = adaptor(image_tensor)
385            automatic_masks = automatic_masks.numpy()
386            if automatic_masks.shape[1] == 0:
387                raise RuntimeError("AIS finds no objects in the test image. Use an image with objects.")
388            if label_image is None:
389                label_image = _to_label_image(automatic_masks)
390
391        input_paths = _create_test_inputs(image, label_image, tmp_dir)
392        masks, scores = adaptor(**{key: torch.from_numpy(np.load(path)) for key, path in input_paths.items()})
393        output_paths = {key: os.path.join(tmp_dir, f"{key}.npy") for key in ("masks", "scores")}
394        np.save(output_paths["masks"], masks.numpy())
395        np.save(output_paths["scores"], scores.numpy())
396        del adaptor
397
398        weights = spec.WeightsDescr(
399            pytorch_state_dict=spec.PytorchStateDictWeightsDescr(
400                source=Path(weight_path),
401                architecture=spec.ArchitectureFromFileDescr(
402                    source=Path(os.path.join(os.path.dirname(__file__), "predictor_adaptor.py")),
403                    callable="SAM2PredictorAdaptor",
404                    kwargs={"model_type": backbone},
405                ),
406                pytorch_version=spec.Version(torch.__version__),
407                dependencies=spec.FileDescr(source=Path(_write_dependencies(tmp_dir))),
408            )
409        )
410        doc_path = _write_documentation(kwargs.pop("documentation", None), model_type, with_decoder, tmp_dir)
411        covers = kwargs.pop("covers", None)
412        if covers is None:
413            # The cover shows all objects for AIS, and the prompted objects otherwise.
414            cover_masks = masks.numpy() if automatic_masks is None else automatic_masks
415            covers = [_generate_cover(input_paths, cover_masks, automatic_masks is None, tmp_dir)]
416        model_description = _build_model_description(
417            name, input_paths, output_paths, weights, doc_path, covers, **kwargs,
418        )
419
420        summary = bioimageio.core.test_model(model_description, devices=["cpu"])
421        if summary.status != "passed":
422            summary.display()
423            raise RuntimeError(f"The exported model '{name}' fails the BioImage.IO test.")
424        # The package test runs only the prompts, so the function checks AIS here.
425        if with_decoder:
426            _check_automatic(model_description, input_paths["image"], automatic_masks)
427
428        save_bioimageio_package(model_description, output_path=output_path)

Export a micro-sam2 model to the BioImage.IO model format.

The exported model does interactive segmentation with box, point and mask prompts. If the weights hold a UniSAM2 decoder, it also does automatic instance segmentation (AIS) when you give only the image. The package test runs box and point prompts. For weights with a decoder, the function also checks AIS through BioImage.IO before it saves the package.

Arguments:
  • image: The test image, 2d or channel-last with 1 or 3 channels.
  • label_image: The segmentation of the test image. The function derives the test prompts from it. For weights with a decoder, the AIS result of the model is used by default.
  • model_type: The name of a finetuned micro-sam2 model, e.g. 'hvit_t_cells'. With checkpoint_path, the name of your model.
  • name: The name of the exported model.
  • output_path: The path of the exported package, a zip file.
  • checkpoint_path: The path of your SAM2 checkpoint. By default the weights of model_type are downloaded. A joint checkpoint with 'model_state' and 'decoder_state' also gives the decoder.
  • decoder_path: The path of your UniSAM2 decoder checkpoint.
  • kwargs: Optional metadata: 'description', 'authors', 'cite', 'tags', 'license', 'documentation' (text or a file path), 'covers' (file paths), 'id', 'id_emoji', 'uploader' and 'version'.
Raises:
  • RuntimeError: If the exported model fails a check.