scikit-ops 0.1.0.dev6__py3-none-any.whl → 0.1.0.dev7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: scikit-ops
3
- Version: 0.1.0.dev6
3
+ Version: 0.1.0.dev7
4
4
  Summary: Appose-powered ops, and the machinery for running them.
5
5
  Project-URL: homepage, https://github.com/apposed/scikit-ops
6
6
  Project-URL: documentation, https://github.com/apposed/scikit-ops/blob/main/README.md
@@ -30,7 +30,7 @@ Classifier: Topic :: Utilities
30
30
  Requires-Python: >=3.10
31
31
  Requires-Dist: numpy
32
32
  Requires-Dist: ophelper<0.2,>=0.1.0.dev0
33
- Requires-Dist: oprunner<0.2,>=0.1.0.dev2
33
+ Requires-Dist: oprunner<0.2,>=0.1.0.dev3
34
34
  Requires-Dist: opspec<0.2,>=0.1.0.dev0
35
35
  Description-Content-Type: text/markdown
36
36
 
@@ -1,6 +1,7 @@
1
1
  skop/__init__.py,sha256=q3aBnPDP8M-mFYHVcXGB3nIwAJ9Woq6i5TKJp-T6_3o,518
2
2
  skop/models.py,sha256=fWPjTVLoqISXYBsf2HllaRhCx0c_QoOInA5cxp6mgH4,5311
3
3
  skop/ops/__init__.py,sha256=DYALgX7N8j17grfDurLsAEYe90MY6xnAvWBH1ctJWik,808
4
+ skop/ops/_microsam.py,sha256=bCjtIDlgQxTdih9SBzCMEy1VA61D8KO9D_fSrKy-1oA,763
4
5
  skop/ops/_util.py,sha256=4aTMa_NVv6IqmRXmVnQB6NZY_qHa7yvjduMYme-rGd4,4076
5
6
  skop/ops/edges.py,sha256=oom-p_Qgvdp64dG2k5clqvzNNMeSTC7u_LsC1pem3DA,13777
6
7
  skop/ops/generate.py,sha256=0cKxIdDyJXIRloFfAeypx7DxIYhvvxdux1WwrkgBMBw,2722
@@ -26,17 +27,19 @@ skop/ops/kernels/_recenter.py,sha256=jHQYKKK-l84HTQgCZgH3UQQzxekazeviG2sNzRAc0tk
26
27
  skop/ops/kernels/gibson_lanni.py,sha256=NngT_BAZnnwViHcCbLt0abK5SWYdGzJfr6K4kfGXov4,6745
27
28
  skop/ops/kernels/paraxial.py,sha256=CEqv4Fzq0ZXlIFelqWTOsbVuHEcgEWQLxz87zISTxbc,5554
28
29
  skop/ops/kernels/psf.py,sha256=wntCqZ6wsq9HeVA9wtA6tSotns03BrpVOLwFNZGOH-Q,2087
29
- skop/ops/mask/__init__.py,sha256=hk0mQqFiypPG9ZucNuKfU1tjQkab5H5jRsG6kTuZx6s,1387
30
+ skop/ops/mask/__init__.py,sha256=uwDiWytHXC3hHOFmU49_Y65Ecmz2MNaG4TdMKhOzesE,1469
30
31
  skop/ops/mask/_result.py,sha256=OtEe58jlYC88g-uTujypyUaMoucMDO_OT9VIhPGBkJk,1717
31
- skop/ops/mask/microsam.py,sha256=Rq3CxPKPu2gn-7w8PN1v3ow0yp41H_lc6U2rlV073yg,4670
32
+ skop/ops/mask/microsam.py,sha256=x_o_Frxf2k6GqSelZL82HVWy9d_KE-ofVjB-ZYS0YQQ,4757
33
+ skop/ops/mask/microsam2.py,sha256=5fF0iqc5sJQM5qL8Mhs3yvgFN7sPAZRh7XHtu6Y_jHs,4369
32
34
  skop/ops/mask/mobilesam.py,sha256=PqiXvF0CrH4n7PnJPItXg_24PpMMw0JzRoqnzBu8FXk,7436
33
35
  skop/ops/prompt/__init__.py,sha256=uk3Bn0zgSBoI1ajorhXYD5p2t94hOfCP14tdITV00nA,678
34
- skop/ops/prompt/microsam.py,sha256=B21jV2hz0xJtadHQyE7oR1AoW83eKveKrWb4cL2asts,6643
36
+ skop/ops/prompt/microsam.py,sha256=F90g6pXyR3Bnjj_xGVEPPxKGMUwWvVWp8l6CRsrbuOQ,6783
35
37
  skop/ops/segment/__init__.py,sha256=YrhqQclX9BZOhVDL2JyflDI7u8xJhoQXVQAW35cX7xI,714
