Skip to main content

synthseg-mlx

Segment brain MRI or CT with SynthSeg in native MLX. Includes cortical parcellation, structure volumes and QC scores.

PyPI Python License Apple Silicon Hugging Face MedMLX

SynthSeg cortical parcellation in axial and coronal brain MRI
Input Output
3D brain MRI or CT · NIfTI Brain labels, volumes and QC
Model Weights download Peak MLX memory Measured on
synthseg 424 MB 6.6 GB Apple M1 Max, 160×192×192 T1 MRI with cortical parcellation

Install

uv venv --python 3.13
source .venv/bin/activate
uv pip install "synthseg-mlx>=0.5.0"

Run

from synthseg_mlx import run

result = run(image_path="brain.nii.gz", output_dir="out")
print(result["outputs"]["mask"])

Weights download from MedMLX/synthseg-mlx on first use; medmlx setup synthseg downloads them ahead of time. For local weights, pass a folder containing synthseg_2.0.safetensors, synthseg_parc_2.0.safetensors and synthseg_qc_2.0.safetensors as weights_path. With parc=False, the parcellation checkpoint is not needed.

Inputs are resampled to 1 mm if any voxel size differs from 1 mm by more than 0.05 mm; otherwise the input grid is kept. The mask shares its grid with resampled_input.nii.gz.

Inputs and outputs

Argument Meaning
image_path One 3D brain MRI in NIfTI (.nii or .nii.gz) of any contrast and resolution, or a CT in Hounsfield units with ct=True
output_dir Directory for the outputs; created if missing
weights_path Optional folder of native safetensors files (see below)
ct False by default; True clips intensities to 0–80 before normalization
robust False by default; True runs the SynthSeg-robust cascade. Implies fast; cannot be combined with v1
fast False by default; True skips left/right averaging and per-class topology cleanup
v1 False by default; True uses SynthSeg 1.0 and omits total intracranial volume. Combines with fast
crop None by default; one or three sizes in voxels (RAS order, rounded up to multiples of 32) bounding the processed patch, as upstream --crop. It also replaces the 128-voxel minimum padding
parc True by default; False keeps plain cortex labels 3 and 42 in the mask and volumes
save_posteriors False by default; True also writes posteriors.nii.gz, as upstream --post
overwrite False by default; existing outputs are replaced only when True
precision "source-fp32" (default) keeps each variant's arithmetic; "compensated-fp32" uses compensated Metal operators for the standard model and smooths each prediction before averaging

Upstream turns parcellation off by default; this runner turns it on. parc=False skips loading and running the parcellation network. QC scores the same segmentation output with or without parc, unlike upstream's QC without --parc.

Images must be:

  • finite, non-constant and 3D, with at least three voxels per axis;
  • in millimeter or unspecified spatial units, with header voxel sizes that match the affine;
  • on orthogonal axes (rotation is fine).

A last axis of three voxels is rejected; four to ten voxels gives a warning, and padding can fail if that axis stays ten voxels or fewer after preprocessing.

Output File Content
mask mask.nii.gz int32 FreeSurfer labels; cortex replaced by Desikan-Killiany parcels 1001–1035 and 2001–2035 unless parc=False
resampled_input resampled_input.nii.gz The input on the mask's grid, or a copy when no resampling was needed
volumes volumes.csv Soft volumes in mm³; total intracranial volume comes first, except for v1
qc_scores qc.csv Eight regional QC scores from 0 to 1
posteriors posteriors.nii.gz float32 per-label probabilities on the mask's grid; only with save_posteriors=True

run returns {"outputs": {...}, "artifacts": {...}, "details": {...}}. artifacts describes each file by role (the mask as a label map with its label names), and details holds run metadata.

Error Raised when
InvalidInputError Images, options or existing outputs are invalid
AssetNotReadyError Checkpoints are missing or incompatible
ModelExecutionError The written files fail the output checks

Local weights

Download the converted SynthSeg weights and run:

from huggingface_hub import snapshot_download
from synthseg_mlx import run

weights = snapshot_download(
    "MedMLX/synthseg-mlx",
    revision="b4fa99020571cd5921f2205834dd5028fa804046",
    allow_patterns=["synthseg_2.0.safetensors", "synthseg_parc_2.0.safetensors",
                    "synthseg_qc_2.0.safetensors"],
)
result = run(image_path="brain.nii.gz", weights_path=weights, output_dir="out")
print(result["outputs"]["mask"])
Variant Segmentation file
robust synthseg_robust_2.0.safetensors
v1, with or without fast synthseg_1.0.safetensors
Any other run synthseg_2.0.safetensors

