Skip to main content

niitools

NeuroImaging Informatics Tools — Extract and aggregate brain segmentation statistics from FastSurfer outputs

Python Version License: MIT

Overview

niitools is a Python package designed to streamline the extraction and aggregation of neuroimaging statistics from FastSurfer brain segmentation outputs. It processes multiple subjects at scale and generates publication-ready CSV and Excel reports for four key neuroimaging metrics:

  • Cortical Thickness — Average thickness across cortical regions (left & right hemispheres)
  • Subcortical Segmentation — Volumes of subcortical structures (Aseg)
  • Brain Stem Analysis — Volumetric measurements of brain stem components
  • Cerebellar Segmentation — Cerebellar structure volumes via CerebNet

Perfect for neuroimaging research pipelines, clinical studies, and batch processing of brain MRI analysis outputs.


✨ Features

  • 🚀 Batch Processing — Process hundreds of subjects in a single command
  • 📊 Multi-Format Output — Generate both CSV and Excel files with automatic formatting
  • 🧠 Four Analysis Modules — Comprehensive coverage of cortical, subcortical, brainstem, and cerebellar metrics
  • 🔄 Flexible API — Use as a command-line tool or import as a Python library
  • 📝 Logging Support — Detailed logging with loguru for debugging and audit trails
  • ✅ Validation — Automatic validation of FastSurfer output directory structure

📦 Installation

git clone https://github.com/diogohs/niitools.git
cd niitools
pip install -e .

This installs the package in editable mode and registers the niitools command-line tool.

From PyPI

pip install niitools

Requirements

  • Python: 3.8 or higher
  • Dependencies:
    • pandas>=2.0.3 — Data manipulation and analysis
    • openpyxl>=3.1.5 — Excel file generation
    • loguru>=0.7.3 — Advanced logging

🚀 Quick Start

Command-Line Usage

Extract FastSurfer statistics from all subjects in a directory:

niitools fastsurfer -i ./data/input -o ./data/output

Arguments:

  • -i, --input (required) — Path to directory containing FastSurfer output directories
  • -o, --output (required) — Path to output directory for CSV and Excel files

Example:

niitools fastsurfer -i /mri_data/fastsurfer_results -o /mri_data/statistics

Python Library Usage

Import and use niitools in your Python scripts:

from pathlib import Path
from niitools.fastsurfer import run_fastsurfer

# Define input and output paths
input_dir = Path("./data/input")
output_dir = Path("./data/output")

# Run the analysis
run_fastsurfer(input_dir, output_dir)

The function will:

  1. Scan the input directory for valid FastSurfer output structures
  2. Extract statistics from each subject
  3. Aggregate results across all subjects
  4. Generate both CSV and Excel output files

📋 Output Files

The analysis generates 8 output files (4 metrics × 2 formats):

Files Generated

Metric CSV File Excel File
Cortical Thickness (Left) FastSurfer_Cortical_Thickness_left.csv FastSurfer_Cortical_Thickness_left.xlsx
Cortical Thickness (Right) FastSurfer_Cortical_Thickness_right.csv FastSurfer_Cortical_Thickness_right.xlsx
Subcortical (Aseg) FastSurfer_Aseg.csv FastSurfer_Aseg.xlsx
Brain Stem FastSurfer_BrainStem.csv FastSurfer_BrainStem.xlsx
Cerebellar (CerebNet) FastSurfer_CerebNet.csv FastSurfer_CerebNet.xlsx

Output Structure

Each output file contains:

  • Subject Column — Subject identifier in the first column
  • Region Columns — One column per brain region with extracted metrics
  • One Row per Subject — Aggregated statistics for each subject

🏗️ Project Structure

niitools/
├── niitools/
│   ├── __init__.py              # Package initialization
│   ├── __main__.py              # CLI entry point
│   ├── validate.py              # Validation utilities
│   ├── utils.py                 # Helper functions
│   └── fastsurfer/
│       ├── __init__.py          # Module exports
│       ├── _executor.py         # Main execution logic
│       ├── aseg.py              # Subcortical segmentation parsing
│       ├── brainstem.py         # Brain stem parsing
│       ├── cerebnet.py          # Cerebellar segmentation parsing
│       └── cortical.py          # Cortical thickness parsing
├── tests/
│   ├── __init__.py
│   └── test_converter.py        # Unit tests
├── notebooks/                   # Jupyter notebooks with examples
├── data/
│   ├── input/                   # FastSurfer outputs (input)
│   └── output/                  # Generated statistics (output)
├── pyproject.toml               # Project configuration
├── README.md                    # This file
└── LICENSE                      # MIT License

