Skip to content

Processing

qim3d.processing.local_thickness

local_thickness(image, scale=1, mask=None, visualize=False, **viz_kwargs)

Computes the local thickness map for a 2D or 3D image.

Local Thickness is a morphometric measure defined as the diameter of the largest sphere that fits entirely within the object boundary and contains the point. Intuitively, it represents the "width" of the structure at any given voxel. It is widely used to analyze pore sizes, trabecular bone thickness, or vessel diameters.

This function wraps the localthickness package, which implements the "Fast Local Thickness" algorithm. Unlike traditional methods that use computationally expensive large structuring elements, this algorithm uses iterative dilation with small kernels, making it significantly faster and feasible for high-resolution 3D microscopy data.

Note: This function requires a binary image. If a grayscale image is provided, it will be automatically binarized using Otsu's thresholding method.

Parameters:

Name Type Description Default
image ndarray

The input 2D or 3D array. * Binary: Processed directly. * Grayscale: Automatically binarized using Otsu's method (a warning will be logged).

required
scale float

A downscaling factor to speed up computation. For example, 0.5 downsamples the image by half in each dimension before processing. Defaults to 1 (no scaling).

1
mask ndarray

A binary mask of the same shape as image. Local thickness will only be computed for regions where the mask is True. Defaults to None.

None
visualize bool

If True, immediately displays a visualization of the thickness map using qim3d.viz.local_thickness. Defaults to False.

False
**viz_kwargs Any

Additional keyword arguments passed to the visualization function.

{}

Returns:

Name Type Description
local_thickness ndarray

A NumPy array of the same shape as the input, where each pixel/voxel value represents the local thickness at that point.

Example

import qim3d

vol = qim3d.examples.fly_150x256x256
lt_vol = qim3d.processing.local_thickness(vol, visualize=True, axis=0)
local thickness 3d

import qim3d

# Generate synthetic collection of blobs
vol, labels = qim3d.generate.volume_collection(
    n_volumes=3,
    collection_shape=(64, 64, 64),
    shape_range=((12, 12, 12), (20, 20, 20)),
)

# Extract one slice to show that local thickness works on 2D slices too
slice = vol[:, :, 32]
lt_blobs = qim3d.processing.local_thickness(slice, visualize=True)
local thickness 2d

Runtime and memory usage

local thickness estimate time and mem Performance computed on Intel(R) Xeon(R) Gold 6226 CPU @ 2.70GHz.

Reference

Dahl, V. A., & Dahl, A. B. (2023, June). Fast Local Thickness. 2023 IEEE/CVF Conference on Computer Vision and Pattern Recognition Workshops (CVPRW). https://doi.org/10.1109/cvprw59228.2023.00456