36
38
  skop/ops/segment/cellpose3.py,sha256=GxEAVOpAMYurYMcbTf5hMlzQDt0KgJq1qMPTxRFFF60,10375
37
39
  skop/ops/segment/cellpose4.py,sha256=y7g7ZXK0M8l11IJAPKJ-OtIZBrxWK5-mmNdJRUUMlqc,5149
38
40
  skop/ops/segment/instanseg.py,sha256=TvQbmwqDm4_pqBbQX6H1kYvKuNb5fdppxoIIJOK8G9M,6296
39
- skop/ops/segment/microsam.py,sha256=JmXs0H3oNLmGqSQkojQoKvVgCSH0y0TfSobqbjgZmk4,4410
41
+ skop/ops/segment/microsam.py,sha256=RZ9bvsGnyrqgjwPCm9jy_Eed6z2QO26W4rFKtB3nXzU,4512
42
+ skop/ops/segment/microsam2.py,sha256=ipr3tggcN1RKC8e-y1fbGiv88QH5XSi4_2AjJCDtOJY,5277
40
43
  skop/ops/segment/stardist2d.py,sha256=XSG4kabcfeY5fsQr1e3kYmGbkWOqyoTTyEp98MB679M,6605
41
44
  skop/ops/segment/starfun3d.py,sha256=03RB3QL59NkkbgVABXTf9_VKZ-1Li_wUeJFPFjTqeAQ,3417
42
45
  skop/ops/segment/unseg/__init__.py,sha256=nxfXLG3xmnL5zwAlUB7YPdFeLNQk5R6L8JZ8BQ3c1nk,5088
@@ -45,26 +48,26 @@ skop/ops/train/__init__.py,sha256=KtM51FOiGn47yPtCG27PNkKLLvA7381FZ-XPzBngtq8,31
45
48
  skop/ops/train/_util.py,sha256=xgQxx4PDBVODntPmmlNGQ65ICs8yAPKHQHHBHqFkg6I,6114
46
49
  skop/ops/train/cellpose3.py,sha256=uh1SI72eYwnmSQjo0jmKhlkTW3FE5MKTd_H9_6onwac,8482
47
50
  skop/ops/train/cellpose4.py,sha256=akcfij7wsR4kdqlw9AmBBZ5Jh3UCF6dMLSyUnxFhVYA,7212
48
- skop/ops/train/microsam.py,sha256=J2CgZ7sg0lbdDemjpqzzobasMkl8y-cQDKM-66q6kpQ,7917
51
+ skop/ops/train/microsam.py,sha256=vSbW5W-_XvTRGNBtgHxik0oZ-8G542bijhEgftxpcYY,7937
49
52
  skop/ops/train/stardist2d.py,sha256=dioZYyyw6coHoPLGWIBJxVIYmAHtOp6GjxsDkGDBCSQ,18876
50
53
  skop/ops/train/yolo.py,sha256=nof2iyvy79tIpYU15hqN5CRGIEuGmbAApX5Ma6jGMjI,20348
51
54
  skop/ops/workflows/__init__.py,sha256=7GyWvVd9hIuDhup-ElcIeinjoI6xAe_JLwS67UDsIZM,1934
52
55
  skop/ops/workflows/deconvolve/__init__.py,sha256=7f6Sd4cJCfPPfEVwlXo3TIyN00P974zjXA-s3xv5YZ8,189
53
56
  skop/ops/workflows/deconvolve/with_psf.py,sha256=yATu3eqPW37haDJPEFxtI3DEMuWqaMxtrgFK0glZadM,4260
54
57
  skop/ops/workflows/mask/__init__.py,sha256=nKt0l8GrX44sCQ9jTtExBARnNrPZu6Y2AWVsMBPzdto,190
55
- skop/ops/workflows/mask/detect_then_mask.py,sha256=-6DtBC0rdrs1XZKM5rN-ruFO7kRJatIpZGDp4cb0ZA0,4166
58
+ skop/ops/workflows/mask/detect_then_mask.py,sha256=bGX-KkZkeQapag9EHRmxOzxpMPhLmQpf-mzDy8FGz24,4473
56
59
  skop/ops/workflows/segment/__init__.py,sha256=RBdgluVVsBwuyPgYdkXbfYnb6sAWUrMQ7vcMV8rxOB4,184
57
60
  skop/ops/workflows/segment/connect_2d_in_3d.py,sha256=gV9M5AJQbV0Q4weeP-BF_LHiOg6TSoBUsZhndc5jzhU,6377
58
61
  skop/envs/cellpose3/pixi.toml,sha256=iITLZdO4M6UdWI8MYbEPsCT_mDG-mlPEvlPoGvhfRn4,1696
