scikit-ops 0.1.0.dev3__py3-none-any.whl → 0.1.0.dev5__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.dev3
3
+ Version: 0.1.0.dev5
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
@@ -29,9 +29,9 @@ Classifier: Topic :: Software Development :: Libraries :: Python Modules
29
29
  Classifier: Topic :: Utilities
30
30
  Requires-Python: >=3.10
31
31
  Requires-Dist: numpy
32
- Requires-Dist: ophelper==0.1.0.dev0
33
- Requires-Dist: oprunner==0.1.0.dev1
34
- Requires-Dist: opspec==0.1.0.dev0
32
+ Requires-Dist: ophelper<0.2,>=0.1.0.dev0
33
+ Requires-Dist: oprunner<0.2,>=0.1.0.dev2
34
+ Requires-Dist: opspec<0.2,>=0.1.0.dev0
35
35
  Description-Content-Type: text/markdown
36
36
 
37
37
  # scikit-ops
@@ -30,18 +30,22 @@ skop/ops/mask/__init__.py,sha256=hk0mQqFiypPG9ZucNuKfU1tjQkab5H5jRsG6kTuZx6s,138
30
30
  skop/ops/mask/_result.py,sha256=OtEe58jlYC88g-uTujypyUaMoucMDO_OT9VIhPGBkJk,1717
31
31
  skop/ops/mask/microsam.py,sha256=Rq3CxPKPu2gn-7w8PN1v3ow0yp41H_lc6U2rlV073yg,4670
32
32
  skop/ops/mask/mobilesam.py,sha256=PqiXvF0CrH4n7PnJPItXg_24PpMMw0JzRoqnzBu8FXk,7436
33
- skop/ops/segment/__init__.py,sha256=GblPOpbYOPKcTUZMP2X3VU8m3EMAuFMttEhicnlIw8E,667
33
+ skop/ops/prompt/__init__.py,sha256=uk3Bn0zgSBoI1ajorhXYD5p2t94hOfCP14tdITV00nA,678
34
+ skop/ops/prompt/microsam.py,sha256=B21jV2hz0xJtadHQyE7oR1AoW83eKveKrWb4cL2asts,6643
35
+ skop/ops/segment/__init__.py,sha256=YrhqQclX9BZOhVDL2JyflDI7u8xJhoQXVQAW35cX7xI,714
34
36
  skop/ops/segment/cellpose3.py,sha256=GxEAVOpAMYurYMcbTf5hMlzQDt0KgJq1qMPTxRFFF60,10375
35
37
  skop/ops/segment/cellpose4.py,sha256=y7g7ZXK0M8l11IJAPKJ-OtIZBrxWK5-mmNdJRUUMlqc,5149
36
38
  skop/ops/segment/instanseg.py,sha256=TvQbmwqDm4_pqBbQX6H1kYvKuNb5fdppxoIIJOK8G9M,6296
39
+ skop/ops/segment/microsam.py,sha256=JmXs0H3oNLmGqSQkojQoKvVgCSH0y0TfSobqbjgZmk4,4410
37
40
  skop/ops/segment/stardist2d.py,sha256=XSG4kabcfeY5fsQr1e3kYmGbkWOqyoTTyEp98MB679M,6605
38
41
  skop/ops/segment/starfun3d.py,sha256=03RB3QL59NkkbgVABXTf9_VKZ-1Li_wUeJFPFjTqeAQ,3417
39
42
  skop/ops/segment/unseg/__init__.py,sha256=nxfXLG3xmnL5zwAlUB7YPdFeLNQk5R6L8JZ8BQ3c1nk,5088
40
43
  skop/ops/segment/unseg/_algorithm.py,sha256=M1l3g8g7hBr3af9aEwLBvnUbo_PvikEoZHRNiED7mfA,68689