@inproceedings{Dahl_2023, title={Fast Local Thickness},
url={[http://dx.doi.org/10.1109/CVPRW59228.2023.00456](http://dx.doi.org/10.1109/CVPRW59228.2023.00456)},
DOI={10.1109/cvprw59228.2023.00456},
booktitle={2023 IEEE/CVF Conference on Computer Vision and Pattern Recognition Workshops (CVPRW)},
publisher={IEEE},
author={Dahl, Vedrana Andersen and Dahl, Anders Bjorholm},
year={2023},
month=jun }
Source code in qim3d/processing/_local_thickness.py
def local_thickness(
    image: np.ndarray,
    scale: float = 1,
    mask: np.ndarray | None = None,
    visualize: bool = False,
    **viz_kwargs,
) -> np.ndarray:
    """
    Computes the local thickness map for a 2D or 3D image.

    Local Thickness is a morphometric measure defined as the diameter of the largest sphere that fits entirely within the object boundary and contains the point. Intuitively, it represents the "width" of the structure at any given voxel. It is widely used to analyze pore sizes, trabecular bone thickness, or vessel diameters.

    This function wraps the [localthickness](https://github.com/vedranaa/local-thickness) package, which implements the "Fast Local Thickness" algorithm. Unlike traditional methods that use computationally expensive large structuring elements, this algorithm uses iterative dilation with small kernels, making it significantly faster and feasible for high-resolution 3D microscopy data.

    **Note:** This function requires a **binary** image. If a grayscale image is provided, it will be automatically binarized using Otsu's thresholding method.

    Args:
        image (np.ndarray): The input 2D or 3D array.
            * **Binary:** Processed directly.
            * **Grayscale:** Automatically binarized using Otsu's method (a warning will be logged).
        scale (float, optional): A downscaling factor to speed up computation. For example, `0.5` downsamples the image by half in each dimension before processing. Defaults to 1 (no scaling).
        mask (np.ndarray, optional): A binary mask of the same shape as `image`. Local thickness will only be computed for regions where the mask is `True`. Defaults to `None`.
        visualize (bool, optional): If `True`, immediately displays a visualization of the thickness map using `qim3d.viz.local_thickness`. Defaults to `False`.
        **viz_kwargs (Any): Additional keyword arguments passed to the visualization function.

    Returns:
        local_thickness (np.ndarray):
            A NumPy array of the same shape as the input, where each pixel/voxel value represents the local thickness at that point.

    Example:
        ```python
        import qim3d

        vol = qim3d.examples.fly_150x256x256
        lt_vol = qim3d.processing.local_thickness(vol, visualize=True, axis=0)
        ```
        ![local thickness 3d](../../assets/screenshots/local_thickness_3d.gif)

        ```python
        import qim3d

        # Generate synthetic collection of blobs
        vol, labels = qim3d.generate.volume_collection(
            n_volumes=3,
            collection_shape=(64, 64, 64),
            shape_range=((12, 12, 12), (20, 20, 20)),
        )

        # Extract one slice to show that local thickness works on 2D slices too
        slice = vol[:, :, 32]
        lt_blobs = qim3d.processing.local_thickness(slice, visualize=True)

        ```
        ![local thickness 2d](../../assets/screenshots/local_thickness_2d.png)

    !!! info "Runtime and memory usage"
        ![local thickness estimate time and mem](../../assets/screenshots/Local_thickness_time_mem_estimation.png)
        Performance computed on Intel(R) Xeon(R) Gold 6226 CPU @ 2.70GHz.

    !!! quote "Reference"
        Dahl, V. A., & Dahl, A. B. (2023, June). Fast Local Thickness. 2023 IEEE/CVF Conference on Computer Vision and Pattern Recognition Workshops (CVPRW).
        <https://doi.org/10.1109/cvprw59228.2023.00456>

        ```bibtex
        @inproceedings{Dahl_2023, title={Fast Local Thickness},
        url={[http://dx.doi.org/10.1109/CVPRW59228.2023.00456](http://dx.doi.org/10.1109/CVPRW59228.2023.00456)},
        DOI={10.1109/cvprw59228.2023.00456},
        booktitle={2023 IEEE/CVF Conference on Computer Vision and Pattern Recognition Workshops (CVPRW)},
        publisher={IEEE},
        author={Dahl, Vedrana Andersen and Dahl, Anders Bjorholm},
        year={2023},
        month=jun }
        ```
    """
    import localthickness as lt

    # Check if input is binary
    if np.unique(image).size > 2:
        # If not, binarize it using Otsu's method, log the threshold and compute the local thickness
        threshold = qim3d.operations.threshold(image, method="otsu")
        _logger.warning(
            f"Input image is not binary. It will be binarized using Otsu's method with threshold: {threshold}"
        )
        local_thickness = lt.local_thickness(image > threshold, scale=scale, mask=mask)
    else:
        # If it is binary, compute the local thickness directly
        local_thickness = lt.local_thickness(image, scale=scale, mask=mask)

    # Visualize the local thickness if requested
    if visualize:
        display(qim3d.viz.local_thickness(image, local_thickness, **viz_kwargs))

    return local_thickness

qim3d.processing.structure_tensor

structure_tensor(volume, sigma=1.0, rho=6.0, base_noise=True, smallest=True, visualize=False, **viz_kwargs)

Computes the Structure Tensor for 3D local orientation analysis.

The structure tensor is a matrix-based representation of partial derivatives. It is used to analyze the local orientation of features (like fibers, veins, or layers) in a 3D volume. By examining the eigenvalues and eigenvectors of this tensor, one can determine the dominant direction of structures at every voxel.

This implementation wraps the structure-tensor package, which offers fast, GPU-accelerated computation suitable for large datasets (e.g., micro-CT).

Parameters:

Name Type Description Default
volume ndarray

The input 3D volume.

required
sigma float

The noise scale. This defines the standard deviation of the Gaussian kernel used to smooth the image before calculating gradients. Features smaller than this scale are suppressed. Defaults to 1.0.

1.0
rho float

The integration scale. This defines the size of the neighborhood over which orientation information is averaged (integrated). Larger values yield smoother orientation fields but may blur distinct features. Defaults to 6.0.

6.0
base_noise bool

If True, adds infinitesimal noise to the volume before processing. This prevents numerical instability (NaNs) in uniform regions where gradients are zero. Defaults to True.

True
smallest bool

If True, returns only the eigenvector corresponding to the smallest eigenvalue. In gradient-based analysis, the smallest eigenvalue typically corresponds to the direction of least change (i.e., along the fiber/structure axis). If False, returns all eigenvectors. Defaults to True.

True
visualize bool

If True, immediately displays a visualization of the vector field using qim3d.viz.vectors. Defaults to False.

False
**viz_kwargs Any

Additional keyword arguments passed to the visualization function (e.g., n_vectors, opacity).

{}

Returns:

Type Description
(val, vec)

A tuple containing: * val (np.ndarray): An array of shape (3, Z, Y, X) containing the eigenvalues sorted in ascending order. * vec (np.ndarray): * If smallest is True: An array of shape (3, Z, Y, X) representing the vector components (z, y, x) of the primary orientation. * If smallest is False: An array of shape (3, 3, Z, Y, X) containing all three eigenvectors sorted by eigenvalue.

Raises:

Type Description
ValueError

If the input volume is not 3D.

Example

import qim3d

vol = qim3d.examples.fibers_150x150x150
val, vec = qim3d.processing.structure_tensor(vol, visualize = True, axis = 1)
structure tensor

Runtime and memory usage

structure tensor estimate time and mem Performance computed on Intel(R) Xeon(R) Gold 6226 CPU @ 2.70GHz.

Reference

Jeppesen, N., et al. "Quantifying effects of manufacturing methods on fiber orientation in unidirectional composites using structure tensor analysis." Composites Part A: Applied Science and Manufacturing 149 (2021): 106541. https://doi.org/10.1016/j.compositesa.2021.106541

@article{JEPPESEN2021106541,
title = {Quantifying effects of manufacturing methods on fiber orientation in unidirectional composites using structure tensor analysis},
journal = {Composites Part A: Applied Science and Manufacturing},
volume = {149},
pages = {106541},
year = {2021},
issn = {1359-835X},
doi = {[https://doi.org/10.1016/j.compositesa.2021.106541](https://doi.org/10.1016/j.compositesa.2021.106541)},
url = {[https://www.sciencedirect.com/science/article/pii/S1359835X21002633](https://www.sciencedirect.com/science/article/pii/S1359835X21002633)},
author = {N. Jeppesen and L.P. Mikkelsen and A.B. Dahl and A.N. Christensen and V.A. Dahl}
}
Source code in qim3d/processing/_structure_tensor.py
def structure_tensor(
    volume: np.ndarray,
    sigma: float = 1.0,
    rho: float = 6.0,
    base_noise: bool = True,
    smallest: bool = True,
    visualize: bool = False,
    **viz_kwargs,
) -> tuple[np.ndarray, np.ndarray]:
    """
    Computes the Structure Tensor for 3D local orientation analysis.

    The structure tensor is a matrix-based representation of partial derivatives. It is used to analyze the local orientation of features (like fibers, veins, or layers) in a 3D volume. By examining the eigenvalues and eigenvectors of this tensor, one can determine the dominant direction of structures at every voxel.

    This implementation wraps the [structure-tensor package](https://github.com/Skielex/structure-tensor/), which offers fast, GPU-accelerated computation suitable for large datasets (e.g., micro-CT).

    Args:
        volume (np.ndarray): The input 3D volume.
        sigma (float, optional): The noise scale. This defines the standard deviation of the Gaussian kernel used to smooth the image *before* calculating gradients. Features smaller than this scale are suppressed. Defaults to 1.0.
        rho (float, optional): The integration scale. This defines the size of the neighborhood over which orientation information is averaged (integrated). Larger values yield smoother orientation fields but may blur distinct features. Defaults to 6.0.
        base_noise (bool, optional): If `True`, adds infinitesimal noise to the volume before processing. This prevents numerical instability (NaNs) in uniform regions where gradients are zero. Defaults to `True`.
        smallest (bool, optional): If `True`, returns only the eigenvector corresponding to the **smallest** eigenvalue. In gradient-based analysis, the smallest eigenvalue typically corresponds to the direction of least change (i.e., **along** the fiber/structure axis). If `False`, returns all eigenvectors. Defaults to `True`.
        visualize (bool, optional): If `True`, immediately displays a visualization of the vector field using `qim3d.viz.vectors`. Defaults to `False`.
        **viz_kwargs (Any): Additional keyword arguments passed to the visualization function (e.g., `n_vectors`, `opacity`).

    Returns:
        (val, vec): A tuple containing:
            * **val** (np.ndarray): An array of shape `(3, Z, Y, X)` containing the eigenvalues sorted in ascending order.
            * **vec** (np.ndarray):
                * If `smallest` is `True`: An array of shape `(3, Z, Y, X)` representing the vector components (z, y, x) of the primary orientation.
                * If `smallest` is `False`: An array of shape `(3, 3, Z, Y, X)` containing all three eigenvectors sorted by eigenvalue.

    Raises:
        ValueError: If the input `volume` is not 3D.

    Example:
        ```python
        import qim3d

        vol = qim3d.examples.fibers_150x150x150
        val, vec = qim3d.processing.structure_tensor(vol, visualize = True, axis = 1)
        ```
        ![structure tensor](../../assets/screenshots/structure_tensor_visualization_fibers.gif)

    !!! info "Runtime and memory usage"
        ![structure tensor estimate time and mem](../../assets/screenshots/Structure_tensor_time_mem_estimation.png)
        Performance computed on Intel(R) Xeon(R) Gold 6226 CPU @ 2.70GHz.

    !!! quote "Reference"
        Jeppesen, N., et al. "Quantifying effects of manufacturing methods on fiber orientation in unidirectional composites using structure tensor analysis." Composites Part A: Applied Science and Manufacturing 149 (2021): 106541.
        <https://doi.org/10.1016/j.compositesa.2021.106541>

        ```bibtex
        @article{JEPPESEN2021106541,
        title = {Quantifying effects of manufacturing methods on fiber orientation in unidirectional composites using structure tensor analysis},
        journal = {Composites Part A: Applied Science and Manufacturing},
        volume = {149},
        pages = {106541},
        year = {2021},
        issn = {1359-835X},
        doi = {[https://doi.org/10.1016/j.compositesa.2021.106541](https://doi.org/10.1016/j.compositesa.2021.106541)},
        url = {[https://www.sciencedirect.com/science/article/pii/S1359835X21002633](https://www.sciencedirect.com/science/article/pii/S1359835X21002633)},
        author = {N. Jeppesen and L.P. Mikkelsen and A.B. Dahl and A.N. Christensen and V.A. Dahl}
        }
        ```
    """
    previous_logging_level = logging.getLogger().getEffectiveLevel()
    logging.getLogger().setLevel(logging.CRITICAL)
    import structure_tensor as st

    logging.getLogger().setLevel(previous_logging_level)

    if volume.ndim != 3:
        msg = "The input volume must be 3D"
        raise ValueError(msg)

    # Ensure volume is a float
    if volume.dtype != np.float32 and volume.dtype != np.float64:
        volume = volume.astype(np.float32)

    if base_noise:
        # Add small noise to the volume
        # FIXME: This is a temporary solution to avoid uniform regions with constant values
        # in the volume, which lead to numerical issues in the structure tensor computation
        vol_noisy = volume + np.random.default_rng(seed=0).uniform(
            0, 1e-10, size=volume.shape
        )

        # Compute the structure tensor (of volume with noise)
        s_vol = st.structure_tensor_3d(vol_noisy, sigma, rho)

    else:
        # Compute the structure tensor (of volume without noise)
        s_vol = st.structure_tensor_3d(volume, sigma, rho)

    # Compute the eigenvalues and eigenvectors of the structure tensor
    full = not smallest
    print(
        f"Computing eigenvalues and eigenvectors of the structure tensor, full = {full}"
    )
    val, vec = st.eig_special_3d(s_vol, full=full, eigenvalue_order="asc")

    if visualize:
        from qim3d.viz import vectors

        display(vectors(volume, vec, **viz_kwargs))

    return val, vec