59
62
  skop/envs/cupy/pixi.toml,sha256=JF-jHEh6WpqyK4CtaFnYzHc7OZRNyf2xezuWYb-MFek,1377
60
63
  skop/envs/minimal/pixi.toml,sha256=bZWIUkttfC9klPbRMHl01E4e7OGlrTpJ6V84veVHCr0,1031
61
- skop/envs/pytorch/pixi.toml,sha256=rmbIGWNOtB8Y7Pj4zZS3R4g9bTs3cOHZ2Soc0niyAPY,3775
64
+ skop/envs/pytorch/pixi.toml,sha256=kEYT4BJ0RwaRf9ouirKIrtCXs-WJcPvRVpoE1LSFgw4,3900
62
65
  skop/envs/sdeconv/pixi.toml,sha256=VNt7w0guatGlS6vU79BqKWKfNKKr9VkfmvU_RwUxi5Y,3822
63
66
  skop/envs/segment-everything/pixi.toml,sha256=1EmfO-fL9bj6SH-RnxdZpGw75pXmx6-g4EGxj_sqBJE,3774
64
67
  skop/envs/skimage/pixi.toml,sha256=wAfyOSuvsUpmKIj_Hqk3ylxck_uh6wYeMZ2BTjoSBTI,1136
65
68
  skop/envs/stardist-tf/pixi.toml,sha256=oIY1XmErvbApe_pLGyQzzSf1K_RgN2rrgAvyVWYfKag,3487
66
69
  skop/envs/unseg-cv/pixi.toml,sha256=TwcYzpAnfBd5taAB0b-kRXBhbw5aXHoLzoKRaebvyDw,1065
67
- scikit_ops-0.1.0.dev6.dist-info/METADATA,sha256=BUQnjhC7ksd4UwhOqVmY5nL7jKecnzRyRPKxxkqwCtQ,1950
68
- scikit_ops-0.1.0.dev6.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
69
- scikit_ops-0.1.0.dev6.dist-info/entry_points.txt,sha256=0gDhmxYQNjvBwJO4L0Q2fB-5fIEBbRVUS5u5heCYulQ,43
70
- scikit_ops-0.1.0.dev6.dist-info/RECORD,,
70
+ scikit_ops-0.1.0.dev7.dist-info/METADATA,sha256=ibxBIGWvnyoFfraYWGmfo4Y1agC7adgi4a6JqaITbYk,1950
71
+ scikit_ops-0.1.0.dev7.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
72
+ scikit_ops-0.1.0.dev7.dist-info/entry_points.txt,sha256=0gDhmxYQNjvBwJO4L0Q2fB-5fIEBbRVUS5u5heCYulQ,43
73
+ scikit_ops-0.1.0.dev7.dist-info/RECORD,,
@@ -20,8 +20,10 @@ version = "0.1.0"
20
20
  # Cellpose 4 replaced the v3 model zoo and moved the API with it, so the two
21
21
  # cannot share an environment at any version pin.
22
22
 
23
+ # 12.9: micro_sam 2 needs sam-2, whose GPU builds all want CUDA 12.8 (Windows)
24
+ # or 12.9 (Linux) or newer. So this needs an NVIDIA driver from mid-2025 on.
23
25
  [system-requirements]
24
- cuda = "12.0"
26
+ cuda = "12.9"
25
27
 
26
28
  [dependencies]
27
29
  python = "3.11.*"
@@ -35,18 +37,17 @@ ultralytics = ">=8.3"
35
37
  # unsatisfiable. So this goes back to `appose = ">=0.12"` above as soon as
36
38
  # the rev below is bumped past that change and conda-forge carries 0.12.
37
39
 
38
- # NB: micro_sam depends on `napari >=0.5,<0.6` and `pyqt` outright -- it ships
39
- # a napari plugin and does not split it out. So this environment installs a GUI
40
- # stack that nothing in it imports; the ops use micro_sam.util and
41
- # micro_sam.prompt_based_segmentation, neither of which touches napari. Heavy
42
- # but harmless: a worker process never opens a window, and 0002's whole point
43
- # is that this napari pin cannot reach the front end's.
40
+ # NB: micro_sam depends on `napari >=0.7.1,<0.11` and `pyqt6` outright -- it
41
+ # ships a napari plugin and does not split it out. So this environment installs
42
+ # a GUI stack that nothing in it imports; the ops use micro_sam's model and
43
+ # prompt functions, none of which touches napari. Heavy but harmless: a worker
44
+ # process never opens a window, and 0002's whole point is that this napari pin
45
+ # cannot reach the front end's.
44
46
  #
