Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

NiiVue Streamlit Component

A modern Streamlit component for visualizing neuroimaging data using NiiVue, built with TypeScript, Preact, and Vite.

🚀 Quick Start

Simple Installation & Usage

  1. Install the component:

    pip install niivue-streamlit
    
  2. Use in your Streamlit app:

    import streamlit as st
    from niivue_component import niivue_viewer
    
    uploaded_file = st.file_uploader("Choose a NIFTI file", type=["nii", "nii.gz"])
    
    if uploaded_file is not None:
        result = niivue_viewer(
            nifti_data=uploaded_file.getvalue(),
            filename=uploaded_file.name,
            height=700
        )
    
        # Handle click events
        if result:
            st.write(f"Clicked voxel: {result['voxel']}, Value: {result['value']}")
    

✨ Features

  • 🎨 Two Component Modes:
    • StyledViewer: Full-featured viewer with interactive menu and controls
    • UnstyledCanvas: Minimal canvas-only viewer for embedding
  • 🔄 Multiple View Modes:
    • Axial, Coronal, Sagittal slices
    • 3D render view
    • Multiplanar view with render
  • 📊 Advanced Capabilities:
    • Multiple overlay images with custom colormaps
    • Surface mesh rendering (FreeSurfer pial, white, inflated, GIfTI, STL, OBJ, etc.)
    • Mesh overlays (curvature, thickness, annotations)
    • Combined volume + mesh visualization
    • Configurable display settings (crosshair, radiological convention, colorbar, interpolation)
    • Bidirectional communication (click events from viewer to Python)
    • DICOM support

📖 Advanced Usage

With Overlays

from niivue_component import niivue_viewer

result = niivue_viewer(
    nifti_data=main_image_bytes,
    filename="brain.nii.gz",
    overlays=[
        {
            "data": overlay_bytes,
            "name": "activation.nii.gz",
            "colormap": "hot",
            "opacity": 0.7
        }
    ],
    view_mode="multiplanar",
    styled=True,
    settings={
        "crosshair": True,
        "radiological": False,
        "colorbar": True,
        "interpolation": True
    },
    height=800
)

With Mesh Surfaces

from niivue_component import niivue_viewer

# Load a FreeSurfer surface mesh
mesh_data = open("lh.pial", "rb").read()

result = niivue_viewer(
    meshes=[{
        "data": mesh_data,
        "name": "lh.pial",
    }],
    view_mode="3d",
    height=700
)

Mesh with Overlays (Curvature, Thickness)

mesh_data = open("lh.pial", "rb").read()
thickness_data = open("lh.thickness", "rb").read()

result = niivue_viewer(
    meshes=[{
        "data": mesh_data,
        "name": "lh.pial",
        "overlays": [{
            "data": thickness_data,
            "name": "lh.thickness",
            "colormap": "redyell",
            "opacity": 0.7
        }]
    }],
    view_mode="3d",
    height=700
)

Volume with Mesh

# Display a volume image alongside a surface mesh
volume_data = open("brain.nii.gz", "rb").read()
mesh_data = open("lh.pial", "rb").read()

result = niivue_viewer(
    nifti_data=volume_data,
    filename="brain.nii.gz",
    meshes=[{
        "data": mesh_data,
        "name": "lh.pial",
    }],
    view_mode="3d",
    height=700
)

Minimal Viewer (No Menu)

# Perfect for embedding in complex layouts
result = niivue_viewer(
    nifti_data=image_bytes,
    filename="scan.nii",
    styled=False,  # Hide menu
    view_mode="axial",
    height=400
)

Scene Documents (NVDocument)

A NiiVue scene document (.nvd, or .nvd.json) restores images together with their display settings and the view. Pass it like an image; the file name tells the viewer it is a scene:

scene = Path("brain.nvd").read_bytes()
niivue_viewer(nifti_data=scene, filename="brain.nvd")

In the styled viewer, NVDocument saves the scene as a download, and NVDocument > Load opens a scene document from disk.

Waiting for the Image to Load

With load_events=True, the viewer tells Python when loading has finished: base_loaded once the main image (or first mesh) is shown, then fully_loaded once every overlay and mesh passed with it has loaded too. Use it to start a timer or a next step only once the image is visible.