41
- skop/ops/train/__init__.py,sha256=7t5uGBng74lcxXlF1HUckE7bhGMk1KCbesjOlepnU3g,3047
44
+ skop/ops/train/__init__.py,sha256=KtM51FOiGn47yPtCG27PNkKLLvA7381FZ-XPzBngtq8,3106
42
45
  skop/ops/train/_util.py,sha256=xgQxx4PDBVODntPmmlNGQ65ICs8yAPKHQHHBHqFkg6I,6114
43
46
  skop/ops/train/cellpose3.py,sha256=uh1SI72eYwnmSQjo0jmKhlkTW3FE5MKTd_H9_6onwac,8482
44
47
  skop/ops/train/cellpose4.py,sha256=akcfij7wsR4kdqlw9AmBBZ5Jh3UCF6dMLSyUnxFhVYA,7212
48
+ skop/ops/train/microsam.py,sha256=J2CgZ7sg0lbdDemjpqzzobasMkl8y-cQDKM-66q6kpQ,7917
45
49
  skop/ops/train/stardist2d.py,sha256=dioZYyyw6coHoPLGWIBJxVIYmAHtOp6GjxsDkGDBCSQ,18876
46
50
  skop/ops/train/yolo.py,sha256=nof2iyvy79tIpYU15hqN5CRGIEuGmbAApX5Ma6jGMjI,20348
47
51
  skop/ops/workflows/__init__.py,sha256=7GyWvVd9hIuDhup-ElcIeinjoI6xAe_JLwS67UDsIZM,1934
@@ -60,7 +64,7 @@ skop/envs/segment-everything/pixi.toml,sha256=1EmfO-fL9bj6SH-RnxdZpGw75pXmx6-g4E
60
64
  skop/envs/skimage/pixi.toml,sha256=wAfyOSuvsUpmKIj_Hqk3ylxck_uh6wYeMZ2BTjoSBTI,1136
61
65
  skop/envs/stardist-tf/pixi.toml,sha256=oIY1XmErvbApe_pLGyQzzSf1K_RgN2rrgAvyVWYfKag,3487
62
66
  skop/envs/unseg-cv/pixi.toml,sha256=TwcYzpAnfBd5taAB0b-kRXBhbw5aXHoLzoKRaebvyDw,1065
