.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "auto_examples/01_introductory/viz_slice.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_auto_examples_01_introductory_viz_slice.py>`
        to download the full example code

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_auto_examples_01_introductory_viz_slice.py:


=====================
Simple volume slicing
=====================

Here we present an example for visualizing slices from 3D images.

.. GENERATED FROM PYTHON SOURCE LINES 8-16

.. code-block:: Python


    import os

    from dipy.data import fetch_bundles_2_subjects
    import nibabel as nib

    import fury








.. GENERATED FROM PYTHON SOURCE LINES 17-18

Let's download and load a T1.

.. GENERATED FROM PYTHON SOURCE LINES 18-35

.. code-block:: Python


    fetch_bundles_2_subjects()

    fname_t1 = os.path.join(
        os.path.expanduser("~"),
        ".dipy",
        "exp_bundles_and_maps",
        "bundles_2_subjects",
        "subj_1",
        "t1_warped.nii.gz",
    )


    img = nib.load(fname_t1)
    data = img.get_fdata()
    affine = img.affine








.. GENERATED FROM PYTHON SOURCE LINES 36-37

Create a Scene object which holds all the actors which we want to visualize.

.. GENERATED FROM PYTHON SOURCE LINES 37-41

.. code-block:: Python


    scene = fury.window.Scene()
    scene.background((0.5, 0.5, 0.5))








.. GENERATED FROM PYTHON SOURCE LINES 42-47

Render slices from T1 with a specific value range
=================================================

The T1 has usually a higher range of values than what can be visualized in an
image. We can set the range that we would like to see.

.. GENERATED FROM PYTHON SOURCE LINES 47-51

.. code-block:: Python


    mean, std = data[data > 0].mean(), data[data > 0].std()
    value_range = (mean - 0.5 * std, mean + 1.5 * std)








.. GENERATED FROM PYTHON SOURCE LINES 52-55

The ``slice`` function will read data and resample the data using an affine
transformation matrix. The default behavior of this function is to show the
middle slice of the last dimension of the resampled data.

.. GENERATED FROM PYTHON SOURCE LINES 55-58

.. code-block:: Python


    slice_actor = fury.actor.slicer(data, affine, value_range)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    /opt/homebrew/Caskroom/miniforge/base/envs/py311-fury/lib/python3.11/site-packages/sphinx_gallery/gen_rst.py:722: UserWarning: We'll no longer accept the way you call the slicer function in future versions of FURY.

    Here's how to call the Function slicer: slicer(data_value, affine='value', value_range='value', opacity='value', lookup_colormap='value', interpolation='value', picking_tol='value')

      exec(self.code, self.fake_main.__dict__)




.. GENERATED FROM PYTHON SOURCE LINES 59-60

The ``slice_actor`` contains an axial slice.

.. GENERATED FROM PYTHON SOURCE LINES 60-63

.. code-block:: Python


    scene.add(slice_actor)








.. GENERATED FROM PYTHON SOURCE LINES 64-67

The same actor can show any different slice from the given data using its
``display`` function. However, if we want to show multiple slices we need to
copy the actor first.

.. GENERATED FROM PYTHON SOURCE LINES 67-70

.. code-block:: Python


    slice_actor2 = slice_actor.copy()








.. GENERATED FROM PYTHON SOURCE LINES 71-73

Now we have a new ``slice_actor`` which displays the middle slice of sagittal
plane.

.. GENERATED FROM PYTHON SOURCE LINES 73-81