event = niivue_viewer(
    nifti_data=image,
    filename=f"{subject}_T1w.nii.gz",
    overlays=[{"data": mask, "name": "mask.nii.gz"}],
    load_events=True,
    update_interval_ms=None,  # no click events, only load events
    key=f"viewer-{subject}",
)
if event and event["type"] in ("base_loaded", "fully_loaded"):
    st.session_state.setdefault(f"shown-{subject}", time.time())

Each event re-runs the script, like a click. The return value only holds the latest event and keeps it across re-runs: a new key per image starts from None, so a value never belongs to the previous image. When there is nothing more to load, fully_loaded follows right after base_loaded, and the script may only see the later one, so accept either as "shown". fully_loaded is sent again when new overlays or meshes are loaded for the same image, for example when a slider sets an overlay's opacity.

If the main image fails to load, the viewer sends load_error instead, with the message in error, and no other event for that image. An overlay or mesh that fails to load still ends in fully_loaded; its error goes to the browser console.

Because every event re-runs the script, pass the same arguments on each run. Image bytes rebuilt on every run (a freshly written .nii.gz carries a new timestamp) count as a new image, which loads and sends an event again, without end. Cache them, for example with st.cache_data.

⚡ Performance

Because Streamlit re-runs the whole script whenever a component calls Streamlit.setComponentValue, bidirectional click feedback from the viewer can become a bottleneck: without care, every mouse event re-reads the file, re-base64-encodes the NIfTI, and re-transmits it to the iframe. Three knobs keep the viewer snappy:

  1. @st.fragment — wrap the viewer plus the UI that consumes its return value in a fragment. Clicks re-run only the fragment, not the whole page. See app_bidirectional.py.
  2. @st.cache_data — cache Path.read_bytes() so the same bytes aren't re-loaded on every re-run. The component wrapper also caches the base64 encoding internally, keyed on the bytes object's identity, so caching your loader transparently skips re-encoding too.
  3. update_interval_ms — controls the throttle on click events sent back to Python (default 100 ms). Pass None to disable feedback entirely when the return value isn't used (e.g. app_simple.py, app_overlay.py, app_advanced.py).

Minimal template:

import streamlit as st
from niivue_component import niivue_viewer
from pathlib import Path

@st.cache_data
def load_nifti(path: str) -> bytes:
    return Path(path).read_bytes()

image = load_nifti("brain.nii.gz")

@st.fragment
def viewer():
    result = niivue_viewer(
        nifti_data=image,
        filename="brain.nii.gz",
        key="viewer",
        update_interval_ms=100,  # or None to disable feedback
    )
    if result:
        st.write(result)

viewer()

📚 API Reference

niivue_viewer()

Parameters:

  • nifti_data (bytes, optional): Raw file data of the main image (NIfTI or another supported format), or a scene document (.nvd, .nvd.json)
  • filename (str): Displayed filename; its extension selects the format
  • overlays (list[dict], optional): Overlay images list
    • data (bytes): Overlay data
    • name (str): Overlay name
    • colormap (str): Colormap (default: 'red')
    • opacity (float): 0-1 (default: 0.5)
  • meshes (list[dict], optional): Mesh surfaces list
    • data (bytes): Mesh file data
    • name (str): Mesh filename (must include extension, e.g. 'lh.pial', 'brain.gii')
    • overlays (list[dict], optional): Mesh overlays (curvature, thickness, etc.)
      • data (bytes): Overlay data
      • name (str): Overlay filename
      • colormap (str): Colormap (default: 'redyell')
      • opacity (float): 0-1 (default: 0.7)
  • height (int): Height in pixels (default: 600)
  • view_mode (str): 'axial', 'coronal', 'sagittal', '3d', 'multiplanar' (default)
  • styled (bool): Show menu (default: True)
  • settings (dict, optional):
    • crosshair (bool): default True
    • radiological (bool): default False
    • colorbar (bool): default False
    • interpolation (bool): default True
  • update_interval_ms (int or None): throttle for click events sent back to Python (default: 100 ms). None disables feedback entirely — use it when the return value isn't consumed to avoid any Python round-trip during mouse interaction.
  • key (str, optional): Component key
  • load_events (bool): send base_loaded and fully_loaded events when loading finishes, or load_error when it fails (default: False). See Waiting for the Image to Load.

