Custom Matcaps¶

A Matcap image provide a simple method to emulate the lighting effects of a complex environment. This Jupyter notebook mirrors the mesh matcap web page.

In [1]:
import ipywidgets as widgets
from ipyniivue import NiiVue, SliceType

nv = NiiVue(
    show_3d_crosshair=True,
    back_color=(1, 1, 1, 1),
)

nv.set_slice_type(SliceType.RENDER)
nv.opts.is_colorbar = True

mesh_layer = {
    "path": "../images/BrainMesh_ICBM152.lh.motor.mz3",
    "cal_min": 2,
    "cal_max": 5,
    "use_negative_cmap": True,
    "opacity": 0.7,
}

nv.load_meshes(
    [
        {
            "path": "../images/BrainMesh_ICBM152.lh.mz3",
            "layers": [mesh_layer],
        },
    ]
)

nv.set_mesh_shader(nv.meshes[0].id, "Matcap")
nv.set_clip_plane(-0.1, 270, 0)

## User interface

threshold_slider = widgets.IntSlider(
    value=20,
    min=1,
    max=49,
    description="Threshold",
    readout=False
)

matcap_options = ["Shiny", "Cortex", "Cream", "Fuzzy", "Peach", "Plastic", "Gold"]
matcap_dropdown = widgets.Dropdown(
    options=matcap_options,
    value="Shiny",
    description="MatCap",
)


def on_threshold_change(change):
    """Set mesh layer property cal_min."""
    nv.set_mesh_layer_property(
        mesh_id=nv.meshes[0].id,
        layer_index=0,
        attribute="cal_min",
        value=change["new"] * 0.1,
    )


threshold_slider.observe(on_threshold_change, names="value")


def on_matcap_change(change):
    """Load matcap texture."""
    nv.set_mesh_shader(nv.meshes[0].id, "Matcap")
    matcap_name = change["new"]
    matcap_path = "../images/matcaps/" + f"{matcap_name}.jpg"
    with open(matcap_path, "rb") as f:
        matcap_data = f.read()
    nv.load_mat_cap_texture(matcap_data)

matcap_dropdown.observe(on_matcap_change, names="value")

widgets.VBox(
    [
        widgets.HBox([threshold_slider, matcap_dropdown]),
        nv,
    ]
)
Out[1]:
In [ ]: