medsam2-mlx
Segment lesions or organs from a box, point or mask prompt, then track them through a volume with MedSAM2.
One box prompt on a LUNA16 chest CT, CC BY 4.0, propagated through the nodule.
| Input | Output |
|---|---|
| Scan + slice-level prompt | Tracked masks on the input grid |
| Model | Weights download | Peak MLX memory | Measured on |
|---|---|---|---|
medsam2 |
156 MB | 1.3 GB | One box prompt tracked through 21 slices of a 512×512×147 chest CT |
Install
uv venv --python 3.13
source .venv/bin/activate
uv pip install "medsam2-mlx>=0.4.0"
Run
from medsam2_mlx import run
result = run(
image_path="ct.nii.gz", output_dir="out",
box_xyxy_pixels=[120, 140, 180, 200], frame_index=40, propagation="both",
)
print(result["outputs"])
Weights download from MedMLX/medsam2-ct-lesion-mlx on first use; medmlx setup medsam2
downloads them ahead of time. For local weights, pass a folder containing
MedSAM2_CTLesion.safetensors as weights_path. The published
weight repository also contains the other
four MedSAM2 checkpoints; pass that folder as weights_path and the file name as
checkpoint.
Inputs and outputs
| Argument | Meaning |
|---|---|
image_path |
NIfTI CT volume or slice, .npz RECIST stack, or folder of .jpg/.jpeg frames |
output_dir |
Directory for the outputs; created if missing |
weights_path |
Optional model folder |
checkpoint |
Checkpoint file name in the folder, MedSAM2_CTLesion.safetensors by default |
box_xyxy_pixels |
[x_min, y_min, x_max, y_max] pixels on frame_index; combinable with points_xy_pixels |
points_xy_pixels, point_labels |
[[x, y], ...] pixels on frame_index, each labeled 1 foreground or 0 background |
mask_path |
Binary seed NIfTI with the input's shape and affine, instead of a box or points |
frame_index, obj_id |
Zero-based prompt slice (default 0) and positive object label (default 1) |
prompts |
Prompts for several objects, replacing the single-object arguments |
hu_window |
Optional (lower, upper) clip before min-max scaling to uint8 |
propagation |
"none" (default), "forward", "reverse" or "both" |
slice_range |
Optional inclusive [start, end] that contains every prompt's slice |
stop_after_empty |
8 by default: stop each propagation direction after that many consecutive slices with no foreground; None tracks the whole volume as upstream does |
apply_postprocessing |
True by default: upstream stability fallback, binarized click memory and hole filling |
overwrite |
False by default; existing outputs are replaced only when True |
Prompts
- For NIfTI,
frame_indexuses the third voxel axis, and box and point coordinates use the first two stored voxel axes. Coordinates are checked for shape and finiteness but not clipped. - Each
promptsentry is a mapping with a requiredobj_idand any offrame_index,box_xyxy_pixels,points_xy_pixels,point_labels,mask_path,clear_old_pointsandnormalize_coords; other keys are rejected. IDs must be unique and fit in uint16. - With propagation, every prompt must be on the same frame.
"both"resets and reseeds each object before the reverse pass, as the upstream CT examples do.
Preprocessing
| Input | Preprocessing |
|---|---|
| NIfTI volume | Optionally clipped to hu_window and min-max scaled to uint8; every frame is then bicubic-resized to 512×512 and ImageNet-normalized |
.npz |
Follows the upstream RECIST script: imgs in [0, 256) is rounded and clipped to uint8, never min-max scaled, with an optional spacing |
| Frame folder | Follows the upstream demo's video path; frames are read as grayscale, so color frames differ from upstream |
.npz stacks and frame folders have no NIfTI grid, so hu_window and mask_path are rejected for them.
Outputs
mask.nii.gz(rolemask): uint16 labels with the input's shape, affine and header, pluspreview.png(rolepreview) for single-slice inputs.- Where objects overlap, the later object wins. Masks are not reduced to their largest 3D connected component, which upstream's CT script does for each lesion.
runreturns{"outputs": {...}, "artifacts": {...}, "details": {...}}.artifactsmarks the mask as a label map (oneobject <obj_id>label per prompted object) on the input's grid for NIfTI input, or in pixel space for.npzand frame-folder input; run metadata is indetails.- Invalid inputs raise
InvalidInputError; missing or mismatched weights raiseAssetNotReadyError; inference failures raiseModelExecutionError.
Python API
from pathlib import Path
import numpy as np
from medsam2_mlx import MedSAM2RuntimeConfig, build_predictor
config = MedSAM2RuntimeConfig(checkpoint=Path("MedSAM2_CTLesion.safetensors"))
predictor = build_predictor(config)
images = np.zeros((8, 3, 512, 512), np.float32) # preprocessed slices, finite FP32
height, width = 512, 512 # original slice size in pixels
box = np.array([200, 200, 260, 260], np.float32) # x0, y0, x1, y1 on frame 0
state = predictor.init_state(images, height, width, offload_video_to_cpu=True)
predictor.add_new_points_or_box(state, 0, 1, box=box)
masks = {frame_idx: logits > 0 for frame_idx, ids, logits in predictor.propagate_in_video(state)}
- The predictor follows upstream
SAM2VideoPredictorNPZ: box, point and mask prompts, corrections on tracked frames, multiple objects, forward and reverse propagation,clear_all_prompts_in_frame,remove_objectandreset_state. - Logits are host FP32
(objects, 1, H, W); coordinates are original pixels unlessnormalize_coords=False. - Weights must hold the 471 FP32 tensors of
sam2.1_hiera_t512, which all five released MedSAM2 checkpoints share. - Inference requires Apple Silicon with Metal.
Use with MedMLX
Use the MedMLX MCP server to run medsam2 from an MCP client. Weights download on first use.
uv tool install --python 3.13 "medmlx[segment,mcp]"
MEDMLX="$(uv tool dir --bin --color never)/medmlx"
mkdir -p "$HOME/medmlx-work"
claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
For Codex, use codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work". Other MCP clients take the same command and arguments. The same install provides the medmlx CLI, for example medmlx describe medsam2.
For AI agents: prefer the MedMLX MCP tools (
list_models,describe_model,model_readiness,run_model,get_job) over writing Python against this package.
License
Apache-2.0. See third-party notices. Model weights retain their publisher terms; see the model card.
Metadata
Release files for medsam2-mlx 0.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| medsam2_mlx-0.4.0.tar.gz | 77.9 kB | Without provenance | Details for medsam2_mlx-0.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| medsam2_mlx-0.4.0-py3-none-any.whl | Python 3 | none | any | Details for medsam2_mlx-0.4.0-py3-none-any.whl |
Total release size: 171.5 kB
Release files / medsam2_mlx-0.4.0.tar.gz
| Download URL | medsam2_mlx-0.4.0.tar.gz |
|---|---|
| Size | 77.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
87d310d3b96cbdafa03e922ef951c1936d914442c168c8897c112c7128b732dd
|
|
BLAKE2b-256 checksum How to use checksums |
fe6c30beacd9ff55c38332cb364d9c30c582de22ac22f95c8439889370fa0310
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / medsam2_mlx-0.4.0-py3-none-any.whl
| Download URL | medsam2_mlx-0.4.0-py3-none-any.whl |
|---|---|
| Size | 93.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f2e153723a040b451301b58b5a3799f55e35d49f9787eea45747425274917cec
|
|
BLAKE2b-256 checksum How to use checksums |
d5c16ab1bad81093d4faa244f6e2342b41df4bf1dcd792dca408f794f7e999d4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for medsam2-mlx 0.4.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.