Returns:

dict or None: the latest event from the viewer. A click:

  • type: 'voxel_click'
  • voxel: [x, y, z]
  • mm: [x, y, z]
  • value: float
  • filename: str

With load_events=True, also a finished load:

  • type: 'base_loaded', 'fully_loaded' or 'load_error'
  • filename: str
  • timestamp: int, time in the browser in milliseconds since the epoch
  • error: str, only for 'load_error'

🛠️ Development

Dev mode (live reload)

In dev mode, the Python package points to a local Vite dev server instead of built files.

Terminal 1 — start the frontend dev server (port 3001):

pnpm dev

Terminal 2 — run the example app with the dev flag:

NIIVUE_DEV=1 streamlit run app.py

The frontend hot-reloads on changes.

Production mode (built files)

Build the frontend first, then run Streamlit normally:

pnpm build
streamlit run app.py

_RELEASE = True (the default) serves from niivue_component/frontend/build/.

Running Examples

# Simple example
streamlit run app.py

# Advanced example with all features
streamlit run app_advanced.py

📁 Supported Formats

🏗️ Architecture

niivue_component/
├── __init__.py                 # Python API
├── frontend/
│   ├── src/
│   │   ├── components/
│   │   │   ├── StyledViewer.tsx
│   │   │   └── UnstyledCanvas.tsx
│   │   ├── types.ts
│   │   └── utils.ts
│   ├── vite.config.ts
│   └── package.json
└── build/                      # Compiled assets (generated, not in git)

🔧 Building for Distribution

Build files are not committed to git. To prepare the Python package for release:

pnpm build
python -m build

This compiles frontend assets into niivue_component/frontend/build/, which is then bundled into the Python package.

📝 Citation

If you use this component in published work, please cite:

Eckstein K, Androulakis A, Dao TT, et al. Seamless neuroimaging visualization: The NiiVue wrapper ecosystem. Aperture Neuro. 2026;6. doi:10.52294/001c.167815

📄 License

BSD-2-Clause

🙏 Credits

Built on top of:

Metadata

Release files for niivue-streamlit 0.4.0.dev168

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

Source distribution (sdist)

Source distribution for niivue-streamlit 0.4.0.dev168
File Size Uploaded Provenance Actions
niivue_streamlit-0.4.0.dev168.tar.gz 1.6 MB Without provenance Details for niivue_streamlit-0.4.0.dev168.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for niivue-streamlit 0.4.0.dev168
File Interpreter ABI Platform Actions
niivue_streamlit-0.4.0.dev168-py3-none-any.whl Python 3 none any Details for niivue_streamlit-0.4.0.dev168-py3-none-any.whl

Total release size: 3.2 MB

Release files / niivue_streamlit-0.4.0.dev168.tar.gz

Download URL niivue_streamlit-0.4.0.dev168.tar.gz
Size 1.6 MB
Tags Source
SHA-256 checksum
How to use checksums
d165f6e2bffb3e60595188c2c64acc1238356de80cd538b100f2aaeaeb68b8bc
BLAKE2b-256 checksum
How to use checksums
4a617253a8fcc682befc02dcac3306cdf251dc5ad251d02ce70d1eb5e9bfad63
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.18

Release files / niivue_streamlit-0.4.0.dev168-py3-none-any.whl

Download URL niivue_streamlit-0.4.0.dev168-py3-none-any.whl
Size 1.6 MB
Tags Python 3
SHA-256 checksum
How to use checksums
4461d76c26ee2b704bbe740505a7c92818152b97ae52e6494f044f891068d693
BLAKE2b-256 checksum
How to use checksums
79ebb6f40a5ce663e5631a03cda95a1ebfa443e3eb84570be225a657038fa9b6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.18

Security for niivue-streamlit 0.4.0.dev168

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.

Release history Release notifications | RSS feed

This release
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