45
- # It also carries `zarr <3` and `xarray <2025.3` -- worth knowing when the next
46
- # occupant fails to solve.
47
- # Below 2: the ops here were written and tested on 1.8. 2.0 is a major
48
- # version; lift this once they have been run against it.
49
- micro_sam = ">=1.6,<2"
47
+ # 2.x carries both families: SAM2 (`hvit_*` models) at the top and SAM1
48
+ # (`vit_*`) under micro_sam.v1, where skop.ops._microsam finds it. It also
49
+ # needs `zarr >=3` -- worth knowing when the next occupant fails to solve.
50
+ micro_sam = ">=2"
50
51
 
51
52
  # NB: torchvision is required explicitly even though nothing here imports it
52
53
  # directly. conda's ultralytics does not depend on it, but reads
@@ -78,7 +79,7 @@ scikit-ops = "==0.1.0.dev5"
78
79
  [target.linux-64.dependencies]
79
80
  pytorch-gpu = "*"
80
81
  cudnn = "*"
81
- cuda-version = "12.2"
82
+ cuda-version = "12.9.*"
82
83
 
83
84
  [target.win-64.dependencies]
84
85
  pytorch-gpu = "*"
skop/ops/_microsam.py ADDED
@@ -0,0 +1,21 @@
1
+ """micro_sam's SAM1 code, wherever the installed micro_sam keeps it.
2
+
3
+ micro_sam 2 moved it under ``micro_sam.v1``; 1.x has it at the top. Call
4
+ only inside op bodies, so discovery never imports micro_sam.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import importlib
10
+ from types import ModuleType
11
+
12
+
13
+ def sam1(module: str) -> ModuleType:
14
+ """``micro_sam.v1.<module>`` on micro_sam 2, ``micro_sam.<module>`` on 1.x."""
15
+ try:
16
+ return importlib.import_module(f"micro_sam.v1.{module}")
17
+ except ModuleNotFoundError as error:
18
+ # Only a missing micro_sam.v1 means 1.x; anything else is a real failure.
19
+ if error.name not in ("micro_sam.v1", f"micro_sam.v1.{module}"):
20
+ raise
21
+ return importlib.import_module(f"micro_sam.{module}")
skop/ops/mask/__init__.py CHANGED
@@ -13,7 +13,7 @@ say so. ``ophelper.masks`` holds the projections onto something a viewer shows.
13
13
 
14
14
  Every op here shares a signature and returns ``Masks``, so they are
15
15
  substitutable. One op per environment, since ``@op(env=...)`` is fixed per
16
- function: ``microsam_masks`` in the shared 'pytorch' environment, because
16
+ function: ``microsam_masks`` and ``microsam2_masks`` in the shared 'pytorch' environment, because
17
17
  micro_sam is a conda package that coexists with every other torch library
18
18
  there, and ``mobilesam_masks`` in segment-everything's own, alongside the
19
19
  object-aware detector it was trained to pair with and inside the vendored
@@ -24,6 +24,7 @@ from __future__ import annotations
24
24
 
25
25
  from ._result import Masks
26
26
  from .microsam import microsam_masks
27
+ from .microsam2 import microsam2_masks
27
28
  from .mobilesam import mobilesam_masks
28
29
 
29
- __all__ = ["Masks", "microsam_masks", "mobilesam_masks"]
30
+ __all__ = ["Masks", "microsam2_masks", "microsam_masks", "mobilesam_masks"]
skop/ops/mask/microsam.py CHANGED
@@ -82,8 +82,11 @@ def microsam_masks(
82
82
  if len(prompts) == 0:
83
83
  return Masks(ophelper.masks.empty(image.shape[:2]), ophelper.boxes.EMPTY.copy())
84
84
 
85
- from micro_sam.prompt_based_segmentation import segment_from_box
86
- from micro_sam.util import get_sam_model, precompute_image_embeddings
85
+ from .._microsam import sam1
86
+
87
+ segment_from_box = sam1("prompt_based_segmentation").segment_from_box
88
+ get_sam_model = sam1("util").get_sam_model
89
+ precompute_image_embeddings = sam1("util").precompute_image_embeddings
87
90
 
88
91
  progress(f"Loading {model.value}")
89
92
  predictor = get_sam_model(model_type=model.value)
@@ -0,0 +1,125 @@
1
+ """Box-prompted segmentation with micro_sam 2 (SAM2).
2
+
3
+ The SAM2 twin of ``skop.ops.mask.microsam``: same signature, same ``Masks``,
4
+ so the detect-then-mask workflow can swap one for the other. micro_sam 2
5
+ offers both its finetuned ``hvit_*_cells`` models and plain SAM2 (``hvit_b``
6
+ ...). Plain SAM2 has no automatic-segmentation decoder, but a box prompt
7
+ needs none -- every SAM2 model is promptable.
8
+
9
+ Driven through ``micro_sam.v2.util``'s predictor rather than
10
+ ``prompt_based_segmentation.promptable_segmentation_2d``, which paints its
11
+ masks into one label image and so loses the overlaps this op exists to keep.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from enum import Enum
17
+
18
+ import numpy as np
19
+
20
+ import ophelper.boxes
21
+ import ophelper.masks
22
+ from opspec.op import op
23
+ from opspec.runtime import progress
24
+ from opspec.types import BoxesOf, ImageOf
25
+
26
+ from ._result import Masks
27
+
28
+
29
+ class Sam2Model(Enum):
30
+ """micro_sam 2 checkpoints. ``*_cells`` are finetuned on light microscopy;
31
+ the plain ones are Meta's SAM2.1, trained on photographs and video."""
32
+
33
+ cells_base = "hvit_b_cells"
34
+ cells_tiny = "hvit_t_cells"
35
+ cells_small = "hvit_s_cells"
36
+ cells_large = "hvit_l_cells"
37
+ sam2_base = "hvit_b"
38
+ sam2_tiny = "hvit_t"
39
+ sam2_small = "hvit_s"
40
+ sam2_large = "hvit_l"
41
+
42
+
43
+ #: Boxes per predictor call. Each answer is a full-image mask, so this bounds
44
+ #: the memory one call holds.
45
+ _BATCH = 32
46
+
47
+ #: One predictor, for the model last asked for.
48
+ _loaded: dict = {}
49
+
50
+
51
+ def _predictor(model_type: str):
52
+ if model_type not in _loaded:
53
+ from micro_sam.v2.util import get_sam2_image_predictor, get_sam2_model
54
+
55
+ _loaded.clear()
56
+ progress(f"Loading micro_sam 2 {model_type}")
57
+ _loaded[model_type] = get_sam2_image_predictor(get_sam2_model(model_type=model_type))
58
+ return _loaded[model_type]
59
+
60
+
61
+ @op(env="pytorch")
62
+ def microsam2_masks(
63
+ image: ImageOf[np.ndarray],
64
+ boxes: BoxesOf[np.ndarray],
65
+ model: Sam2Model = Sam2Model.cells_base,
66
+ ) -> Masks:
67
+ """Segment one object per bounding box with micro_sam 2.
68
+
69
+ Args:
70
+ image: Image to segment. 2-D or RGB.
71
+ boxes: (N, 4) as [min_y, min_x, max_y, max_x], from a detector op, a
72
+ Shapes layer, or ``ophelper.boxes.from_labels``.
73
+ model: ``cells_*`` are finetuned for microscopy; ``sam2_*`` are plain
74
+ SAM2, which outlines whatever is in the box, unstained or not.
75
+
76
+ Returns:
77
+ masks: (N, Y, X) uint8, one object per plane. These may overlap.
78
+ boxes: the prompts that produced them.
79
+
80
+ Masks come back in prompt order -- ``masks[i]`` answers ``boxes[i]``.
81
+ Boxes SAM2 finds nothing in are dropped from both.
82
+ """
83
+ prompts = ophelper.boxes.as_boxes(boxes)
84
+ if len(prompts) == 0:
85
+ return Masks(ophelper.masks.empty(image.shape[:2]), ophelper.boxes.EMPTY.copy())
86
+
87
+ from micro_sam.v2.normalization import to_image
88
+ from micro_sam.v2.util import autocast, encode_image
89
+
90
+ predictor = _predictor(model.value)
91
+
92
+ progress("Computing image embeddings")
93
+ encode_image(predictor, to_image(np.asarray(image)))
94
+
95
+ # skop boxes are [min_y, min_x, max_y, max_x]; SAM2 takes xyxy.
96
+ height, width = image.shape[:2]
97
+ xyxy = np.stack(
98
+ [
99
+ np.clip(prompts[:, 1], 0, width),
100
+ np.clip(prompts[:, 0], 0, height),
101
+ np.clip(prompts[:, 3], 0, width),
102
+ np.clip(prompts[:, 2], 0, height),
103
+ ],
104
+ axis=1,
105
+ ).astype(np.float32)
106
+
107
+ found = []
108
+ kept = []
109
+ for start in range(0, len(xyxy), _BATCH):
110
+ progress(f"Segmenting objects {start + 1}-{min(start + _BATCH, len(xyxy))} of {len(xyxy)}",
111
+ start, len(xyxy))
112
+ with autocast(predictor.device):
113
+ masks, _, _ = predictor.predict(box=xyxy[start:start + _BATCH], multimask_output=False)
114
+ masks = np.asarray(masks).reshape(-1, height, width)
115
+ for i, mask in enumerate(masks, start=start):
116
+ # SAM2 answers some prompts with nothing; drop them and their box.
117
+ if not (mask > 0).any():
118
+ continue
119
+ found.append((mask > 0).astype(np.uint8))
120
+ kept.append(i)
121
+
122
+ progress(f"Segmented {len(found)} of {len(prompts)} objects")
123
+ if not found:
124
+ return Masks(ophelper.masks.empty(image.shape[:2]), ophelper.boxes.EMPTY.copy())
125
+ return Masks(np.stack(found), prompts[kept])
@@ -46,7 +46,9 @@ _embeddings: OrderedDict = OrderedDict()
46
46
 
