### Start Development Server for JavaScript Source: https://niivue.github.io/ipyniivue/contributing.html Start a development server that automatically rebuilds JavaScript code as changes are made. Recommended for active development. ```bash $ npm run dev ``` -------------------------------- ### Install IPyNiiVue with pip Source: https://niivue.github.io/ipyniivue/_sources/install.rst.txt Use this command to install IPyNiiVue and its dependencies. ```console $ pip install ipyniivue ``` -------------------------------- ### Start JavaScript Development Server Source: https://niivue.github.io/ipyniivue/_sources/contributing.rst.txt Starts a development server that automatically rebuilds JavaScript code on changes. Recommended for active JavaScript development. ```console $ npm run dev ``` -------------------------------- ### Download pcasl.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading pcasl.nii.gz... ``` -------------------------------- ### Set Up Development Environment Source: https://niivue.github.io/ipyniivue/_sources/contributing.rst.txt Manually creates a virtual environment and installs the project in editable mode with development dependencies. Use this if not using hatch. ```console python3 -m venv .venv && source .venv/bin/activate pip install -e ".[dev]" ``` -------------------------------- ### Install Pre-Commit Hooks Source: https://niivue.github.io/ipyniivue/contributing.html Install pre-commit hooks to automatically check and fix code issues before committing. ```bash $ pre-commit install ``` -------------------------------- ### Download gray_bmp.png Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .png file. ```text Downloading gray_bmp.png... ``` -------------------------------- ### Download CT_Philips.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading CT_Philips.nii.gz... ``` -------------------------------- ### Download anat_final.FT+tlrc.HEAD Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .HEAD file. ```text Downloading anat_final.FT+tlrc.HEAD... ``` -------------------------------- ### Develop IPyNiiVue with Virtual Environment Source: https://niivue.github.io/ipyniivue/contributing.html Manually create a virtual environment and install IPyNiiVue with development dependencies using pip. ```bash python3 -m venv .venv && source .venv/bin/activate pip install -e ".[dev]" ``` -------------------------------- ### Download CT_AVM.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading CT_AVM.nii.gz... ``` -------------------------------- ### Download dsistudio.src.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .src.gz file. ```text Downloading dsistudio.src.gz... ``` -------------------------------- ### Download anat_final.FT+tlrc.BRIK Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .BRIK file. ```text Downloading anat_final.FT+tlrc.BRIK... ``` -------------------------------- ### Initialize and Load Volumes for Three NiiVue Instances Source: https://niivue.github.io/ipyniivue/gallery/sync.bidirectional.html Creates three NiiVue instances with specified height and background color, then loads different volumes into each instance. This is the setup for demonstrating synchronized views. ```python import ipywidgets as widgets from IPython.display import display from ipyniivue import MultiplanarType, NiiVue ## Create three instances nv1 = NiiVue( height=400, multiplanar_force_render=True, back_color=(0.0, 0.0, 0.0, 1.0), ) nv2 = NiiVue( height=400, multiplanar_force_render=True, back_color=(0.0, 0.0, 0.0, 1.0), ) nv3 = NiiVue( height=400, multiplanar_force_render=True, back_color=(0.0, 0.0, 0.0, 1.0), ) nv1.load_volumes([{"path": "../images/pcasl.nii.gz"}]) nv2.load_volumes([{"path": "../images/aal.nii.gz"}]), nv3.load_volumes([{"path": "../images/mni152.nii.gz"}]) ``` -------------------------------- ### Setup and Initialize NiiVue Instance Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Initializes a NiiVue instance with a specified background color, enables the colorbar, sets the slice type to RENDER, and configures a clip plane. ```python ## Setup NiiVue Instance v = NiiVue( back_color=(0.7, 0.7, 0.9, 1), ) v.opts.is_colorbar = True v.set_slice_type("RENDER") v.set_clip_plane(0.35, 270, 0) ``` -------------------------------- ### Download DoG.png Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .png file. ```text Downloading DoG.png... ``` -------------------------------- ### NiiVue Mask and Overlay Example Source: https://niivue.github.io/ipyniivue/gallery/vox.mask.html Loads volumes, sets rendering options, and controls background mask overlays with a checkbox. Requires ipywidgets and ipyniivue libraries. ```python # Import necessary libraries import ipywidgets as widgets from IPython.display import display from ipyniivue import NiiVue, SliceType # Create a NiiVue instance with specific options nv = NiiVue(show_3d_crosshair=True) # Load the volumes volumes = [ { "path": "../images/fslmean.nii.gz", }, { "path": "../images/fslt.nii.gz", "colormap": "redyell", "cal_min": 0.05, "cal_max": 5.05, "opacity": 0.9, }, ] nv.load_volumes(volumes) # Set the slice type to render (3D view) nv.set_slice_type(SliceType.RENDER) # Set the clip plane nv.set_clip_plane(0.15, 270, 0) # Set the render azimuth and elevation nv.set_render_azimuth_elevation(45, 45) ## Create interactive checkbox # Create a checkbox to toggle background masks overlays background_masks_checkbox = widgets.Checkbox( value=False, description="Background masks overlay", disabled=False, ) # Function to handle checkbox changes def on_background_masks_change(change): """Set background mask overlay.""" nv.background_masks_overlays = change.new # Observe changes to the checkbox background_masks_checkbox.observe(on_background_masks_change, names="value") ## Display all display(background_masks_checkbox) display(nv) ``` -------------------------------- ### Download visiblehuman.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading visiblehuman.nii.gz... ``` -------------------------------- ### Download MR_Gd.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading MR_Gd.nii.gz... ``` -------------------------------- ### Download spmMotor.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading spmMotor.nii.gz... ``` -------------------------------- ### Download chris_PD.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading chris_PD.nii.gz... ``` -------------------------------- ### Download chris_t2.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading chris_t2.nii.gz... ``` -------------------------------- ### Download rgb_bmp.jpg Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .jpg file. ```text Downloading rgb_bmp.jpg... ``` -------------------------------- ### Download wm.mgz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .mgz file. ```text Downloading wm.mgz... ``` -------------------------------- ### Download spm152.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading spm152.nii.gz... ``` -------------------------------- ### Download fmri_pitch.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading fmri_pitch.nii.gz... ``` -------------------------------- ### Download chris_t1.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading chris_t1.nii.gz... ``` -------------------------------- ### Download CT_pitch.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading CT_pitch.nii.gz... ``` -------------------------------- ### Download mni152.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading mni152.nii.gz... ``` -------------------------------- ### Download CT_Electrodes.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading CT_Electrodes.nii.gz... ``` -------------------------------- ### Download dsistudio.fib.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .fib.gz file. ```text Downloading dsistudio.fib.gz... ``` -------------------------------- ### Download CT_Abdo.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading CT_Abdo.nii.gz... ``` -------------------------------- ### Download Iguana.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading Iguana.nii.gz... ``` -------------------------------- ### Download template.mif.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .mif.gz file. ```text Downloading template.mif.gz... ``` -------------------------------- ### Download chris_MRA.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading chris_MRA.nii.gz... ``` -------------------------------- ### Initialize NiiVue and Load Image Source: https://niivue.github.io/ipyniivue/gallery/draw2.html Initializes the NiiVue viewer, sets display options, and loads an initial volume. This is the starting point for most drawing interactions. ```python import json import ipywidgets as widgets from IPython.display import display from ipyniivue import ColorMap, NiiVue, ShowRender, SliceType nv = NiiVue(back_color=(1, 1, 1, 1)) nv.set_radiological_convention(False) nv.opts.multiplanar_show_render = ShowRender.ALWAYS nv.set_slice_type(SliceType.MULTIPLANAR) nv.load_volumes([{"path": "../images/FLAIR.nii.gz"}]) ``` -------------------------------- ### Download cactus.nii.gz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nii.gz file. ```text Downloading cactus.nii.gz... ``` -------------------------------- ### WidgetObserver Observation Setup Source: https://niivue.github.io/ipyniivue/_modules/ipyniivue/widget.html Sets up the observer to listen for changes on the 'value' attribute of the associated widget. This method is called during initialization. ```python def _observe(self): self.widget.observe(self._widget_change, names=["value"]) ``` -------------------------------- ### NiiVue Widget Integration Example Source: https://niivue.github.io/ipyniivue/gallery/widgets.html This snippet shows how to load volumes into NiiVue and create various ipywidgets to control NiiVue's display properties. It includes examples for mosaic string, corner text, clip dark, scan opacity, hippocampus opacity, scan colormap, and hippocampus colormap. ```python import ipywidgets from ipyniivue import NiiVue, SliceType, WidgetObserver volumes = [ { "path": "../images/mni152.nii.gz", "colormap": "gray", "visible": True, "opacity": 1.0, }, { "path": "../images/hippo.nii.gz", "colormap": "red", "visible": True, "opacity": 1.0, }, ] nv = NiiVue( slice_type=SliceType.MULTIPLANAR, back_color=(0.3, 0.3, 0.5, 1) ) nv.load_volumes(volumes) widgetArray = [] initial_mosaic = ("L A -16 0 16 32 S -24") mosaic_text = { "widget": ipywidgets.Text( description="Mosaic ", value=initial_mosaic, ), "obj": nv.opts, "attribute": "slice_mosaic_string", } widgetArray.append(mosaic_text) cornet_text_button = { "widget": ipywidgets.ToggleButton( description="Corner Text", value=False, button_style='', icon='' ), "obj": nv.opts, "attribute": "is_corner_orientation_text", # this will be set to True/False } widgetArray.append(cornet_text_button) widget_dark_check = { "widget": ipywidgets.Checkbox( value=False, description="Clip Dark", ), "obj": nv.opts, "attribute": "is_alpha_clip_dark", } widgetArray.append(widget_dark_check) widget_back_opacity = { "widget": ipywidgets.RadioButtons( options=[ ("Transparent", 0), ("Translucent", 0.5), ("Opaque", 1), ], value=1, description="Scan Opacity:", ), "obj": nv.volumes[0], "attribute": "opacity", } widgetArray.append(widget_back_opacity) widget_hippo_opacity = { "widget": ipywidgets.FloatSlider( value=1.0, min=0.0, max=1.0, step=0.1, description="Hippocampus Opacity:", orientation="horizontal", style={\"description_width\": "initial"}, ), "obj": nv.volumes[1], "attribute": "opacity", } widgetArray.append(widget_hippo_opacity) widget_scan_colormap = { "widget": ipywidgets.Select( options=["Gray", "Red", "Blue", "Green"], value="Gray", description="Scan Colormap:", style={\"description_width\": "initial"}, ), "obj": nv.volumes[0], "attribute": "colormap", } widgetArray.append(widget_scan_colormap) widget_hippo_colormap = { "widget": ipywidgets.Dropdown( options=["Red", "Blue", "Green", "Gray"], value="Red", description="Hippocampus Colormap:", style={\"description_width\": "initial"}, ), "obj": nv.volumes[1], "attribute": "colormap", } widgetArray.append(widget_hippo_colormap) for widget in widgetArray: WidgetObserver(**widget) for widget in widgetArray: display(widget["widget"]) nv ``` -------------------------------- ### Setup Controls Arrangement Source: https://niivue.github.io/ipyniivue/gallery/draw2.html Arranges various drawing and display controls into horizontal and vertical boxes for UI layout. ```python controls_row1 = widgets.HBox([draw_pen]) movement_buttons = widgets.HBox( [ left_button, right_button, posterior_button, anterior_button, inferior_button, superior_button, ] ) other_buttons = widgets.HBox([save_button, undo_button, growcut_button]) checkboxes1 = widgets.HBox( [ fill_pen_overwrites_checkbox, radiological_checkbox, world_space_checkbox, ] ) checkboxes2 = widgets.HBox( [ linear_interpolation_checkbox, highdpi_checkbox, ] ) controls = widgets.VBox( [ controls_row1, movement_buttons, other_buttons, draw_opacity, checkboxes1, checkboxes2, script_text, custom_button, location_label, ] ) ``` -------------------------------- ### Import Libraries for NiiVue Source: https://niivue.github.io/ipyniivue/gallery/data_loading_formats.html Imports necessary libraries including ipyniivue, numpy, pathlib, and nibabel. Includes a check and installation command for nibabel if it's not found. ```python import ipyniivue import numpy as np import pathlib try: import nibabel as nib except ModuleNotFoundError: !pip install nibabel import nibabel as nib ``` -------------------------------- ### Initialize and Load Diffusion Volumes Source: https://niivue.github.io/ipyniivue/gallery/vox.dti.html Initializes the NiiVue viewer with specific settings and loads FA and V1 diffusion volumes. This setup is for displaying and interacting with voxel-based diffusion data. ```python from ipyniivue import NiiVue, ShowRender import ipywidgets as widgets from IPython.display import display v = NiiVue( back_color=(1, 1, 1, 1), show_3d_crosshair=True, multiplanar_show_render=ShowRender.ALWAYS, height=1024 ) v.load_volumes([ {'path': '../images/FA.nii.gz' }, {'path': '../images/V1.nii.gz', 'opacity': 1 } ]) v.volumes[0].colorbar_visible = False v.opts.is_alpha_clip_dark = True v.set_crosshair_width(0.1) v.is_force_mouse_click_to_voxel_centers = True ``` -------------------------------- ### Initialize NiiVue and Load Volumes Source: https://niivue.github.io/ipyniivue/gallery/modulatescalar.html Sets up the NiiVue viewer with a background color and loads multiple image volumes with specified properties like colormap, opacity, and intensity scaling. ```python import ipywidgets as widgets from IPython.display import display from ipyniivue import NiiVue v = NiiVue( back_color=(0.2, 0.2, 0.3, 1), ) volume_list = [ { "path": "../images/mean_func.nii.gz", "opacity": 1, "colormap": "gray", }, { "path": "../images/cope1.nii.gz", "colormap": "winter", "opacity": 0, "cal_min": 0.0, "cal_max": 100, }, { "path": "../images/tstat1.nii.gz", "opacity": 1, "colormap": "warm", "cal_min": 0, "cal_max": 4.5, }, ] v.load_volumes(volume_list) v.overlay_outline_width = 0.25 v.volumes[0].colorbar_visible = False v.opts.is_colorbar = True v.set_interpolation(True) v.scene.crosshair_pos = (0.55, 0.5, 0.8) v.opts.slice_type = "MULTIPLANAR" ``` -------------------------------- ### Undo Drawing Source: https://niivue.github.io/ipyniivue/api.html Example of reverting the drawing to its previous state. ```python nv.draw_undo() ``` -------------------------------- ### Download HCD1464653.qsdr.fz Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .fz file. ```text Downloading HCD1464653.qsdr.fz... ``` -------------------------------- ### Create NiiVue UI and Load Volumes Source: https://niivue.github.io/ipyniivue/gallery/vox.tradeoffs.html Sets up the user interface with various controls (checkboxes, dropdown, sliders) and initializes a NiiVue instance. It loads multiple volumes with specific colormaps and settings, and configures event handlers for UI interactions. ```python import json import ipywidgets as widgets from ipyniivue import NiiVue from ipyniivue.constants import ShowRender ## create user interface status_bar = widgets.Label(value="") aa_check = widgets.Checkbox(value=True, description="Anti Alias") dpi_check = widgets.Checkbox(value=True, description="High DPI") render_mode = widgets.Dropdown( options=[ ("slices", "-1"), ("matte", "0"), ("low", "0.3"), ("medium", "0.6"), ("high", "1.0"), ], value="0.6", description="Render Mode", ) atlas_slider = widgets.IntSlider( value=64, min=0, max=255, description="Atlas", readout=False ) stat_slider = widgets.IntSlider( value=255, min=0, max=255, description="Statistics", readout=False ) # create niivue instance with open( "../images/aal.json") as f: cmap = json.load(f) v = None # Global variable to hold the NiiVue instance def create_nv(anti_alias): """Create new NiiVue instance.""" global nv if nv: # Don't forget to dispose of the previous nv if it exists nv.close() nv = NiiVue( back_color=(1, 1, 1, 1), show_3d_crosshair=True, is_anti_alias=anti_alias, ) @nv.on_location_change def handle_location_change(location): """Display location.""" status_bar.value = location["string"] nv.opts.multiplanar_show_render = ShowRender.ALWAYS nv.opts.is_colorbar = True volume_list = [ {"path": "../images/mni152.nii.gz"}, {"path": "../images/aal.nii.gz"}, { "path": "../images/stats.nv_demo_mskd.nii.gz", "colormap": "warm", "colormap_negative": "winter", "frame_4d": 1, "cal_min": 3.3641, "cal_max": 6, }, ] nv.load_volumes(volume_list) # Hide colorbars for volumes 0 and 1 nv.volumes[0].colorbar_visible = False nv.volumes[1].colorbar_visible = False nv.volumes[1].set_colormap_label(cmap) return nv # Create initial nv v = create_nv(aa_check.value) ## Define event handlers def on_dpi_check_change(change): """Set high resolution capable.""" nv.set_high_resolution_capable(change["new"]) def on_render_mode_change(change): """Set volume render illumination.""" nv.set_volume_render_illumination(float(change["new"])) def on_atlas_slider_change(change): """Set 2nd volume opacity.""" nv.volumes[1].opacity = change["new"] / 255.0 def on_stat_slider_change(change): """Set 3rd volume opacity.""" nv.volumes[2].opacity = change["new"] / 255.0 def on_aa_check_change(change): """Recreate nv with new anti_alias setting and re-apply settings.""" anti_alias = change["new"] # Create new nv new_nv = create_nv(anti_alias) # Update the UI container ui_container.children = ( widgets.HBox([aa_check, dpi_check, render_mode]), widgets.HBox([atlas_slider, stat_slider]), new_nv, status_bar, ) # Re-apply settings, except for antialias, because doing # so would result in an endless loop here on_dpi_check_change({"new": dpi_check.value}) on_atlas_slider_change({"new": atlas_slider.value}) on_stat_slider_change({"new": stat_slider.value}) ## Set up observers dpi_check.observe(on_dpi_check_change, names="value") render_mode.observe(on_render_mode_change, names="value") atlas_slider.observe(on_atlas_slider_change, names="value") stat_slider.observe(on_stat_slider_change, names="value") aa_check.observe(on_aa_check_change, names="value") ## Apply initial settings # Except for antialias, because doing so would result in an endless loop here # Also, not doing on_render_mode_change because canvas has not been attached yet # so gl does not exist yet. on_dpi_check_change({"new": dpi_check.value}) on_atlas_slider_change({"new": atlas_slider.value}) on_stat_slider_change({"new": stat_slider.value}) ## Display all ui_container = widgets.VBox( [ widgets.HBox([aa_check, dpi_check, render_mode]), widgets.HBox([atlas_slider, stat_slider]), nv, status_bar, ] ) display(ui_container) ``` -------------------------------- ### Setup and Interact with Sparse Atlas Source: https://niivue.github.io/ipyniivue/gallery/vox.atlas.sparse.html This script initializes a NiiVue instance, loads sparse atlas data, and sets up UI controls for opacity, atlas outline, and render mode. It also includes callbacks to update the atlas based on user interactions. ```python import json import ipywidgets as widgets from IPython.display import display from ipyniivue import DragMode, NiiVue, ShowRender # Setup NiiVue Instance nv = NiiVue( back_color=(0.5, 0.5, 0.5, 1), show_3d_crosshair=True, drag_mode=DragMode.PAN, yoke_3d_to_2d_zoom=True, multiplanar_show_render=ShowRender.ALWAYS, ) nv.load_volumes( [ {"path": "../images/inia19-t1-brain.nii.gz"}, {"path": "../images/inia19-NeuroMaps.nii.gz", "opacity": 0.5}, ] ) # for urls: nv.volumes[1].set_colormap_label_from_url("./images/inia19-NeuroMaps.json") with open( "../images/inia19-NeuroMaps.json") as f: cmap = json.load(f) nv.volumes[1].set_colormap_label(cmap) nv.volumes[1].opacity = 0.03 nv.set_atlas_outline(0.01) ## UI # Slider for opacity opacity_slider = widgets.IntSlider( min=1, max=255, value=8, description="Opacity", continuous_update=True, readout=False, ) location_label = widgets.HTML(" ") outline_options = ["None", "Gap", "Opaque", "Black"] outline_dropdown = widgets.Dropdown( options=outline_options, value="Gap", description="Atlas outline", ) render_options = ["Slices", "Matte", "Low", "Medium", "High"] render_dropdown = widgets.Dropdown( options=render_options, value="Matte", description="Render mode", style={"description_width": "initial"}, ) ## Define callbacks def on_opacity_change(change): """Update the opacity of the atlas volume.""" nv.volumes[1].opacity = change["new"] / 255 def on_outline_change(change): """Set atlas outline style.""" value_name = change["new"] # Default borderValue for "No border" borderValue = 0.0 if value_name == "Gap": borderValue = 0.01 elif value_name == "Opaque": borderValue = 1 elif value_name == "Black": borderValue = -1.0 # else "None" → 0.0 nv.set_atlas_outline(borderValue) def on_render_change(change): """Set render mode.""" value_name = change["new"] # Default borderValue for "matte" renderValue = 0.0 if value_name == "Slices": renderValue = -1.0 elif value_name == "Low": renderValue = 0.3 elif value_name == "Medium": renderValue = 0.6 elif value_name == "High": renderValue = 1.0 # else "Matte" → 0.0 nv.set_volume_render_illumination(renderValue) # nv.update_gl_volume() def handle_location_change(location): """Update the location label with current coordinates.""" region = int(location["values"][1]["value"]) if region == nv.opts.atlas_active_index: return # nv.set_atlas_active_index(region) location_label.value = location["string"] ## Setup observers opacity_slider.observe(on_opacity_change, names="value") nv.on_location_change(handle_location_change) on_opacity_change({"new": opacity_slider.value}) outline_dropdown.observe(on_outline_change, names="value") render_dropdown.observe(on_render_change, names="value") ## Display All controls = widgets.HBox([opacity_slider, outline_dropdown, render_dropdown]) display( widgets.VBox( [ controls, nv, location_label, ] ) ) ``` -------------------------------- ### Load Volumes and Initialize NiiVue Source: https://niivue.github.io/ipyniivue/gallery/saving.html This snippet demonstrates how to load multiple volumes with specified colormaps and visibility settings, and then initializes the NiiVue viewer in multiplanar slice mode. ```python from ipyniivue import NiiVue, SliceType volumes = [ { "path": "../images/mni152.nii.gz", "colormap": "gray", "visible": True, "opacity": 1.0, }, { "path": "../images/hippo.nii.gz", "colormap": "red", "visible": True, "opacity": 1, }, ] vn = NiiVue(slice_type=SliceType.MULTIPLANAR) vn.load_volumes(volumes) vn ``` -------------------------------- ### Set up Drawing Callbacks and GUI Controls Source: https://niivue.github.io/ipyniivue/gallery/draw2.html Configures callbacks for location changes and image loading, and creates various GUI controls for drawing, navigation, and display settings. ```python ## Set up Callbacks drawing_loaded = False location_label = widgets.Label(value="") @nv.on_location_change def handle_location_change(location): """Update the location label when the crosshair location changes.""" location_label.value = f"Location: {location['string']}" @nv.on_image_loaded def handle_image_loaded(volume): """Reset drawing settings when a new image is loaded.""" global drawing_loaded if not drawing_loaded: drawing_loaded = True nv.load_drawing("../images/lesion.nii.gz") nv.set_drawing_enabled(False) draw_pen.value = -1 # Set the drawPen dropdown to 'Off' ## Create GUI Controls # Dropdown for Draw Pen draw_pen = widgets.Dropdown( options=[ ("Off", -1), ("Erase", 0), ("Red", 1), ("Green", 2), ("Blue", 3), ("Filled Erase", 8), ("Filled Red", 9), ("Filled Green", 10), ("Filled Blue", 11), ("Erase Selected Cluster", 12), ], value=-1, description="Draw color:", ) # Movement Buttons left_button = widgets.Button(description="Left") right_button = widgets.Button(description="Right") posterior_button = widgets.Button(description="Posterior") anterior_button = widgets.Button(description="Anterior") inferior_button = widgets.Button(description="Inferior") superior_button = widgets.Button(description="Superior") # Other Buttons save_button = widgets.Button(description="Save Drawing") undo_button = widgets.Button(description="Undo") growcut_button = widgets.Button(description="Grow Cut") # Draw Opacity Slider draw_opacity = widgets.IntSlider( value=80, min=0, max=100, step=1, description="Drawing Opacity", readout=False, style={"description_width": "initial"}, ) # Checkboxes fill_pen_overwrites_checkbox = widgets.Checkbox( value=True, description="Fill pen overwrites", ) radiological_checkbox = widgets.Checkbox( value=False, description="Radiological", ) world_space_checkbox = widgets.Checkbox( value=False, description="World space", ) linear_interpolation_checkbox = widgets.Checkbox( value=True, description="Linear Interpolation", ) highdpi_checkbox = widgets.Checkbox( value=True, description="HighDPI", ) # Textarea for Custom Colormap text_value = """ { "R": [0, 255, 22, 127], "G": [0, 20, 192, 187], "B": [0, 152, 80, 255], "labels": ["clear", "pink", "lime", "sky"] } """ num_lines = text_value.count("\n") + 1 # Adding 1 to include the last line script_text = widgets.Textarea( value=text_value, description="Colormap", layout=widgets.Layout(width="60%"), rows=num_lines, # Set rows to the number of lines in your text ) # Apply Button for Custom Colormap custom_button = widgets.Button(description="Apply") ``` -------------------------------- ### Build Documentation Source: https://niivue.github.io/ipyniivue/_sources/contributing.rst.txt Builds the project documentation using Sphinx. This command generates the documentation website. ```console $ hatch run docs ``` -------------------------------- ### Initialize NiiVue and Load Volumes Source: https://niivue.github.io/ipyniivue/gallery/vox.atlas.html Creates a NiiVue instance, sets initial options, and loads MNI152 and AAL atlas volumes. Ensure the image paths are correct. ```python import json import ipywidgets as widgets from IPython.display import display from ipyniivue import NiiVue, ShowRender ## Create NiiVue Instance nv = NiiVue( show_3d_crosshair=True, back_color=(0.5, 0.5, 0.5, 1), ) nv.set_interpolation(True) nv.opts.crosshair_gap = 12 nv.opts.multiplanar_show_render = ShowRender.ALWAYS nv.opts.drag_mode = "PAN" nv.opts.yoke_3d_to_2d_zoom = True nv.load_volumes( [ {"path": "../images/mni152.nii.gz"}, {"path": "../images/aal.nii.gz"}, ] ) ``` -------------------------------- ### Load Initial Volume into NiiVue Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Loads an initial volume into the NiiVue instance from a specified path, setting its colormap to 'gray', opacity to 1, and visibility to True. ```python initial_volume_path = DATA_FOLDER / "mni152.nii.gz" v.load_volumes( [ { "path": initial_volume_path, "colormap": "gray", "opacity": 1, "visible": True, } ] ) ``` -------------------------------- ### Initialize NiiVue and Load Volumes with Thresholds Source: https://niivue.github.io/ipyniivue/gallery/stats.alphathreshold.html Initializes a NiiVue instance with custom settings and loads two volumes. The second volume is configured with specific colormaps for positive and negative values, along with their respective statistical thresholds (cal_min, cal_max, cal_min_neg, cal_max_neg). ```python import ipywidgets as widgets from IPython.display import display from ipyniivue import NiiVue, ShowRender, SliceType # Create NiiVue instance with specific settings nv = NiiVue( loading_text="waiting", back_color=(1, 1, 1, 1), show_3d_crosshair=True, is_colorbar=True, multiplanar_show_render=ShowRender.ALWAYS, ) # Set initial configuration nv.set_radiological_convention(False) nv.set_slice_type(SliceType.MULTIPLANAR) nv.set_slice_mm(False) nv.set_interpolation(True) # Load 4D volume with paired HEAD and BRIK files nv.load_volumes( [ { "path": "../images/fslmean.nii.gz", }, { "path": "../images/fslt.nii.gz", "colormap": "warm", "colormap_negative": "winter", "cal_min": 3, "cal_max": 6, "cal_min_neg": -6, "cal_max_neg": -3, }, ] ) # Hide colorbar for anatomical scan nv.volumes[0].colorbar_visible = False # Set initial overlay outline nv.overlay_outline_width = 0.25 ``` -------------------------------- ### Set Initial Display and Handle Location Changes Source: https://niivue.github.io/ipyniivue/gallery/modulatescalar.html Configures the initial display mode after volumes are loaded and sets up a handler to update an HTML element with the current cursor location. ```python ## Actions # Set the initial display mode. # This function requires that the canvas is attached # and all 3 volumes are loaded (ie, their IDs are defined) # So, we use nv.on_image_loaded def set_initial_display(volume): """Set initial display mode.""" if all(v.id for v in nv.volumes): on_display_mode_change({"new": display_mode_dropdown.value}) nv.on_image_loaded(set_initial_display, remove=True) # remove after 1st run v.on_image_loaded(set_initial_display) ## Handle location change location_output = widgets.HTML(value=" ") def handle_location_change(location): """Handle location changes.""" location_output.value = "  " + location["string"] v.on_location_change(handle_location_change) ``` -------------------------------- ### Download trix/fa.mif Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .mif file. ```text Downloading trix/fa.mif... ``` -------------------------------- ### Download Dataset and Load from Path Source: https://niivue.github.io/ipyniivue/gallery/data_loading_formats.html Fetches a dataset from a GitHub URL using ipyniivue.download_dataset, saves it to a local 'images' folder, and then loads the image from the local path. This is useful when data is not locally available but accessible via a URL. ```python nv2 = ipyniivue.NiiVue() github_url = "https://github.com/niivue/niivue-demo-images/raw/main" DATA_FOLDER = pathlib.Path("images") ipyniivue.download_dataset( api_url=github_url, dest_folder=DATA_FOLDER, files=[ "mni152.nii.gz", ], ) v2.load_volumes([{"path": DATA_FOLDER / "mni152.nii.gz"}]) v2 ``` -------------------------------- ### Download mha.mha Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .mha file. ```text Downloading mha.mha... ``` -------------------------------- ### Download and Display Various Mesh Formats Source: https://niivue.github.io/ipyniivue/gallery/mesh.formats.html This code snippet downloads a collection of mesh files from a remote URL to a local directory and then initializes a NiiVue instance to display two default meshes. It sets up event handlers for dropdowns to control mesh loading, opacity, and shader. ```python import pathlib import ipywidgets as widgets from IPython.display import display import ipyniivue from ipyniivue import NiiVue, download_dataset ## Download Formats DATA_FOLDER = pathlib.Path(ipyniivue.__file__).parent / "images" local_imgs = [ "mni152_2009.mz3", "ColumnMajorOrder.gii", "mni_format.obj.gz", "simplify_brain.obj", "lh.pial", "sub-test02_left_hemisphere.srf.gz", "tract.SLF1_R.tck", "colby.trk", "colby.trx", "TR_S_R.tt.gz", "tract.FAT_R.vtk", "water-color.wrl", "MolView-sticks-color_38.x3d", ] files_to_download_local = local_imgs.copy() download_dataset( api_url="https://niivue.com/demos/images/", dest_folder=DATA_FOLDER, files=files_to_download_local, ) ## Setup NiiVue Instance nv = NiiVue( back_color=(0.9, 0.9, 1.0, 1), ) nv.opts.show_legend = False nv.load_meshes([ { "path": "../images/CIT168.mz3", }, { "path": "../images/BrainMesh_ICBM152.lh.mz3", "rgba255": [222, 164, 164, 255], } ]) ## Store image paths img_paths = {} # Formats for img in local_imgs: img_path = DATA_FOLDER / img img_paths[img] = img_path ## User interface dropdowns # Dropdown for Formats formats_dropdown = widgets.Dropdown( options=[(img, img) for img in local_imgs], description="Formats:", value=None, ) ## Event handlers def on_format_change(change): """Handle selection in Formats Dropdown.""" selected_img = change["new"] if not selected_img: return img_path = img_paths.get(selected_img) if not img_path.exists(): print(f"Image {img_path} not found.") return volumeObj = { "path": img_path, } print("Loading format image:", img_path.name) nv.load_meshes([volumeObj]) alpha_options = ["Opaque", "Translucent", "Transparent"] alpha_dropdown = widgets.Dropdown( options=alpha_options, value="Opaque", description="Opacity:", ) def on_alpha_change(change): """Set mesh layer shader.""" idx = len(nv.meshes) - 1 value = change["new"] if (value == "Opaque"): nv.meshes[idx].opacity = 1.0 if (value == "Translucent"): nv.meshes[idx].opacity = 0.2 if (value == "Transparent"): nv.meshes[idx].opacity = 0.0 nv.draw_scene() shader_options = nv.mesh_shader_names() shader_dropdown = widgets.Dropdown( options=shader_options, value="Phong", # Default shader description="Shader:", ) def on_shader_change(change): """Set mesh layer shader.""" idx = len(nv.meshes) - 1 nv.set_mesh_shader(nv.meshes[idx].id, change["new"]) ## Observe the dropdowns formats_dropdown.observe(on_format_change, names="value") shader_dropdown.observe(on_shader_change, names="value") alpha_dropdown.observe(on_alpha_change, names="value") ## Display controls = widgets.HBox([formats_dropdown, shader_dropdown, alpha_dropdown]) display(controls, nv) ``` -------------------------------- ### Load Local NIfTI Image with NiiVue Source: https://niivue.github.io/ipyniivue/gallery/basic.html Initializes NiiVue and loads a NIfTI image from a local file path. Ensure the image file exists at the specified path. ```python from ipyniivue import NiiVue nv = NiiVue() nv.load_volumes([{'path': '../images/mni152.nii.gz'}]) nv ``` -------------------------------- ### Download FLAIR.nrrd Source: https://niivue.github.io/ipyniivue/gallery/vox.formats.html Example of a download progress indicator for a .nrrd file. ```text Downloading FLAIR.nrrd... ``` -------------------------------- ### Initialize and Observe Opacity Dropdown Source: https://niivue.github.io/ipyniivue/gallery/mesh.tradeoffs.html Sets up the opacity dropdown with options for mesh transparency and its observer function. The observer sets the `opacity` property of the second mesh (index 1) and reapplies the shader. ```python alpha_options = ["Opaque", "Translucent", "Transparent"] alpha_dropdown = widgets.Dropdown( options=alpha_options, value="Translucent", description="Opacity:", ) def on_alpha_change(change): """Set mesh layer shader.""" idx = 1 value = change["new"] if (value == "Opaque"): nv.meshes[idx].opacity = 1.0 if (value == "Translucent"): nv.meshes[idx].opacity = 0.2 if (value == "Transparent"): nv.meshes[idx].opacity = 0.0 # TODO: draw_scene causes error if no voxels loaded # nv.draw_scene() nv.set_mesh_shader(nv.meshes[0].id, shader_dropdown.value) ``` -------------------------------- ### Initialize NiiVue and Load Volumes Source: https://niivue.github.io/ipyniivue/gallery/mosaics2.html Initializes the NiiVue widget and loads two NIfTI volumes with specified colormaps and display ranges. This sets up the basic visualization environment. ```python import ipywidgets as widgets from IPython.display import display from ipyniivue import NiiVue nv = NiiVue(height=600, back_color=(1, 1, 1, 1), is_colorbar=True, drag_mode="CONTRAST") nv.load_volumes( [ { "path": "../images/fslmean.nii.gz", "colormap": "gray", "colorbar_visible": False, }, { "path": "../images/fslt.nii.gz", "colormap": "warm", "colormap_negative": "winter", "cal_min": 2, "cal_max": 6, }, ] ) ``` -------------------------------- ### Dilate Drawing Source: https://niivue.github.io/ipyniivue/api.html Example of using the `draw_grow_cut` method to dilate the current drawing. ```python nv.draw_grow_cut() ``` -------------------------------- ### Close Drawing Source: https://niivue.github.io/ipyniivue/api.html Example of how to close the current drawing operation within the NiiVue widget. ```python nv.close_drawing() ``` -------------------------------- ### Get Colormap by Name Source: https://niivue.github.io/ipyniivue/_modules/ipyniivue/widget.html Retrieves a predefined colormap object using its name. Colormap names are case-insensitive. ```python cmap = nv.colormap_from_key('Hot') ``` -------------------------------- ### Initialize and Organize ipyniivue Controls Source: https://niivue.github.io/ipyniivue/gallery/stats.alphathreshold.html Sets up initial values for outline and alpha mode changes, observes changes in positive and negative stat ranges, and organizes various control widgets into rows and a main vertical box for display. ```python on_outline_change({"new": outline_slider.value}) on_alpha_mode_change({"new": alpha_dropdown.value}) pos_stat_range.observe(on_pos_stat_change, names="value") neg_stat_range.observe(on_neg_stat_change, names="value") controls_row1 = widgets.HBox( [dpi_checkbox, negative_checkbox, smooth_checkbox, world_checkbox] ) controls_row2 = widgets.HBox([neg_stat_range, pos_stat_range]) controls_row3 = widgets.HBox([outline_slider, alpha_dropdown]) controls = widgets.VBox( [controls_row1, controls_row2, controls_row3, location_output] ) display(widgets.VBox([controls, nv])) ``` -------------------------------- ### Get Binary Traits Source: https://niivue.github.io/ipyniivue/_modules/ipyniivue/widget.html Returns a list of trait names that are considered binary. This method is used internally. ```python def _get_binary_traits(self): return ["pts", "tris"] ``` -------------------------------- ### Get List of Available Colormaps Source: https://niivue.github.io/ipyniivue/api.html Demonstrates how to fetch a list of all colormap names available in the NiiVue widget. ```python colormaps = nv.colormaps() ``` -------------------------------- ### Get Units Code String Source: https://niivue.github.io/ipyniivue/_modules/ipyniivue/traits.html Returns a human-readable string for a given units code. Supports spatial and temporal units. ```python def _get_units_code_string(self, code): """Return a human-readable string for unit codes.""" mapping = { self.UNITS_METER: "Meters", self.UNITS_MM: "Millimeters", self.UNITS_MICRON: "Microns", self.UNITS_SEC: "Seconds", self.UNITS_MSEC: "Milliseconds", self.UNITS_USEC: "Microseconds", self.UNITS_HZ: "Hz", self.UNITS_PPM: "PPM", self.UNITS_RADS: "Rads", } return mapping.get(code, "Unknown") ``` -------------------------------- ### Observed Traits Example Source: https://niivue.github.io/ipyniivue/_modules/ipyniivue/config_options.html This snippet shows how to observe changes in specific traits and propagate them to a parent object if a notification method exists. ```python @t.observe(*_OBSERVED_TRAITS) def _propagate_parent_change(self, change): if self._parent and callable( getattr(self._parent, "_notify_opts_changed", None) ): self._parent._notify_opts_changed(change) ```