.. code-block:: Python


    slice_actor2.display(slice_actor2.shape[0] // 2, None, None)

    scene.add(slice_actor2)

    scene.reset_camera()
    scene.zoom(1.4)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    /opt/homebrew/Caskroom/miniforge/base/envs/py311-fury/lib/python3.11/site-packages/sphinx_gallery/gen_rst.py:722: UserWarning: We'll no longer accept the way you call the display function in future versions of FURY.

    Here's how to call the Function display: display(self_value, x='value', y='value', z='value')

      exec(self.code, self.fake_main.__dict__)




.. GENERATED FROM PYTHON SOURCE LINES 82-83

In order to interact with the data you will need to uncomment the line below.

.. GENERATED FROM PYTHON SOURCE LINES 83-86

.. code-block:: Python


    # fury.window.show(scene, size=(600, 600), reset_camera=False)








.. GENERATED FROM PYTHON SOURCE LINES 87-88

Otherwise, you can save a screenshot using the following command.

.. GENERATED FROM PYTHON SOURCE LINES 88-91

.. code-block:: Python


    fury.window.record(scene, out_path="slices.png", size=(600, 600), reset_camera=False)




.. image-sg:: /auto_examples/01_introductory/images/sphx_glr_viz_slice_001.png
   :alt: viz slice
   :srcset: /auto_examples/01_introductory/images/sphx_glr_viz_slice_001.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    /opt/homebrew/Caskroom/miniforge/base/envs/py311-fury/lib/python3.11/site-packages/sphinx_gallery/gen_rst.py:722: UserWarning: We'll no longer accept the way you call the record function in future versions of FURY.

    Here's how to call the Function record: record(scene='value', cam_pos='value', cam_focal='value', cam_view='value', out_path='value', path_numbering='value', n_frames='value', az_ang='value', magnification='value', size='value', reset_camera='value', screen_clip='value', stereo='value', verbose='value')

      exec(self.code, self.fake_main.__dict__)




.. GENERATED FROM PYTHON SOURCE LINES 92-94

Render slices from FA with your colormap
========================================

.. GENERATED FROM PYTHON SOURCE LINES 94-111

.. code-block:: Python


    # It is also possible to set the colormap of your preference. Here we are
    # loading an FA image and showing it in a non-standard way using an HSV
    # colormap.

    fname_fa = os.path.join(
        os.path.expanduser("~"),
        ".dipy",
        "exp_bundles_and_maps",
        "bundles_2_subjects",
        "subj_1",
        "fa_1x1x1.nii.gz",
    )

    img = nib.load(fname_fa)
    fa = img.get_fdata()








.. GENERATED FROM PYTHON SOURCE LINES 112-113

Notice here how the scale range is. We use FA min and max values to set it up

.. GENERATED FROM PYTHON SOURCE LINES 113-121

.. code-block:: Python


    lut = fury.actor.colormap_lookup_table(
        scale_range=(fa.min(), fa.max()),
        hue_range=(0.4, 1.0),
        saturation_range=(1, 1.0),
        value_range=(0.0, 1.0),
    )








.. GENERATED FROM PYTHON SOURCE LINES 122-124

This is because the lookup table is applied in the slice after interpolating
to (0, 255).

.. GENERATED FROM PYTHON SOURCE LINES 124-139

.. code-block:: Python


    fa_actor = fury.actor.slicer(fa, affine, lookup_colormap=lut)

    scene.clear()
    scene.add(fa_actor)

    scene.reset_camera()
    scene.zoom(1.4)

    # fury.window.show(scene, size=(600, 600), reset_camera=False)

    fury.window.record(
        scene, out_path="slices_lut.png", size=(600, 600), reset_camera=False
    )




.. image-sg:: /auto_examples/01_introductory/images/sphx_glr_viz_slice_002.png
   :alt: viz slice
   :srcset: /auto_examples/01_introductory/images/sphx_glr_viz_slice_002.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 140-146

Now we would like to add the ability to click on a voxel and show its value
on a panel in the window. The panel is a UI element which requires access to
different areas of the visualization pipeline and therefore we don't
recommend using it with ``window.show``. The more appropriate way is to use
the ``ShowManager`` object, which allows accessing the pipeline in different
areas.

.. GENERATED FROM PYTHON SOURCE LINES 146-150

.. code-block:: Python


    show_m = fury.window.ShowManager(scene, size=(1200, 900))






.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    /opt/homebrew/Caskroom/miniforge/base/envs/py311-fury/lib/python3.11/site-packages/sphinx_gallery/gen_rst.py:722: UserWarning: We'll no longer accept the way you call the __init__ function in future versions of FURY.

    Here's how to call the Function __init__: __init__(self_value, scene='value', title='value', size='value', png_magnify='value', reset_camera='value', order_transparent='value', interactor_style='value', stereo='value', multi_samples='value', max_peels='value', occlusion_ratio='value')

      exec(self.code, self.fake_main.__dict__)




.. GENERATED FROM PYTHON SOURCE LINES 151-152

We'll start by creating the panel and adding it to the ``ShowManager``

.. GENERATED FROM PYTHON SOURCE LINES 152-171

.. code-block:: Python


    label_position = fury.ui.TextBlock2D(text="Position:")
    label_value = fury.ui.TextBlock2D(text="Value:")

    result_position = fury.ui.TextBlock2D(text="")
    result_value = fury.ui.TextBlock2D(text="")

    panel_picking = fury.ui.Panel2D(
        size=(250, 125), position=(20, 20), color=(0, 0, 0), opacity=0.75, align="left"
    )

    panel_picking.add_element(label_position, (0.1, 0.55))
    panel_picking.add_element(label_value, (0.1, 0.25))

    panel_picking.add_element(result_position, (0.45, 0.55))
    panel_picking.add_element(result_value, (0.45, 0.25))

    show_m.scene.add(panel_picking)








.. GENERATED FROM PYTHON SOURCE LINES 172-174

Add a left-click callback to the slicer. Also disable interpolation so you
can see what you are picking.

.. GENERATED FROM PYTHON SOURCE LINES 174-192

.. code-block:: Python



    def left_click_callback(obj, _ev):
        """Get the value of the clicked voxel and show it in the panel."""
        event_pos = show_m.iren.GetEventPosition()

        obj.picker.Pick(event_pos[0], event_pos[1], 0, show_m.scene)

        i, j, k = obj.picker.GetPointIJK()
        result_position.message = "({}, {}, {})".format(str(i), str(j), str(k))
        result_value.message = "%.8f" % data[i, j, k]


    fa_actor.SetInterpolate(False)
    fa_actor.AddObserver("LeftButtonPressEvent", left_click_callback, 1.0)

    # show_m.start()





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    1



.. GENERATED FROM PYTHON SOURCE LINES 193-201

Create a mosaic
================

By using the ``copy`` and ``display`` method of the ``slice_actor`` becomes
easy and efficient to create a mosaic of all the slices.

So, let's clear the scene and change the projection from perspective to
parallel. We'll also need a new show manager and an associated callback.

.. GENERATED FROM PYTHON SOURCE LINES 201-222

.. code-block:: Python


    scene.clear()
    scene.projection("parallel")

    result_position.message = ""
    result_value.message = ""

    show_m_mosaic = fury.window.ShowManager(scene, size=(1200, 900))


    def left_click_callback_mosaic(obj, _ev):
        """Get the value of the clicked voxel and show it in the panel."""
        event_pos = show_m_mosaic.iren.GetEventPosition()

        obj.picker.Pick(event_pos[0], event_pos[1], 0, show_m_mosaic.scene)

        i, j, k = obj.picker.GetPointIJK()
        result_position.message = "({}, {}, {})".format(str(i), str(j), str(k))
        result_value.message = "%.8f" % data[i, j, k]






.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    /opt/homebrew/Caskroom/miniforge/base/envs/py311-fury/lib/python3.11/site-packages/sphinx_gallery/gen_rst.py:722: UserWarning: We'll no longer accept the way you call the projection function in future versions of FURY.

    Here's how to call the Function projection: projection(self_value, proj_type='value')

      exec(self.code, self.fake_main.__dict__)




.. GENERATED FROM PYTHON SOURCE LINES 223-226

Now we need to create two nested for loops which will set the positions of
the grid of the mosaic and add the new actors to the scene. We are going
to use 15 columns and 10 rows but you can adjust those with your datasets.

.. GENERATED FROM PYTHON SOURCE LINES 226-259

.. code-block:: Python


    cnt = 0

    X, Y, Z = slice_actor.shape[:3]

    rows = 10
    cols = 15
    border = 10

    for j in range(rows):
        for i in range(cols):
            slice_mosaic = slice_actor.copy()
            slice_mosaic.display(None, None, cnt)
            slice_mosaic.SetPosition(
                (X + border) * i, 0.5 * cols * (Y + border) - (Y + border) * j, 0
            )
            slice_mosaic.SetInterpolate(False)
            slice_mosaic.AddObserver(
                "LeftButtonPressEvent", left_click_callback_mosaic, 1.0
            )
            scene.add(slice_mosaic)
            cnt += 1
            if cnt > Z:
                break
        if cnt > Z:
            break

    scene.reset_camera()
    scene.zoom(1.0)

    # show_m_mosaic.scene.add(panel_picking)
    # show_m_mosaic.start()








.. GENERATED FROM PYTHON SOURCE LINES 260-263

If you uncomment the two lines above, you will be able to move
the mosaic up/down and left/right using the middle mouse button drag,
zoom in/out using the scroll wheel, and pick voxels with left click.

.. GENERATED FROM PYTHON SOURCE LINES 263-266

.. code-block:: Python



    fury.window.record(scene, out_path="mosaic.png", size=(900, 600), reset_camera=False)



.. image-sg:: /auto_examples/01_introductory/images/sphx_glr_viz_slice_003.png
   :alt: viz slice
   :srcset: /auto_examples/01_introductory/images/sphx_glr_viz_slice_003.png
   :class: sphx-glr-single-img






.. rst-class:: sphx-glr-timing

   **Total running time of the script:** (0 minutes 3.888 seconds)


.. _sphx_glr_download_auto_examples_01_introductory_viz_slice.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: viz_slice.ipynb <viz_slice.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: viz_slice.py <viz_slice.py>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_