47
47
  def _get_predictor(model_type: str):
48
48
  if model_type not in _predictor:
49
- from micro_sam.util import get_sam_model
49
+ from .._microsam import sam1
50
+
51
+ get_sam_model = sam1("util").get_sam_model
50
52
 
51
53
  _predictor.clear()
52
54
  progress(f"Loading micro_sam model {model_type}")
@@ -62,7 +64,9 @@ def _get_embeddings(image, embedding_path: str, model_type: str, ndim: int):
62
64
  _embeddings.move_to_end(key)
63
65
  return held[1]
64
66
 
65
- from micro_sam.util import precompute_image_embeddings
67
+ from .._microsam import sam1
68
+
69
+ precompute_image_embeddings = sam1("util").precompute_image_embeddings
66
70
 
67
71
  predictor = _get_predictor(model_type)
68
72
  progress("Computing or loading image embeddings")
@@ -149,7 +153,9 @@ def microsam_points(
149
153
  if len(points) == 0:
150
154
  return np.zeros(spatial, dtype=np.uint8)
151
155
 
152
- from micro_sam.prompt_based_segmentation import segment_from_points
156
+ from .._microsam import sam1
157
+
158
+ segment_from_points = sam1("prompt_based_segmentation").segment_from_points
153
159
 
154
160
  predictor = _get_predictor(model_type)
155
161
  embeddings = _get_embeddings(image, embedding_path, model_type, ndim)
@@ -175,9 +181,9 @@ def microsam_points(
175
181
  if not volume or not plane.any():
176
182
  return seg
177
183
 
178
- from micro_sam.multi_dimensional_segmentation import (
179
- segment_mask_in_volume,
180
- )
184
+ segment_mask_in_volume = sam1(
185
+ "multi_dimensional_segmentation"
186
+ ).segment_mask_in_volume
181
187
 
182
188
  progress("Carrying the object through z")
183
189
  seg, _ = segment_mask_in_volume(
@@ -53,9 +53,11 @@ def _predictor_and_segmenter(model: str, checkpoint: str, tiled: bool):
53
53
  mtime = Path(checkpoint).stat().st_mtime if checkpoint else None
54
54
  key = (model, checkpoint, mtime, tiled)
55
55
  if key not in _loaded:
56
- from micro_sam.automatic_segmentation import (
57
- get_predictor_and_segmenter,
58
- )
56
+ from .._microsam import sam1
57
+
58
+ get_predictor_and_segmenter = sam1(
59
+ "automatic_segmentation"
60
+ ).get_predictor_and_segmenter
59
61
 
60
62
  _loaded.clear()
61
63
  progress(f"Loading micro_sam {checkpoint or model}")
@@ -103,9 +105,11 @@ def microsam(
103
105
  model = checkpoint_model_type(checkpoint, model)
104
106
  predictor, segmenter = _predictor_and_segmenter(model, checkpoint, tile)
105
107
 
106
- from micro_sam.automatic_segmentation import (
107
- automatic_instance_segmentation,
108
- )
108
+ from .._microsam import sam1
109
+
110
+ automatic_instance_segmentation = sam1(
111
+ "automatic_segmentation"
112
+ ).automatic_instance_segmentation
109
113
 
110
114
  progress("Segmenting")
111
115
  labels = automatic_instance_segmentation(
@@ -0,0 +1,144 @@
1
+ """micro_sam 2 automatic instance segmentation: every object, no prompts.
2
+
3
+ The SAM2 twin of ``skop.ops.segment.microsam``. Its knobs are not micro_sam
4
+ 1's, hence an op of its own. Two engines, picked by the model:
5
+
6
+ * A finetuned model (``hvit_*_cells``, ``hvit_s_em_*``) has a decoder, and
7
+ runs micro_sam's "AIS": the decoder predicts foreground and boundaries, and
8
+ the AIS knobs turn those into objects. A knob left as None takes the
9
+ model's tuned default (micro_sam's ``DEFAULT_POSTPROCESSING``).
10
+ * A base SAM2 model (``hvit_t/s/b/l``, Meta's weights) has none, and runs
11
+ "AMG": a grid of point prompts, a mask per point, the good ones kept. It
12
+ segments anything object-like, including what the finetuning data left
13
+ unlabelled (e.g. the red blood cells of NeurIPS 2022).
14
+
15
+ Shares the 'pytorch' environment (0002), whose micro_sam 2 carries both.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import numpy as np
21
+ from opspec.op import op
22
+ from opspec.runtime import progress
23
+ from opspec.types import ImageOf, LabelsOf
24
+
25
+ from .microsam import _ndim
26
+
27
+ #: Finetuned micro_sam 2 models with a decoder, by what they were trained on.
28
+ MODELS = (
29
+ "hvit_t_cells",
30
+ "hvit_s_cells",
31
+ "hvit_b_cells",
32
+ "hvit_l_cells",
33
+ "hvit_s_em_mito",
34
+ "hvit_s_em_nuclei",
35
+ )
36
+
37
+ #: SAM2 itself, no decoder: these run AMG.
38
+ BASE_MODELS = ("hvit_t", "hvit_s", "hvit_b", "hvit_l")
39
+
40
+ #: One predictor and segmenter, for the settings last asked for.
41
+ _loaded: dict = {}
42
+
43
+
44
+ def _predictor_and_segmenter(model: str, mode: str, **amg):
45
+ key = (model, mode, tuple(sorted(amg.items())))
46
+ if key not in _loaded:
47
+ from micro_sam.v2.automatic_segmentation import (
48
+ get_predictor_and_segmenter,
49
+ )
50
+
51
+ _loaded.clear()
52
+ progress(f"Loading micro_sam 2 {model} ({mode})")
53
+ _loaded[key] = get_predictor_and_segmenter(
54
+ model_type=model, segmentation_mode=mode, **amg
55
+ )
56
+ return _loaded[key]
57
+
58
+
59
+ @op(env="pytorch")
60
+ def microsam2(
61
+ image: ImageOf[np.ndarray],
62
+ model: str = "hvit_t_cells",
63
+ foreground_threshold: float | None = None,
64
+ density_threshold: float | None = None,
65
+ min_size: int | None = None,
66
+ foreground_weight: float | None = None,
67
+ sigma: float | None = None,
68
+ n_iter: int | None = None,
69
+ dt: float | None = None,
70
+ pred_iou_thresh: float = 0.8,
71
+ stability_score_thresh: float = 0.85,
72
+ min_object_size: int = 0,
73
+ max_object_size: int | None = None,
74
+ tiled: bool | None = None,
75
+ ) -> LabelsOf[np.ndarray]:
76
+ """Find every object in *image* with micro_sam 2.
77
+
78
+ Args:
79
+ image: YX, YXC or ZYX.
80
+ model: A finetuned model (``hvit_t_cells`` ...), run with its decoder,
81
+ or a base SAM2 model (``hvit_b`` ...), run as AMG.
82
+ foreground_threshold: Decoder models. Lower finds more, and
83
+ fainter, objects.
84
+ density_threshold: Decoder models. Seeds need this much flow
85
+ converging on them; lower splits more.
86
+ min_size: Decoder models. Smallest object kept, in pixels.
87
+ foreground_weight: Decoder models. How much the foreground map
88
+ counts against the boundary map when splitting touching objects.
89
+ sigma, n_iter, dt: Decoder models. Smoothing, steps and step size of
90
+ the flow integration that groups pixels into objects.
91
+ pred_iou_thresh: Base models. Masks SAM2 scores lower are dropped.
92
+ stability_score_thresh: Base models. Masks that change shape with
93
+ the cut-off are dropped.
94
+ min_object_size, max_object_size: Base models. Object area limits,
95
+ in pixels; None for no upper limit.
96
+ tiled: Split the image into overlapping tiles. None: micro_sam's
97
+ choice (tiles above 768 px) for decoder models, untiled for base
98
+ models, where tile borders cut objects.
99
+
100
+ Returns:
101
+ A label image shaped like the image's spatial axes.
102
+ """
103
+ from micro_sam.v2.automatic_segmentation import (
104
+ automatic_instance_segmentation,
105
+ )
106
+
107
+ if model in BASE_MODELS:
108
+ predictor, segmenter = _predictor_and_segmenter(
109
+ model,
110
+ "amg",
111
+ pred_iou_thresh=pred_iou_thresh,
112
+ stability_score_thresh=stability_score_thresh,
113
+ )
114
+ knobs = {
115
+ "min_object_size": min_object_size,
116
+ "max_object_size": max_object_size,
117
+ }
118
+ tiled = bool(tiled)
119
+ else:
120
+ predictor, segmenter = _predictor_and_segmenter(model, "ais")
121
+ knobs = {
122
+ "foreground_threshold": foreground_threshold,
123
+ "density_threshold": density_threshold,
124
+ "min_size": min_size,
125
+ "foreground_weight": foreground_weight,
126
+ "sigma": sigma,
127
+ "n_iter": n_iter,
128
+ "dt": dt,
129
+ }
130
+ if tiled is False:
131
+ knobs.update(tile_shape=(0, 0), halo=(0, 0))
132
+
133
+ progress("Segmenting")
134
+ labels = automatic_instance_segmentation(
135
+ predictor=predictor,
136
+ segmenter=segmenter,
137
+ input_path=np.asarray(image),
138
+ ndim=_ndim(image.shape),
139
+ verbose=False,
140
+ **{k: v for k, v in knobs.items() if v is not None},
141
+ )
142
+ labels = np.asarray(labels)
143
+ progress(f"Found {len(np.unique(labels)) - 1} objects")
144
+ return labels.astype(np.uint32)
@@ -131,9 +131,12 @@ def train_microsam(
131
131
 
132
132
  import imageio.v3 as iio
133
133
  import torch
134
- from micro_sam import training as sam_training
135
134
  from torch_em.data import MinInstanceSampler
136
135
 
136
+ from .._microsam import sam1
137
+
138
+ sam_training = sam1("training")
139
+
137
140
  if len(images) != len(labels) or not images:
138
141
  raise ValueError(
139
142
  f"{len(images)} images and {len(labels)} labels: need equal, nonzero"
@@ -2,8 +2,8 @@
2
2
 
3
3
  The two-stage segmenter from docs/spec/workflow-ops.md, and the reason the
4
4
  detectors and mask detectors were built to share signatures in the first
5
- place. Any of the two detectors pairs with either of the two mask detectors,
6
- which is four segmenters from four ops -- and the point of the pairing is that
5
+ place. Any of the three detectors pairs with any of the three mask detectors,
6
+ which is nine segmenters from six ops -- and the point of the pairing is that
7
7
  they are genuinely different: the object-aware YOLO finds objects a
8
8
  photograph-trained SAM misses, and micro_sam draws cells that MobileSAM
9
9
  smears.
@@ -31,7 +31,9 @@ from opspec.runtime import progress, run
31
31
  from opspec.types import BoxesOf, ImageOf, MasksOf
32
32
  from skop.ops.detect.fastsam import fastsam
33
33
  from skop.ops.detect.object_aware_yolo import object_aware_yolo
34
+ from skop.ops.detect.yolo import yolo
34
35
  from skop.ops.mask.microsam import microsam_masks
36
+ from skop.ops.mask.microsam2 import microsam2_masks
35
37
  from skop.ops.mask.mobilesam import mobilesam_masks
36
38
 
37
39
 
@@ -58,12 +60,16 @@ def detect_then_mask(
58
60
  image: ImageOf[np.ndarray],
59
61
  detector: Annotated[
60
62
  Callable,
61
- Choices(object_aware_yolo=object_aware_yolo, fastsam=fastsam),
63
+ Choices(object_aware_yolo=object_aware_yolo, fastsam=fastsam, yolo=yolo),
62
64
  ] = object_aware_yolo,
63
65
  detector_args: Annotated[dict | None, ParamsFor("detector", binds="image")] = None,
64
66
  masker: Annotated[
65
67
  Callable,
66
- Choices(mobilesam=mobilesam_masks, microsam=microsam_masks),
68
+ Choices(
69
+ mobilesam=mobilesam_masks,
70
+ microsam=microsam_masks,
71
+ microsam2=microsam2_masks,
72
+ ),
67
73
  ] = mobilesam_masks,
68
74
  masker_args: Annotated[
69
75
  dict | None, ParamsFor("masker", binds=("image", "boxes"))
@@ -74,10 +80,12 @@ def detect_then_mask(
74
80
  Args:
75
81
  image: The image to segment.
76
82
  detector: Which op finds the bounding boxes. ``object_aware_yolo`` was
77
- trained on microscopy; ``fastsam`` is a general detector.
83
+ trained on microscopy; ``fastsam`` is a general detector;
84
+ ``yolo`` runs your own YOLO .pt checkpoint, tiled.
78
85
  detector_args: Settings for the chosen detector, minus the image.
79
86
  masker: Which op draws a mask inside each box. ``microsam`` is
80
- finetuned for microscopy and slower; ``mobilesam`` is the one the
87
+ finetuned for microscopy and slower; ``microsam2`` is its SAM2
88
+ successor, finetuned or plain; ``mobilesam`` is the one the
81
89
  object-aware detector was trained to pair with.
82
90
  masker_args: Settings for the chosen mask detector, minus the image
83
91
  and the boxes, which this workflow supplies.