63
- scikit_ops-0.1.0.dev3.dist-info/METADATA,sha256=ZbjL7LFHIKnwwg7NmiHNY5Ix4MRL7Oh7B02istNnaoc,1935
64
- scikit_ops-0.1.0.dev3.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
65
- scikit_ops-0.1.0.dev3.dist-info/entry_points.txt,sha256=0gDhmxYQNjvBwJO4L0Q2fB-5fIEBbRVUS5u5heCYulQ,43
66
- scikit_ops-0.1.0.dev3.dist-info/RECORD,,
67
+ scikit_ops-0.1.0.dev5.dist-info/METADATA,sha256=wyljm0eSNreHGGeiAZWbsOxhzFBfv91l3nxypC0qbyI,1950
68
+ scikit_ops-0.1.0.dev5.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
69
+ scikit_ops-0.1.0.dev5.dist-info/entry_points.txt,sha256=0gDhmxYQNjvBwJO4L0Q2fB-5fIEBbRVUS5u5heCYulQ,43
70
+ scikit_ops-0.1.0.dev5.dist-info/RECORD,,
@@ -0,0 +1,17 @@
1
+ """Prompted segmentation: the object under the user's clicks.
2
+
3
+ For interactive tools. A click costs milliseconds but the image's embedding
4
+ costs seconds, so a prompt op comes with an embed op, and the module keeps
5
+ the embeddings the embed op made in the worker, which lives as long as the
6
+ runner. ``microsam_embed`` once per image, then ``microsam_points`` per click.
7
+
8
+ Not ``skop.ops.mask``: those take a detector's boxes and return overlapping
9
+ masks for a workflow. These take a person's points and return the one object
10
+ they meant.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from .microsam import microsam_embed, microsam_points
16
+
17
+ __all__ = ["microsam_embed", "microsam_points"]
@@ -0,0 +1,194 @@
1
+ """Point-prompted micro_sam, embedding once per image.
2
+
3
+ Interactive SAM is two costs of very different size: an embedding per image
4
+ (seconds, more for a volume) and a prompt per click (milliseconds). So these
5
+ are two ops sharing one module, and the module keeps what the expensive one
6
+ made. The worker is long-lived -- one per environment for the runner's
7
+ lifetime -- so a module-level dict outlives every call, which is all the
8
+ "session" this needs (scikit-ops design 0019, "Embeddings are the other
9
+ occupant").
10
+
11
+ Three levels of reuse, cheapest first:
12
+
13
+ 1. In this worker's memory, keyed by the embedding path the caller passes.
14
+ A few are kept, so flipping between two slices and back costs nothing.
15
+ 2. On disk, as micro_sam's own zarr at that path. micro_sam stores a SHA1 of
16
+ the image beside it and refuses a zarr made from different pixels, so a
17
+ return visit -- even after napari restarts -- is a read, never a stale
18
+ answer.
19
+ 3. Recomputed, and saved to that path for next time.
20
+
21
+ Where embeddings live is the caller's project layout; the ops are only handed
22
+ a path. Uses micro_sam's public functions, not ``sam_annotator``, whose
23
+ ``__init__`` imports napari.
24
+
25
+ Shares the 'pytorch' environment (0002) with the other micro_sam ops.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from collections import OrderedDict
31
+
32
+ import numpy as np
33
+ from opspec.op import op
34
+ from opspec.runtime import progress
35
+ from opspec.types import ImageOf, LabelsOf, PointsOf
36
+
37
+ #: How many images' embeddings stay in memory. Enough to flip between a few
38
+ #: slices instantly; each is the encoder's output, tens of MB per plane.
39
+ KEEP_EMBEDDINGS = 3
40
+
41
+ #: One predictor, for the model last asked for. Another model replaces it.
42
+ _predictor: dict = {}
43
+ #: (embedding_path, model_type) -> (image shape, image embeddings)
44
+ _embeddings: OrderedDict = OrderedDict()
45
+
46
+
47
+ def _get_predictor(model_type: str):
48
+ if model_type not in _predictor:
49
+ from micro_sam.util import get_sam_model
50
+
51
+ _predictor.clear()
52
+ progress(f"Loading micro_sam model {model_type}")
53
+ _predictor[model_type] = get_sam_model(model_type=model_type)
54
+ return _predictor[model_type]
55
+
56
+
57
+ def _get_embeddings(image, embedding_path: str, model_type: str, ndim: int):
58
+ """This image's embeddings: from memory, from disk, or computed."""
59
+ key = (embedding_path or None, model_type)
60
+ held = _embeddings.get(key)
61
+ if key[0] is not None and held is not None and held[0] == image.shape:
62
+ _embeddings.move_to_end(key)
63
+ return held[1]
64
+
65
+ from micro_sam.util import precompute_image_embeddings
66
+
67
+ predictor = _get_predictor(model_type)
68
+ progress("Computing or loading image embeddings")
69
+ try:
70
+ embeddings = precompute_image_embeddings(
71
+ predictor,
72
+ image,
73
+ save_path=key[0],
74
+ ndim=ndim,
75
+ verbose=False,
76
+ )
77
+ except RuntimeError as e:
78
+ # A zarr at that path made from other pixels or another model. It is
79
+ # a cache, but someone else's files: compute without it rather than
80
+ # delete it.
81
+ if "Embeddings file" not in str(e):
82
+ raise
83
+ progress(f"Ignoring a mismatched embedding file: {e}")
84
+ embeddings = precompute_image_embeddings(
85
+ predictor, image, save_path=None, ndim=ndim, verbose=False
86
+ )
87
+
88
+ if key[0] is not None:
89
+ _embeddings[key] = (image.shape, embeddings)
90
+ while len(_embeddings) > KEEP_EMBEDDINGS:
91
+ _embeddings.popitem(last=False)
92
+ return embeddings
93
+
94
+
95
+ @op(env="pytorch")
96
+ def microsam_embed(
97
+ image: ImageOf[np.ndarray],
98
+ embedding_path: str = "",
99
+ model_type: str = "vit_b_lm",
100
+ ndim: int = 2,
101
+ ) -> int:
102
+ """Make *image*'s micro_sam embeddings ready for prompting.
103
+
104
+ Args:
105
+ image: 2-D (YX or YXC) or 3-D (ZYX) image to prompt later.
106
+ embedding_path: Zarr to load embeddings from, or save them to. Empty
107
+ keeps them in memory only, for this one call.
108
+ model_type: micro_sam checkpoint, e.g. ``vit_b_lm``.
109
+ ndim: 2 for an image, 3 for a volume.
110
+
111
+ Returns:
112
+ The number of images now held in memory.
113
+ """
114
+ _get_embeddings(image, embedding_path, model_type, ndim)
115
+ return len(_embeddings)
116
+
117
+
118
+ @op(env="pytorch")
119
+ def microsam_points(
120
+ image: ImageOf[np.ndarray],
121
+ points: PointsOf[np.ndarray],
122
+ point_labels: np.ndarray,
123
+ embedding_path: str = "",
124
+ model_type: str = "vit_b_lm",
125
+ ndim: int = 2,
126
+ volume: bool = True,
127
+ iou_threshold: float = 0.7,
128
+ box_extension: float = 0.5,
129
+ ) -> LabelsOf[np.ndarray]:
130
+ """Segment one object from point prompts.
131
+
132
+ Args:
133
+ image: As given to ``microsam_embed``.
134
+ points: (N, 2) as [y, x], or (N, 3) as [z, y, x] for a volume -- all
135
+ on the same z, the plane being clicked.
136
+ point_labels: (N,) 1 for a positive point, 0 for a negative one.
137
+ embedding_path, model_type, ndim: As given to ``microsam_embed``.
138
+ volume: For a volume, carry the object through z from the clicked
139
+ plane; otherwise segment that plane only.
140
+ iou_threshold, box_extension: micro_sam's settings for carrying an
141
+ object from one plane to the next.
142
+
143
+ Returns:
144
+ uint8 mask shaped like the image's spatial axes: 1 for the object.
145
+ """
146
+ points = np.asarray(points, dtype=float).reshape(len(points), -1)
147
+ labels = np.asarray(point_labels, dtype=int).reshape(-1)
148
+ spatial = image.shape[:ndim]
149
+ if len(points) == 0:
150
+ return np.zeros(spatial, dtype=np.uint8)
151
+
152
+ from micro_sam.prompt_based_segmentation import segment_from_points
153
+
154
+ predictor = _get_predictor(model_type)
155
+ embeddings = _get_embeddings(image, embedding_path, model_type, ndim)
156
+
157
+ if ndim == 3:
158
+ z = int(round(points[0][0]))
159
+ yx = points[:, 1:3]
160
+ else:
161
+ z = None
162
+ yx = points[:, 0:2]
163
+
164
+ plane = np.squeeze(
165
+ segment_from_points(
166
+ predictor, yx, labels, image_embeddings=embeddings, i=z
167
+ )
168
+ ).astype(np.uint8)
169
+
170
+ if ndim != 3:
171
+ return plane
172
+
173
+ seg = np.zeros(spatial, dtype=np.uint8)
174
+ seg[z] = plane
175
+ if not volume or not plane.any():
176
+ return seg
177
+
178
+ from micro_sam.multi_dimensional_segmentation import (
179
+ segment_mask_in_volume,
180
+ )
181
+
182
+ progress("Carrying the object through z")
183
+ seg, _ = segment_mask_in_volume(
184
+ seg,
185
+ predictor,
186
+ embeddings,
187
+ np.array([z]),
188
+ stop_lower=False,
189
+ stop_upper=False,
190
+ iou_threshold=iou_threshold,
191
+ projection="single_point",
192
+ box_extension=box_extension,
193
+ )
194
+ return np.asarray(seg).astype(np.uint8)
@@ -10,6 +10,7 @@ from __future__ import annotations
10
10
 
11
11
  from .cellpose4 import cellpose4
12
12
  from .cellpose3 import cellpose3
13
+ from .microsam import microsam
13
14
  from .stardist2d import stardist2d_fluo, stardist2d_he
14
15
  from .starfun3d import segment_nuclei
15
16
  from .unseg import unseg
@@ -17,6 +18,7 @@ from .unseg import unseg
17
18
  __all__ = [
18
19
  "cellpose4",
19
20
  "cellpose3",
21
+ "microsam",
20
22
  "segment_nuclei",
21
23
  "stardist2d_fluo",
22
24
  "stardist2d_he",
@@ -0,0 +1,127 @@
1
+ """micro_sam automatic instance segmentation: every object, no prompts.
2
+
3
+ The whole-image counterpart of ``skop.ops.prompt.microsam`` (clicks) and
4
+ ``skop.ops.mask.microsam`` (boxes). With a model that has micro_sam's
5
+ instance decoder -- ``vit_b_lm``, ``vit_l_lm``, ``vit_b_em_organelles`` and
6
+ anything ``skop.ops.train.microsam`` trained -- that is AIS, and fast; plain
7
+ ``vit_b`` has none and falls back to SAM's automatic mask generator, which
8
+ is slow.
9
+
10
+ Shares the 'pytorch' environment (0002), which carries micro_sam.
11
+
12
+ A trained checkpoint does not say which micro_sam model it was finetuned
13
+ from, and loading it needs that ``model_type``. So the trainer writes
14
+ ``skop_microsam.json`` beside ``best.pt``, and this reads it.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ from pathlib import Path
21
+ from typing import Annotated
22
+
23
+ import numpy as np
24
+ from opspec.op import op
25
+ from opspec.runtime import progress
26
+ from opspec.types import ImageOf, LabelsOf
27
+
28
+ #: The file, beside a trained best.pt, saying what it was finetuned from.
29
+ META = "skop_microsam.json"
30
+
31
+ #: One loaded model: (model_type, checkpoint, mtime, tiled) -> pair.
32
+ _loaded: dict = {}
33
+
34
+
35
+ def _ndim(shape) -> int:
36
+ """2 for YX or YXC, 3 for ZYX -- ai-lab's get_ndim rule."""
37
+ if len(shape) == 3 and shape[-1] < 5:
38
+ return 2
39
+ return len(shape)
40
+
41
+
42
+ def checkpoint_model_type(checkpoint: str, fallback: str) -> str:
43
+ """The micro_sam model a trained checkpoint was finetuned from."""
44
+ meta = Path(checkpoint).parent / META
45
+ try:
46
+ return json.loads(meta.read_text())["model_type"]
47
+ except (OSError, ValueError, KeyError):
48
+ return fallback
49
+
50
+
51
+ def _predictor_and_segmenter(model: str, checkpoint: str, tiled: bool):
52
+ checkpoint = checkpoint or None
53
+ mtime = Path(checkpoint).stat().st_mtime if checkpoint else None
54
+ key = (model, checkpoint, mtime, tiled)
55
+ if key not in _loaded:
56
+ from micro_sam.automatic_segmentation import (
57
+ get_predictor_and_segmenter,
58
+ )
59
+
60
+ _loaded.clear()
61
+ progress(f"Loading micro_sam {checkpoint or model}")
62
+ _loaded[key] = get_predictor_and_segmenter(
63
+ model_type=model, checkpoint=checkpoint, is_tiled=tiled
64
+ )
65
+ return _loaded[key]
66
+
67
+
68
+ @op(env="pytorch")
69
+ def microsam(
70
+ image: ImageOf[np.ndarray],
71
+ model: str = "vit_b_lm",
72
+ checkpoint: str = "",
73
+ tile: bool = False,
74
+ tile_size: Annotated[
75
+ int, {"widget_type": "SpinBox", "min": 64, "max": 4096, "step": 32}
76
+ ] = 384,
77
+ halo: Annotated[
78
+ int, {"widget_type": "SpinBox", "min": 0, "max": 512}
79
+ ] = 64,
80
+ foreground_threshold: float = 0.5,
81
+ center_distance_threshold: float = 0.5,
82
+ boundary_distance_threshold: float = 0.5,
83
+ ) -> LabelsOf[np.ndarray]:
84
+ """Find every object in *image* with micro_sam.
85
+
86
+ Args:
87
+ image: YX, YXC or ZYX.
88
+ model: micro_sam model, e.g. ``vit_b_lm``. With *checkpoint*, the one
89
+ it was finetuned from, unless the checkpoint's ``skop_microsam.json``
90
+ says otherwise.
91
+ checkpoint: A ``best.pt`` from ``train_microsam``, or empty for the
92
+ built-in *model*.
93
+ tile: Embed in tiles, for images too large for one pass.
94
+ tile_size, halo: Tile edge and overlap, in pixels.
95
+ foreground_threshold, center_distance_threshold,
96
+ boundary_distance_threshold: The instance decoder's settings.
97
+ Ignored by models without one.
98
+
99
+ Returns:
100
+ A label image shaped like the image's spatial axes.
101
+ """
102
+ if checkpoint:
103
+ model = checkpoint_model_type(checkpoint, model)
104
+ predictor, segmenter = _predictor_and_segmenter(model, checkpoint, tile)
105
+
106
+ from micro_sam.automatic_segmentation import (
107
+ automatic_instance_segmentation,
108
+ )
109
+
110
+ progress("Segmenting")
111
+ labels = automatic_instance_segmentation(
112
+ predictor=predictor,
113
+ segmenter=segmenter,
114
+ input_path=np.asarray(image),
115
+ ndim=_ndim(image.shape),
116
+ tile_shape=(tile_size, tile_size) if tile else None,
117
+ halo=(halo, halo) if tile else None,
118
+ verbose=False,
119
+ foreground_threshold=foreground_threshold,
120
+ center_distance_threshold=center_distance_threshold,
121
+ boundary_distance_threshold=boundary_distance_threshold,
122
+ )
123
+ labels = np.asarray(labels)
124
+ progress(f"Found {len(np.unique(labels)) - 1} objects")
125
+ return labels.astype(np.uint32)
126
+
127
+
@@ -21,12 +21,14 @@ import numpy as np
21
21
 
22
22
  from .cellpose4 import train_cellpose4
23
23
  from .cellpose3 import train_cellpose3
24
+ from .microsam import train_microsam
24
25
  from .stardist2d import receptive_field_stardist2d, train_stardist2d
25
26
  from .yolo import train_yolo
26
27
 
27
28
  __all__ = [
28
29
  "train_cellpose4",
29
30
  "train_cellpose3",
31
+ "train_microsam",
30
32
  "train_stardist2d",
31
33
  "train_yolo",
32
34
  "receptive_field_stardist2d",
@@ -0,0 +1,213 @@
1
+ """Finetune micro_sam, with its instance decoder, on your own patches.
2
+
3
+ Runs in the shared 'pytorch' environment, beside ``skop.ops.segment.microsam``,
4
+ which segments with what this trains.
5
+
6
+ Takes paths and returns a path, like every training op (design 0011). What
7
+ comes back is micro_sam's own layout, ``<model_dir>/checkpoints/<name>/best.pt``:
8
+ a **file inside a directory named for the model** -- neither Cellpose's bare
9
+ file nor StarDist's directory of weights. Beside it goes
10
+ ``skop_microsam.json``, recording the micro_sam model it was finetuned from.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from pathlib import Path
17
+ from typing import Annotated
18
+
19
+ import numpy as np
20
+
21
+ from opspec.op import op
22
+ from opspec.runtime import cancel_requested, progress
23
+ from skop.ops.segment.microsam import META, checkpoint_model_type
24
+
25
+
26
+ def _to_8bit(image: np.ndarray) -> np.ndarray:
27
+ """micro_sam trains on uint8. Grey only: a trailing RGB axis is averaged."""
28
+ image = np.asarray(image)
29
+ if image.ndim == 3 and image.shape[-1] in (3, 4):
30
+ image = image[..., :3].mean(axis=-1)
31
+ if image.dtype == np.uint8:
32
+ return image
33
+ low, high = float(image.min()), float(image.max())
34
+ if high <= low:
35
+ return np.zeros(image.shape, dtype=np.uint8)
36
+ if image.dtype.kind == "f" and low >= 0 and high <= 1:
37
+ return (image * 255).astype(np.uint8)
38
+ return (255 * (image - low) / (high - low)).astype(np.uint8)
39
+
40
+
41
+ class _Progress:
42
+ """micro_sam's ``pbar_signals``, as opspec progress, and cancel.
43
+
44
+ micro_sam drives a napari progress bar through three Qt signals; any
45
+ object with ``emit`` stands in. Raising from ``update`` is how Cancel
46
+ stops training: best.pt holds the best epoch so far.
47
+ """
48
+
49
+ class _Signal:
50
+ def __init__(self, fn):
51
+ self.emit = fn
52
+
53
+ def __init__(self, name: str):
54
+ self.name = name
55
+ self.total = None
56
+ self.done = 0
57
+ self.shown = -1
58
+ self.pbar_total = self._Signal(self._set_total)
59
+ self.pbar_update = self._Signal(self._update)
60
+ self.pbar_description = self._Signal(lambda text: None)
61
+
62
+ def _set_total(self, total):
63
+ self.total = int(total) if total else None
64
+
65
+ def _update(self, steps):
66
+ self.done += int(steps)
67
+ if cancel_requested():
68
+ raise RuntimeError("Training cancelled")
69
+ if not self.total:
70
+ return
71
+ percent = 5 * (20 * self.done // self.total) # in steps of 5%
72
+ if percent != self.shown:
73
+ self.shown = percent
74
+ progress(
75
+ f"Training {self.name}: {percent}%", self.done, self.total
76
+ )
77
+
78
+
79
+ @op(env="pytorch")
80
+ def train_microsam(
81
+ images: list[str],
82
+ labels: list[str],
83
+ model_dir: str,
84
+ name: str = "microsam_model",
85
+ model: str = "vit_b_lm",
86
+ initial_checkpoint: str = "",
87
+ epochs: Annotated[
88
+ int, {"widget_type": "SpinBox", "min": 1, "max": 5000}
89
+ ] = 100,
90
+ n_objects_per_batch: Annotated[
91
+ int, {"widget_type": "SpinBox", "min": 1, "max": 50}
92
+ ] = 5,
93
+ batch_size: Annotated[
94
+ int, {"widget_type": "SpinBox", "min": 1, "max": 64}
95
+ ] = 1,
96
+ learning_rate: float = 1e-5,
97
+ val_size: Annotated[
98
+ int, {"widget_type": "SpinBox", "min": 0, "max": 100}
99
+ ] = 2,
100
+ early_stopping: Annotated[
101
+ int, {"widget_type": "SpinBox", "min": 0, "max": 1000}
102
+ ] = 10,
103
+ ) -> str:
104
+ """Finetune micro_sam, with its instance decoder, on your patches.
105
+
106
+ Args:
107
+ images: Paths to the input patches. Grey or RGB (averaged to grey),
108
+ any dtype: they are scaled to uint8, which micro_sam trains on.
109
+ labels: Label patches; ``labels[k]`` is the truth for ``images[k]``.
110
+ model_dir: Where micro_sam writes ``checkpoints/<name>/`` and
111
+ ``logs/``.
112
+ name: The model's name, and its directory under ``checkpoints``.
113
+ model: micro_sam model to finetune. Ignored for weights when
114
+ *initial_checkpoint* is set, but still its architecture.
115
+ initial_checkpoint: A ``best.pt`` to continue from, or empty.
116
+ epochs: Passes over the training patches.
117
+ n_objects_per_batch: Objects sampled per patch for prompt training.
118
+ Lower uses less GPU memory.
119
+ batch_size: Patches per batch.
120
+ learning_rate: micro_sam's default for finetuning.
121
+ val_size: Pairs held out from the end for validation. With too few
122
+ pairs to spare, the training pairs validate as well.
123
+ early_stopping: Stop after this many epochs without improvement;
124
+ 0 never stops early.
125
+
126
+ Returns:
127
+ The path of the trained ``best.pt``.
128
+ """
129
+ import shutil
130
+ import tempfile
131
+
132
+ import imageio.v3 as iio
133
+ import torch
134
+ from micro_sam import training as sam_training
135
+ from torch_em.data import MinInstanceSampler
136
+
137
+ if len(images) != len(labels) or not images:
138
+ raise ValueError(
139
+ f"{len(images)} images and {len(labels)} labels: need equal, nonzero"
140
+ )
141
+ if initial_checkpoint:
142
+ model = checkpoint_model_type(initial_checkpoint, model)
143
+
144
+ work = Path(tempfile.mkdtemp(prefix="microsam_train_"))
145
+ try:
146
+ held = val_size if 0 < val_size < len(images) else 0
147
+ split = len(images) - held
148
+ sets = {"train": range(split), "val": range(split, len(images))}
149
+ if not held:
150
+ sets["val"] = sets["train"]
151
+
152
+ shapes = []
153
+ for part, indices in sets.items():
154
+ (work / part / "raw").mkdir(parents=True)
155
+ (work / part / "label").mkdir(parents=True)
156
+ for k in indices:
157
+ raw = _to_8bit(iio.imread(images[k]))
158
+ truth = np.asarray(iio.imread(labels[k])).astype(np.uint32)
159
+ if raw.shape != truth.shape:
160
+ raise ValueError(
161
+ f"{images[k]} is {raw.shape} but its labels are "
162
+ f"{truth.shape}"
163
+ )
164
+ shapes.append(raw.shape)
165
+ iio.imwrite(work / part / "raw" / f"{k:05d}.tif", raw)
166
+ iio.imwrite(work / part / "label" / f"{k:05d}.tif", truth)
167
+ patch_shape = tuple(int(s) for s in np.min(shapes, axis=0))
168
+
169
+ def loader(part):
170
+ return sam_training.default_sam_loader(
171
+ raw_paths=str(work / part / "raw"),
172
+ raw_key="*.tif",
173
+ label_paths=str(work / part / "label"),
174
+ label_key="*.tif",
175
+ with_segmentation_decoder=True,
176
+ patch_shape=patch_shape,
177
+ batch_size=batch_size,
178
+ shuffle=True,
179
+ raw_transform=sam_training.identity,
180
+ sampler=MinInstanceSampler(min_size=25),
181
+ )
182
+
183
+ device = "cuda" if torch.cuda.is_available() else "cpu"
184
+ progress(
185
+ f"Training {name} from {initial_checkpoint or model}: "
186
+ f"{split} train, {held} val, {epochs} epochs, on {device}",
187
+ 0,
188
+ epochs,
189
+ )
190
+ sam_training.train_sam(
191
+ name=name,
192
+ model_type=model,
193
+ train_loader=loader("train"),
194
+ val_loader=loader("val"),
195
+ n_epochs=epochs,
196
+ early_stopping=early_stopping or None,
197
+ n_objects_per_batch=n_objects_per_batch,
198
+ checkpoint_path=initial_checkpoint or None,
199
+ with_segmentation_decoder=True,
200
+ device=device,
201
+ lr=learning_rate,
202
+ save_root=model_dir,
203
+ pbar_signals=_Progress(name),
204
+ )
205
+ finally:
206
+ shutil.rmtree(work, ignore_errors=True)
207
+
208
+ best = Path(model_dir) / "checkpoints" / name / "best.pt"
209
+ if not best.is_file():
210
+ raise RuntimeError(f"micro_sam finished but wrote no {best}")
211
+ (best.parent / META).write_text(json.dumps({"model_type": model}))
212
+ progress(f"Saved {best}")
213
+ return str(best)