def visualize_slices_with_profile(
volume: np.ndarray,
name: str = "Volume",
colormap: str = "gray",
contrast_limits: Optional[tuple] = None,
gamma: float = 1.0,
opacity: float = 1.0,
scale: Optional[tuple] = None,
initial_slice: Optional[int] = None,
z_values: Optional[np.ndarray] = None,
z_label: str = "Z (axis-0 index)",
phases: Optional[Union[Dict[str, List[float]], Dict[str, pd.DataFrame]]] = None,
) -> napari.Viewer:
"""
Visualize 2-D slices of a 3-D volume (parallel to axis-0) in napari.
**Click any pixel** in the napari canvas to open / update a matplotlib
window showing the intensity profile along axis-0 (Z) at that (y, x)
location. A dashed orange vertical line tracks the currently displayed
slice as you move the slider.
Args:
volume (np.ndarray): 3-D array of shape (Z, Y, X).
name (str): Layer name shown in the napari layer list.
colormap (str): Napari colormap (e.g. "grays", "turbo", "magma").
contrast_limits (tuple, optional): Display range. Defaults to data min/max.
gamma (float): Gamma correction for the colormap.
opacity (float): Layer opacity [0, 1].
scale (tuple, optional): Anisotropic voxel spacing (z, y, x).
initial_slice (int, optional): Axis-0 index to display on open. Defaults
to middle slice.
z_values (array-like, optional): Physical values for the X axis of the
Z-profile plot (e.g. depths in mm, timestamps, wavelengths). Must have
exactly ``volume.shape[0]`` elements. Defaults to integer slice indices.
z_label (str, optional): Label for the X axis of the Z-profile plot.
Default: "Z (axis-0 index)".
phases (dict, optional): Either a mapping of phase name → list of peak
positions (in the same units as *z_values*), or the
``dict[str, pd.DataFrame]`` returned by ``get_powder_xrd_peaks``
(the ``tth`` column is used as tick positions). Each phase is
shown as a row of colored tick marks in a panel below the Z-profile
plot. Example::
{"Austenite": [2.07, 2.48, 3.59], "Ferrite": [2.03, 2.87]}
# or:
peaks = get_powder_xrd_peaks(["au.cif", "fe.cif"])
phases=peaks
Returns:
napari.Viewer: The napari viewer instance.
Note:
Works with matplotlib's interactive backend (Qt / Tk / Wx). Call
``napari.run()`` at the end of a script to start the event loop.
Example:
>>> import numpy as np
>>> vol = np.random.rand(64, 128, 128).astype(np.float32)
>>> viewer = visualize_slices_with_profile(vol, colormap="turbo")
>>> napari.run()
"""
import napari # type: ignore
if volume.ndim != 3:
raise ValueError(f"Expected a 3-D array, got shape {volume.shape}.")
n_slices = volume.shape[0]
if z_values is not None:
z_values = np.asarray(z_values, dtype=float)
if z_values.shape != (n_slices,):
raise ValueError(
f"z_values must have length {n_slices} (= volume.shape[0]), "
f"got {z_values.shape}."
)
if contrast_limits is None:
contrast_limits = (float(volume.min()), float(volume.max()))
if initial_slice is None:
initial_slice = n_slices // 2
elif not (0 <= initial_slice < n_slices):
raise ValueError(
f"initial_slice={initial_slice} out of range [0, {n_slices - 1}]."
)
# --- napari viewer (2-D slice mode) ------------------------------------
viewer = napari.Viewer(
title=f"napari — {name} | axis-0 slices (click pixel → Z-profile)",
ndisplay=2,
)
image_layer = viewer.add_image(
volume,
name=name,
colormap=colormap,
contrast_limits=contrast_limits,
gamma=gamma,
opacity=opacity,
scale=scale,
)
viewer.dims.set_current_step(0, initial_slice)
viewer.reset_view()
# --- Points layer to mark the selected pixel ---------------------------
point_layer = viewer.add_points(
data=np.empty((0, 2)),
name="Selected pixel",
size=10,
face_color="red",
symbol="cross",
)
# --- Z-profile plot -----------------------------------------------------
profile_plot = ZProfilePlot(
n_slices=n_slices,
volume_name=name,
z_values=z_values,
z_label=z_label,
phases=phases,
)
# Track last selected pixel so the vline keeps updating on slice changes
last_pixel = {"y": None, "x": None}
# --- Callback: click in the napari canvas -------------------------------
@image_layer.mouse_drag_callbacks.append
def on_click(layer: Any, event: Any) -> None:
# Only react on left-button press (not drag)
if event.type != "mouse_press" or event.button != 1:
return
# event.position is in *world* coordinates (respects scale).
# For a 3-D array displayed in 2-D, position = (z_world, y_world, x_world).
pos = event.position # world coords
# Convert world → data (pixel) indices
data_coords = layer.world_to_data(pos)
if len(data_coords) == 3:
z_idx, y_idx, x_idx = (int(round(c)) for c in data_coords)
elif len(data_coords) == 2:
# Some napari versions drop the z dim in 2-D mode
y_idx, x_idx = (int(round(c)) for c in data_coords)
z_idx = int(viewer.dims.current_step[0])
else:
return
# Clamp to valid range
z_idx = np.clip(z_idx, 0, volume.shape[0] - 1)
y_idx = np.clip(y_idx, 0, volume.shape[1] - 1)
x_idx = np.clip(x_idx, 0, volume.shape[2] - 1)
# Update marker on the slice
point_layer.data = np.array([[y_idx, x_idx]], dtype=float)
# Extract Z-profile and update plot
profile = volume[:, y_idx, x_idx]
current_z = int(viewer.dims.current_step[0])
profile_plot.update(y_idx, x_idx, profile, current_z)
last_pixel["y"] = y_idx
last_pixel["x"] = x_idx
print(
f"[Z-profile] pixel (y={y_idx}, x={x_idx}) "
f"min={profile.min():.4f} max={profile.max():.4f} "
f"mean={profile.mean():.4f}"
)
# --- Callback: slider moves → update vertical marker -------------------
def on_slice_change(event: Any) -> None:
if last_pixel["y"] is not None:
current_z = int(viewer.dims.current_step[0])
profile_plot.mark_current_z(current_z)
viewer.dims.events.current_step.connect(on_slice_change)
print(
f"\n[visualize_slices_with_profile] '{name}'\n"
f" Shape : {volume.shape}\n"
f" dtype : {volume.dtype}\n"
f" Slices : {n_slices} along axis-0\n"
f" → Click any pixel in the napari window to see its Z-profile.\n"
f" → Use the slider (or ← → arrow keys) to scroll through slices.\n"
)
return viewer