📚 Advanced Usage

Processing with Custom Logging

from pathlib import Path
from loguru import logger
from niitools.fastsurfer import run_fastsurfer

# Configure logging
logger.add("niitools_processing.log", level="DEBUG")

# Run with logging enabled
run_fastsurfer(Path("./input"), Path("./output"))

Validating FastSurfer Directories

from pathlib import Path
from niitools.validate import is_fastsurfer_output

subject_dir = Path("./data/SUBJECT_001")
if is_fastsurfer_output(subject_dir):
    print("Valid FastSurfer output structure!")
else:
    print("Missing required subdirectories")

⚙️ FastSurfer Output Requirements

niitools expects standard FastSurfer output directories with the following structure:

SUBJECT_ID/
├── label/          # Brain region labels
├── mri/            # MRI volumes and brain stem outputs
├── scripts/        # FastSurfer processing scripts
├── stats/          # Statistical output files
└── surf/           # Surface files

Ensure your FastSurfer output contains these required files:

  • stats/aseg.stats — Subcortical segmentation statistics
  • stats/cerebellum.CerebNet.stats — Cerebellar segmentation
  • stats/lh.aparc.DKTatlas.mapped.stats — Left hemisphere cortical thickness
  • stats/rh.aparc.DKTatlas.mapped.stats — Right hemisphere cortical thickness
  • mri/brainstemSsLabels.volumes.txt — Brain stem volumes

🐛 Troubleshooting

No subjects found

⚠️  No valid FastSurfer output directories found in {input_dir}

Solution: Verify that input directories contain the required FastSurfer subdirectories (label, mri, scripts, stats, surf).

Missing statistics files

⚠️  Missing required statistics file

Solution: Ensure FastSurfer processing completed successfully and generated all required output files.

Python version incompatibility

ERROR: This package requires Python 3.8 or higher

Solution: Upgrade Python: python --version should return 3.8+


🤝 Contributing

Contributions are welcome! Please feel free to:

  • Report bugs via GitHub Issues
  • Submit pull requests for improvements
  • Suggest new features or analysis modules

📄 License

This project is licensed under the MIT License — see the LICENSE file for details.


Develop

uv pip install -e .
niitools fastsurfer -i data\input -o data\output

Metadata

Release files for niitools 0.0.6

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

Source distribution (sdist)

Source distribution for niitools 0.0.6
File Size Uploaded Provenance Actions
niitools-0.0.6.tar.gz 12.8 kB With provenance Details for niitools-0.0.6.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for niitools 0.0.6
File Interpreter ABI Platform Actions
niitools-0.0.6-py3-none-any.whl Python 3 none any Details for niitools-0.0.6-py3-none-any.whl

Total release size: 26.4 kB

Release files / niitools-0.0.6.tar.gz

Download URL niitools-0.0.6.tar.gz
Size 12.8 kB
Tags Source
SHA-256 checksum
How to use checksums
015f515f4aa476a28940d2e2e898c415c8b636ca7d363950ec78f9d1240321e5
BLAKE2b-256 checksum
How to use checksums
03d48ec01818275288b3cbd0e321d262286e5112c0cbc578144b0f6727953c24
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jul 17, 2026.

Transparency log

Release files / niitools-0.0.6-py3-none-any.whl

Download URL niitools-0.0.6-py3-none-any.whl
Size 13.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5dc7c06c6b81e12c32e91c9eb25f4548e30054ff03689d6361df761937c68412
BLAKE2b-256 checksum
How to use checksums
a42716256f1571764f1344bc30ab7b286fb42ff5488ea6fd8739d41f016d8007
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jul 17, 2026.

Transparency log

Security for niitools 0.0.6

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for niitools-0.0.6.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jul 17, 2026.

Transparency log

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