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 11.6 GB 160×192×192 T1 MRI with cortical parcellation

Install

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

Run

from synthseg_mlx import run

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

Omitting weights_path downloads MedMLX/synthseg-mlx into the shared MedMLX cache on first use; with MedMLX installed, medmlx setup synthseg downloads it ahead of time. To use your own copy, 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 millimetre 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

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.
  • Inference requires Apple Silicon with Metal.

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.4.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.4.0
File Size Uploaded Provenance Actions
synthseg_mlx-0.4.0.tar.gz 65.8 kB Without provenance Details for synthseg_mlx-0.4.0.tar.gz

Built distribution (wheel)

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

Total release size: 144.9 kB

Release files / synthseg_mlx-0.4.0.tar.gz

Download URL synthseg_mlx-0.4.0.tar.gz
Size 65.8 kB
Tags Source
SHA-256 checksum
How to use checksums
e2c0046eb0d2b3ef7ae31f929e7f02ac04850ce7b7fd0a72b39998b5b255b5f1
BLAKE2b-256 checksum
How to use checksums
1f09a619ecb6c05b2cfeff3605f2b7925c0a7f43a2638b63939bc10191bdfb88
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.4.0-py3-none-any.whl

Download URL synthseg_mlx-0.4.0-py3-none-any.whl
Size 79.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0ec550a2146a3da06ddf2fb64635901be3b5a86fb53dd029ec2e230a32cb7dd1
BLAKE2b-256 checksum
How to use checksums
a2c89f8084e8cbf47793f07f7efddafadf2933add60df0e244847bc8fd1b69da
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.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.

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