Every variant also needs synthseg_qc_2.0.safetensors; synthseg_parc_2.0.safetensors is needed only with parc=True.

Python API

The array functions read and write no files. Load the image yourself and pass the loader's squeezed array (loaded_image), affine and voxel sizes (image_resolution) without recasting; models_dir is the weights folder as a Path.

import numpy as np
from synthseg_mlx import (
    SynthSegModel, SynthSegVariant, get_flip_indices, load_label_data, postprocess_arrays,
    predict_numpy, preprocess, qc_scores,
)

variant = SynthSegVariant.STANDARD  # or FAST, ROBUST, V1, V1_FAST
options = dict(robust=variant.robust, fast=variant.fast, v1=variant.v1)
assets = load_label_data(v1=variant.v1, robust=variant.robust)
if variant.fast:
    labels_segmentation, unique_idx = np.unique(assets["segmentation"], return_index=True)
    flip_indices = None
else:
    labels_segmentation, flip_indices, unique_idx = get_flip_indices(
        assets["segmentation"], variant.neutral_labels,
    )
labels_parcellation = np.unique(assets["parcellation"])

model = SynthSegModel.from_safetensors(
    models_dir / variant.segmentation_checkpoint, labels_segmentation,
    models_dir / "synthseg_parc_2.0.safetensors", labels_parcellation,
    models_dir / "synthseg_qc_2.0.safetensors", assets["qc"][unique_idx], flip_indices,
    labels_denoiser=np.unique(assets["denoiser"]) if variant.robust else None,
    **options,
)
image, affine, image_resolution, shape, pad_idx, crop_idx = preprocess(
    loaded_image, affine, image_resolution, ct=False, crop=None, min_pad=128,
)
segmentation, parcellation, raw_qc = predict_numpy(model, image)
label_map, posteriors, volumes = postprocess_arrays(
    segmentation, parcellation, shape=shape, pad_idx=pad_idx, crop_idx=crop_idx,
    labels_segmentation=labels_segmentation, labels_parcellation=labels_parcellation,
    affine=affine, image_resolution=image_resolution,
    topology_classes=assets["topology_classes"][unique_idx], **options,
)
quality = qc_scores(raw_qc, **options)
  • Pass the same variant flags to loading, the model, postprocessing and qc_scores.
  • preprocess keeps upstream resampling, RAS alignment, cropping, CT clipping, normalization and padding. An optional on_resample(image, affine) hook sees the resampled image.
  • predict_numpy takes a padded, normalized NDHWC volume whose spatial sizes are divisible by 16.
  • postprocess keeps the upstream parameter names and, like upstream, modifies its parcellation input.

Use with MedMLX

Use the MedMLX MCP server to run synthseg 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 synthseg.

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.

Metadata

Release files for synthseg-mlx 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for synthseg-mlx 0.5.0
File Size Uploaded Provenance Actions
synthseg_mlx-0.5.0.tar.gz 64.8 kB Without provenance Details for synthseg_mlx-0.5.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for synthseg-mlx 0.5.0
File Interpreter ABI Platform Actions
synthseg_mlx-0.5.0-py3-none-any.whl Python 3 none any Details for synthseg_mlx-0.5.0-py3-none-any.whl

Total release size: 142.9 kB

Release files / synthseg_mlx-0.5.0.tar.gz

Download URL synthseg_mlx-0.5.0.tar.gz
Size 64.8 kB
Tags Source
SHA-256 checksum
How to use checksums
9535e69d04cfe5ad960d30ef70e5b9ae65fc9a005f368e3dcdfe96b987d21a08
BLAKE2b-256 checksum
How to use checksums
4d5c15f024fc26e848069b83eea12e8d94032ad57a54046358dae8c6aa12e571
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 / synthseg_mlx-0.5.0-py3-none-any.whl

Download URL synthseg_mlx-0.5.0-py3-none-any.whl
Size 78.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
87509acf038e6c2b0eeba60e15018916254b1c922d247655d846fbb45b36a6c1
BLAKE2b-256 checksum
How to use checksums
5cbc27c5f2424cc27ccde7c93da063df40b0efc3f20256e9661c2625af532967
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 synthseg-mlx 0.5.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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page