segmentation

nrxrdct.laue.segmentation

nrxrdct.laue.segmentation

Detection and characterisation of diffraction spots in micro-Laue detector images.

Overview

Each detector frame goes through a fixed pipeline before orientation fitting:

  1. Background subtraction (:func:gaussian_background) — a large-sigma Gaussian (FFT-based, O(N log N)) estimates and removes the slowly varying background so that spot detection operates on a flat baseline.

  2. Segmentation — converts the background-subtracted image into a binary mask where True marks candidate spot pixels. Three algorithms are available (see below).

  3. Cleaning (:func:clean_segmentation) — removes objects that are too small (noise) or too large (artefacts), and discards spots that touch detector module gaps.

  4. Spot fitting (:func:write_h5_spotsfile) — crops a small ROI around each connected component, fits a mixture of rotated 2-D Gaussians, and writes the fitted peak positions and shape parameters to an HDF5 file. Pass fit_spots=False to skip fitting and store only the weighted centroids (much faster, sufficient for orientation indexing).

Segmentation methods

All three methods share the same interface: method(image, mask, **kwargs) → binary_mask. They all begin with log-scaling (log1p) and intensity normalisation so that the response is approximately independent of the absolute intensity level.

LoG — Laplacian-of-Gaussian (:func:LoG_segmentation) Best for round or ring-shaped spots of a predictable size. Applies a band-pass filter tuned by sigmas: small sigma → sensitive to small spots; large sigma → picks up extended features. A multi-scale list of sigmas yields a pixel-wise maximum so spots of different sizes are all detected. Works poorly on spots that sit on a strong, rapidly varying background.

WTH — White Top-Hat (:func:WTH_segmentation) Best for compact bright features on an uneven background (e.g. fluorescence halo, detector artefacts). The top-hat transform WTH = image − opening(image) cancels any background structure larger than the structuring element (disk of radius disk_radius) while preserving smaller bright spots. Multi-scale via a list of radii.

HYBRID — LoG + WTH union (:func:hybrid_segmentation) Runs LoG and WTH concurrently (all scales in a single thread pool), thresholds each family independently, then ORs the two masks. Useful when the frame contains both round spots (better by LoG) and sharp streaks or asymmetric peaks (better by WTH).

Choosing a method

  • Start with LoG and a scalar sigmas matched to the typical spot FWHM (roughly FWHM / 2.35).
  • If many spots are missed due to uneven background, switch to WTH and set disk_radius slightly larger than the largest expected spot.
  • Use HYBRID when the frame contains a mix of morphologies or when either method alone leaves significant false negatives.
  • Tune threshold_percentile last: raise it to reduce false positives (only the very brightest pixels survive), lower it to recover dim spots at the cost of more background noise.

HDF5 spot file format

Each frame is written to seg_dir/frame_{idx:05d}.h5. Inside, spots are stored in groups named spot_{ii:04d}_{jj} where ii is the region label and jj is the Gaussian component index (0 = unfitted fallback, 1+ = fitted components). Fields per group:

peak_X, peak_Y Sub-pixel centroid in detector pixel coordinates (column, row). peak_Itot, peak_Isub, peak_bkg Total amplitude, background-subtracted amplitude, and constant background of the fitted Gaussian. peak_fwaxmaj, peak_fwaxmin, peak_inclination Full-width at half-maximum along the major/minor axis (pixels) and tilt angle of the major axis (degrees). Xdev, Ydev Offset between the fitted centre and the ROI centre (pixels). r_squared Coefficient of determination of the Gaussian fit. -1 when fit_spots=False; 0 when fitting failed at runtime. image Raw ROI sub-image (cropped around the centroid). yxcen, bbox Weighted centroid and bounding box from :func:measure_peaks.

LoG_segmentation

LoG_segmentation(image: ndarray, mask: ndarray, sigmas=0.01, threshold_percentile: float = 99.9, local_threshold: bool = False, local_block_size: int = 256) -> np.ndarray

Segment diffraction spots using a Laplacian-of-Gaussian (LoG) filter.

The LoG acts as a band-pass filter that responds strongly to blobs whose spatial extent matches the filter scale. The negative LoG response (−∇²G * I) has a local maximum at the centre of each bright blob, making it well suited for detecting round or weakly elongated Laue spots.

The image is log-scaled (log1p) and intensity-normalised before filtering so the response is approximately gain-independent. When multiple sigmas are given, the pixel-wise maximum across all scales is taken, enabling simultaneous detection of spots with different sizes.

Parameters:
  • image ((Nv, Nh) ndarray) –

    Raw detector image (uint or float).

  • mask ((Nv, Nh) bool ndarray) –

    Valid-pixel mask (True = active detector pixel). Detector gaps and dead pixels should be False. Invalid pixels are filled with a nearest-neighbour interpolation before filtering to avoid edge artefacts.

  • sigmas (float or list of float, default: 0.01 ) –

    Gaussian sigma(s) in pixels for the LoG filter. A single value targets spots whose radius is roughly 2 * sigma pixels. Pass a list to detect spots over a range of sizes simultaneously (multi-scale LoG). Default 0.01 (very small, effectively a plain Laplacian on the log-scaled image).

  • threshold_percentile (float, default: 99.9 ) –

    Percentile of the LoG response used as the detection threshold. Only pixels above this level are labelled as spot pixels. Raise towards 100 to keep only the strongest responses; lower to recover dimmer spots at the cost of more false positives. Default 99.9.

  • local_threshold (bool, default: False ) –

    If True, compute the threshold locally via :func:_local_threshold_map using blocks of local_block_size pixels. This prevents a very bright streak or substrate spot from raising the threshold for faint neighbours. Default False.

  • local_block_size (int, default: 256 ) –

    Block size (pixels) for local threshold estimation. Smaller values make the threshold more adaptive but require more valid pixels per block. Default 256.

Returns:
  • mask_final( (Nv, Nh) bool ndarray ) –

    Binary segmentation mask (True = spot pixel). Pass to :func:clean_segmentation for size filtering and gap exclusion before :func:label_segmented_image.

See Also

WTH_segmentation : White top-hat segmentation (better for uneven backgrounds). hybrid_segmentation : LoG + WTH combined. clean_segmentation : Post-processing (size filter, border removal, gap exclusion).

Source code in src/nrxrdct/laue/segmentation.py
def LoG_segmentation(
    image: np.ndarray,
    mask: np.ndarray,
    sigmas=0.01,
    threshold_percentile: float = 99.9,
    local_threshold: bool = False,
    local_block_size: int = 256,
) -> np.ndarray:
    """
    Segment diffraction spots using a Laplacian-of-Gaussian (LoG) filter.

    The LoG acts as a band-pass filter that responds strongly to blobs whose
    spatial extent matches the filter scale.  The negative LoG response
    (``−∇²G * I``) has a local maximum at the centre of each bright blob,
    making it well suited for detecting round or weakly elongated Laue spots.

    The image is log-scaled (``log1p``) and intensity-normalised before
    filtering so the response is approximately gain-independent.  When multiple
    *sigmas* are given, the pixel-wise maximum across all scales is taken,
    enabling simultaneous detection of spots with different sizes.

    Args:
        image ((Nv, Nh) ndarray): Raw detector image (uint or float).
        mask ((Nv, Nh) bool ndarray): Valid-pixel mask (``True`` = active detector pixel).
            Detector gaps and dead pixels should be ``False``.  Invalid pixels
            are filled with a nearest-neighbour interpolation before filtering
            to avoid edge artefacts.
        sigmas (float or list of float): Gaussian sigma(s) in pixels for the LoG filter.  A single
            value targets spots whose radius is roughly ``2 * sigma`` pixels.
            Pass a list to detect spots over a range of sizes simultaneously
            (multi-scale LoG).  Default ``0.01`` (very small, effectively a
            plain Laplacian on the log-scaled image).
        threshold_percentile (float): Percentile of the LoG response used as the detection threshold.
            Only pixels above this level are labelled as spot pixels.  Raise
            towards 100 to keep only the strongest responses; lower to recover
            dimmer spots at the cost of more false positives.  Default ``99.9``.
        local_threshold (bool): If ``True``, compute the threshold locally via
            :func:`_local_threshold_map` using blocks of *local_block_size*
            pixels.  This prevents a very bright streak or substrate spot from
            raising the threshold for faint neighbours.  Default ``False``.
        local_block_size (int): Block size (pixels) for local threshold estimation.
            Smaller values make the threshold more adaptive but require more
            valid pixels per block.  Default ``256``.

    Returns:
        mask_final ((Nv, Nh) bool ndarray): Binary segmentation mask (``True`` = spot pixel).
            Pass to :func:`clean_segmentation` for size filtering and gap
            exclusion before :func:`label_segmented_image`.

    See Also:
        WTH_segmentation : White top-hat segmentation (better for uneven backgrounds).
        hybrid_segmentation : LoG + WTH combined.
        clean_segmentation : Post-processing (size filter, border removal, gap exclusion).
"""
    from concurrent.futures import ThreadPoolExecutor

    image = fill_gaps_nearest(image, mask)

    img = np.log1p(image)

    vmin, vmax = np.min(img[mask]), np.max(img[mask])

    if vmax > vmin:
        img = sk.exposure.rescale_intensity(img, in_range=(vmin, vmax))

    _sigmas = [sigmas] if np.isscalar(sigmas) else list(sigmas)

    def _log_response(s):
        return -ndi.gaussian_laplace(img, sigma=s)

    with ThreadPoolExecutor() as pool:
        responses = list(pool.map(_log_response, _sigmas))

    enhanced = np.max(responses, axis=0)
    enhanced[~mask] = 0

    if local_threshold:
        thresh = _local_threshold_map(enhanced, mask, local_block_size, threshold_percentile)
    else:
        thresh = np.percentile(enhanced[mask], threshold_percentile)

    mask_final = (enhanced >= thresh) & mask

    return mask_final

WTH_segmentation

WTH_segmentation(image: ndarray, mask: ndarray, disk_radius=7, threshold_percentile: float = 99.9, local_threshold: bool = False, local_block_size: int = 256) -> np.ndarray

Segment diffraction spots using a white top-hat transform.

The white top-hat WTH(I) = I - opening(I) suppresses slowly varying background while preserving bright compact features (spots) smaller than the structuring element. It is complementary to :func:LoG_segmentation: LoG excels at ring/blob detection; WTH is more robust when spots sit on a strong, uneven background (e.g. fluorescence or detector artefacts).

Parameters:
  • image ((Nv, Nh) ndarray) –

    Raw detector image (uint or float).

  • mask ((Nv, Nh) bool ndarray) –

    Valid-pixel mask (True = active detector area).

  • disk_radius (int or list of int, default: 7 ) –

    Radius (or list of radii) of the disk structuring element in pixels. When a list is given, the WTH response is computed at every radius and the pixel-wise maximum is taken, analogous to multi-scale LoG. Each radius should be larger than the largest spot but smaller than the background correlation length. Default 7.

  • threshold_percentile (float, default: 99.9 ) –

    Percentile of the WTH response (within mask) used as the binary threshold. Raise to keep only the brightest spots; lower to be more inclusive. Default 99.9.

Returns:
  • mask_final( (Nv, Nh) bool ndarray ) –

    Binary segmentation mask (True = spot pixel).

See Also: LoG_segmentation : Laplacian-of-Gaussian based segmentation. clean_segmentation : Post-processing (size filter, border removal, etc.).

Source code in src/nrxrdct/laue/segmentation.py
def WTH_segmentation(
    image: np.ndarray,
    mask: np.ndarray,
    disk_radius=7,
    threshold_percentile: float = 99.9,
    local_threshold: bool = False,
    local_block_size: int = 256,
) -> np.ndarray:
    """
    Segment diffraction spots using a white top-hat transform.

    The white top-hat `WTH(I) = I - opening(I)` suppresses slowly varying
    background while preserving bright compact features (spots) smaller than
    the structuring element.  It is complementary to
    :func:`LoG_segmentation`: LoG excels at ring/blob detection; WTH is more
    robust when spots sit on a strong, uneven background (e.g. fluorescence
    or detector artefacts).

    Args:
        image ((Nv, Nh) ndarray): Raw detector image (uint or float).
        mask ((Nv, Nh) bool ndarray): Valid-pixel mask (`True` = active detector area).
        disk_radius (int or list of int): Radius (or list of radii) of the disk structuring element in pixels.
            When a list is given, the WTH response is computed at every radius and
            the pixel-wise maximum is taken, analogous to multi-scale LoG.
            Each radius should be larger than the largest spot but smaller than
            the background correlation length.  Default `7`.
        threshold_percentile (float): Percentile of the WTH response (within *mask*) used as the binary
            threshold.  Raise to keep only the brightest spots; lower to be more
            inclusive.  Default `99.9`.

    Returns:
        mask_final ((Nv, Nh) bool ndarray): Binary segmentation mask (`True` = spot pixel).

    See Also:
    LoG_segmentation : Laplacian-of-Gaussian based segmentation.
    clean_segmentation : Post-processing (size filter, border removal, etc.).
"""
    image = fill_gaps_nearest(image, mask)

    img = np.log1p(image.astype(float))

    vmin, vmax = img[mask].min(), img[mask].max()
    if vmax > vmin:
        img = sk.exposure.rescale_intensity(img, in_range=(vmin, vmax))

    from concurrent.futures import ThreadPoolExecutor

    radii = [disk_radius] if np.isscalar(disk_radius) else list(disk_radius)

    def _wth_response(r):
        # grey_opening with a scalar size uses a square footprint processed
        # row- and column-wise via the van Herk–Gil–Werman O(N) algorithm,
        # which is independent of r — far faster than a disk for large radii.
        opened = ndi.grey_opening(img, size=2 * r + 1)
        return img - opened

    with ThreadPoolExecutor() as pool:
        responses = list(pool.map(_wth_response, radii))

    enhanced = np.max(responses, axis=0)
    enhanced[~mask] = 0.0

    if local_threshold:
        thresh = _local_threshold_map(enhanced, mask, local_block_size, threshold_percentile)
    else:
        thresh = np.percentile(enhanced[mask], threshold_percentile)

    mask_final = (enhanced >= thresh) & mask
    return mask_final

auto_init_gaussian_mixture_global

auto_init_gaussian_mixture_global(image, n_components=None, smooth_sigma=2, threshold_rel=0.2, min_distance=6)

Heuristic init for gaussian mixture: - smooth image - find local maxima via maximum_filter - keep peaks above threshold_rel * max - compute centers (y,x) sorted by peak value, optionally keep top n_components - build weights based on distance to centers with Gaussian kernel (smooth_sigma) - for each component: weighted mean + covariance -> (A, xm, ym, sx, sy, theta) - background C0 = median(img) - clamp params within bounds

Source code in src/nrxrdct/laue/segmentation.py
def auto_init_gaussian_mixture_global(
    image,
    n_components=None,
    smooth_sigma=2,
    threshold_rel=0.2,
    min_distance=6,
):
    """
    Heuristic init for gaussian mixture:
    - smooth image
    - find local maxima via maximum_filter
    - keep peaks above threshold_rel * max
    - compute centers (y,x) sorted by peak value, optionally keep top n_components
    - build weights based on distance to centers with Gaussian kernel (smooth_sigma)
    - for each component: weighted mean + covariance -> (A, xm, ym, sx, sy, theta)
    - background C0 = median(img)
    - clamp params within bounds
"""
    img = np.asarray(image, float)
    ny, nx = img.shape

    smoothed = ndi.gaussian_filter(img, smooth_sigma)
    neighborhood = ndi.maximum_filter(smoothed, size=min_distance)
    peaks = smoothed == neighborhood
    peaks &= smoothed > (threshold_rel * smoothed.max())

    labeled, num = ndi.label(peaks)
    slices = ndi.find_objects(labeled)

    peak_info = []
    for slc in slices:
        # argmax within slice then convert to global coords
        y, x = np.unravel_index(np.argmax(smoothed[slc]), smoothed[slc].shape)
        y += slc[0].start
        x += slc[1].start
        peak_info.append((smoothed[y, x], x, y))

    peak_info.sort(reverse=True)

    if n_components:
        peak_info = peak_info[:n_components]

    centers = np.array([(x, y) for _, x, y in peak_info])
    n = len(centers)

    Y, X = np.mgrid[0:ny, 0:nx]
    coords = np.column_stack([X.ravel(), Y.ravel()])
    pixels = img.ravel()

    dists = cdist(coords, centers)
    weights = np.exp(-(dists**2) / (2 * (smooth_sigma**2)))
    weights *= pixels[:, None]
    weights /= weights.sum(axis=1, keepdims=True) + 1e-12

    init_params = []

    for i in range(n):
        w = weights[:, i]
        total = w.sum() + 1e-12

        xm = (coords[:, 0] * w).sum() / total
        ym = (coords[:, 1] * w).sum() / total

        dx = coords[:, 0] - xm
        dy = coords[:, 1] - ym

        Ixx = (w * dx * dx).sum() / total
        Iyy = (w * dy * dy).sum() / total
        Ixy = (w * dx * dy).sum() / total

        cov = np.array([[Ixx, Ixy], [Ixy, Iyy]])
        eigvals, eigvecs = np.linalg.eigh(cov)

        sigma_x = np.sqrt(eigvals[1])
        sigma_y = np.sqrt(eigvals[0])

        theta = np.arctan2(eigvecs[1, 1], eigvecs[0, 1])

        # amplitude guess: pixel at center - median(img)
        A = img[int(centers[i, 1]), int(centers[i, 0])] - np.median(img)

        init_params += [A, xm, ym, sigma_x, sigma_y, theta]

    C0 = np.median(img)
    init_params.append(C0)

    # clamp to bounds used later
    lower = [0, 0, 0, 1e-6, 1e-6, -np.pi / 2] * n + [-np.inf]
    upper = [np.inf, nx, ny, nx, ny, np.pi / 2] * n + [np.inf]

    for ii in range(len(lower)):
        if init_params[ii] < lower[ii]:
            init_params[ii] = lower[ii]
        if init_params[ii] > upper[ii]:
            init_params[ii] = upper[ii]

    return init_params

clean_segmentation

clean_segmentation(segmented_image, detector_mask, intensity_image, min_size: int = 3, max_size: int = 500, gap_exclude: int = 3, gap_closing: int = 3)

Post-process a binary segmentation mask.

Parameters:
  • segmented_image ((Ny, Nx) bool ndarray) –

    Raw binary mask from the segmentation step.

  • detector_mask ((Ny, Nx) bool ndarray) –

    Valid-pixel mask (True = active pixel).

  • intensity_image ((Ny, Nx) ndarray) –

    Intensity image forwarded to skimage.measure.regionprops.

  • min_size, max_size (int) –

    Minimum / maximum connected-component area in pixels.

  • gap_exclude (int, default: 3 ) –

    Dilation radius (pixels) around detector gaps used to exclude spots that genuinely overlap a module edge or large dead region.

  • gap_closing (int, default: 3 ) –

    Closing radius (pixels) applied to detector_mask before the gap-exclusion dilation. Binary closing fills isolated bad pixels (single dead pixels, small clusters) that are surrounded by valid pixels, so that spots near those bad pixels are not incorrectly excluded. Set to 0 to disable. Default 3.

Returns:
  • final_mask( (Ny, Nx) bool ndarray ) –
  • valid_props( list of RegionProperties ) –
Source code in src/nrxrdct/laue/segmentation.py
def clean_segmentation(
    segmented_image,
    detector_mask,
    intensity_image,
    min_size: int = 3,
    max_size: int = 500,
    gap_exclude: int = 3,
    gap_closing: int = 3,
):
    """
    Post-process a binary segmentation mask.

    Args:
        segmented_image ((Ny, Nx) bool ndarray): Raw binary mask from the segmentation step.
        detector_mask ((Ny, Nx) bool ndarray): Valid-pixel mask (True = active pixel).
        intensity_image ((Ny, Nx) ndarray): Intensity image forwarded to `skimage.measure.regionprops`.
        min_size, max_size (int): Minimum / maximum connected-component area in pixels.
        gap_exclude (int): Dilation radius (pixels) around detector gaps used to exclude spots
            that genuinely overlap a module edge or large dead region.
        gap_closing (int): Closing radius (pixels) applied to *detector_mask* **before** the
            gap-exclusion dilation.  Binary closing fills isolated bad pixels
            (single dead pixels, small clusters) that are surrounded by valid
            pixels, so that spots near those bad pixels are not incorrectly
            excluded.  Set to `0` to disable.  Default `3`.

    Returns:
        final_mask ((Ny, Nx) bool ndarray):
        valid_props (list of RegionProperties):
"""
    seg = ndi.binary_fill_holes(segmented_image)
    seg = sk.morphology.remove_small_objects(seg, max_size=min_size - 1)
    seg = sk.morphology.closing(seg, sk.morphology.disk(1))
    seg = sk.segmentation.clear_border(seg)

    labels = sk.measure.label(seg, connectivity=2)

    # Close the valid-pixel mask to fill isolated bad pixels before dilating
    # the gap zone.  This prevents spots near single dead pixels or small
    # pixel clusters from being discarded, while real module edges (wider
    # than gap_closing) remain as exclusion boundaries.
    if gap_closing > 0:
        closed_mask = ndi.binary_closing(detector_mask, sk.morphology.disk(gap_closing))
    else:
        closed_mask = detector_mask
    gap_zone = ndi.binary_dilation(~closed_mask, sk.morphology.disk(gap_exclude))

    final_mask  = np.zeros_like(detector_mask)
    props       = sk.measure.regionprops(labels, intensity_image=intensity_image)
    valid_props = []
    for p in props:
        if not (min_size <= p.area <= max_size):
            continue
        coords = p.coords
        if np.any(gap_zone[coords[:, 0], coords[:, 1]]):
            continue
        final_mask[labels == p.label] = True
        valid_props.append(p)

    return final_mask, valid_props

convert_spotsfile2peaklist

convert_spotsfile2peaklist(h5path: str, include_unfitted: bool = False, r_squared_min: float = 0.9)

Read the spots HDF5 file and return an (N, 9) array of peak quantities, sorted by descending peak intensity.

peak_X, peak_Y, peak_I (Isub), peak_fwaxmaj, peak_fwaxmin,

peak_inclination, Xdev, Ydev, peak_bkg.

Parameters:
  • h5path (str) –

    Path to the spots HDF5 file produced by the segmentation pipeline.

  • include_unfitted (bool, default: False ) –

    If False (default) only spots with r_squared >= r_squared_min are returned. If True, spots whose Gaussian fit did not meet the threshold are also included: their pixel position is taken from the weighted centroid (yxcen), intensity from the peak pixel value of the stored sub-image, and all shape / background columns are set to 0.

  • r_squared_min (float, default: 0.9 ) –

    Minimum r² to consider a fit acceptable (default 0.9). Spots stored in the HDF5 file with r_squared below this value are treated as unfitted regardless of how they were written.

Returns:
  • peaklist( (N, 9) ndarray ) –

    empty (0, 9) if no spots are found.

Source code in src/nrxrdct/laue/segmentation.py
def convert_spotsfile2peaklist(
    h5path: str,
    include_unfitted: bool = False,
    r_squared_min: float = 0.9,
):
    """
    Read the spots HDF5 file and return an (N, 9) array of peak quantities,
    sorted by descending peak intensity.

    Columns: peak_X, peak_Y, peak_I (Isub), peak_fwaxmaj, peak_fwaxmin,
             peak_inclination, Xdev, Ydev, peak_bkg.

    Args:
        h5path (str): Path to the spots HDF5 file produced by the segmentation pipeline.
        include_unfitted (bool): If `False` (default) only spots with r_squared >= r_squared_min are
            returned.  If `True`, spots whose Gaussian fit did not meet the
            threshold are also included: their pixel position is taken from the
            weighted centroid (`yxcen`), intensity from the peak pixel value of
            the stored sub-image, and all shape / background columns are set to 0.
        r_squared_min (float): Minimum r² to consider a fit acceptable (default 0.9).  Spots stored
            in the HDF5 file with r_squared below this value are treated as
            unfitted regardless of how they were written.

    Returns:
        peaklist ((N, 9) ndarray): empty (0, 9) if no spots are found.
"""
    peak_X = []
    peak_Y = []
    peak_I = []
    peak_fwaxmaj = []
    peak_fwaxmin = []
    peak_inclination = []
    Xdev = []
    Ydev = []
    peak_bkg = []
    Ipixmax = []

    with h5py.File(h5path, "r") as hin:
        for key in hin.keys():
            r2 = hin[f"{key}/r_squared"][()]

            if r2 < r_squared_min:
                if not include_unfitted:
                    continue
                # Fall back to weighted centroid; shape fields are unknown
                yxcen = hin[f"{key}/yxcen"][()]
                img   = hin[f"{key}/image"][()]
                imax  = float(img.max()) if img.size > 0 else 0.0
                peak_X.append(float(yxcen[1]))   # col → X
                peak_Y.append(float(yxcen[0]))   # row → Y
                peak_I.append(imax)
                peak_fwaxmaj.append(0.0)
                peak_fwaxmin.append(0.0)
                peak_inclination.append(0.0)
                Xdev.append(0.0)
                Ydev.append(0.0)
                peak_bkg.append(0.0)
                Ipixmax.append(imax)
                continue

            peak_X.append(hin[f"{key}/peak_X"][()])
            peak_Y.append(hin[f"{key}/peak_Y"][()])
            peak_I.append(hin[f"{key}/peak_Isub"][()])
            peak_fwaxmaj.append(hin[f"{key}/peak_fwaxmaj"][()])
            peak_fwaxmin.append(hin[f"{key}/peak_fwaxmin"][()])
            peak_inclination.append(hin[f"{key}/peak_inclination"][()])
            Xdev.append(hin[f"{key}/Xdev"][()])
            Ydev.append(hin[f"{key}/Ydev"][()])
            peak_bkg.append(hin[f"{key}/peak_bkg"][()])
            Ipixmax.append(hin[f"{key}/Ipixmax"][()])

    if not peak_X:
        return np.empty((0, 9), dtype=np.float64)

    peaklist = np.stack(
        [peak_X, peak_Y, peak_I, peak_fwaxmaj, peak_fwaxmin,
         peak_inclination, Xdev, Ydev, peak_bkg],
        axis=1,
    )

    order = np.argsort(Ipixmax)
    return peaklist[order][::-1]

convert_spotsfiles_to_dat

convert_spotsfiles_to_dat(seg_dir: str, target_dir: str, *, include_unfitted: bool = False, r_squared_min: float = 0.9, n_workers: int | None = None, overwrite: bool = False) -> int

Convert all frame_?????.h5 spot files in seg_dir to DAT files in target_dir, using a process pool for true parallelism.

Parameters:
  • seg_dir (str) –

    Directory containing frame_?????.h5 spot files.

  • target_dir (str) –

    Directory where frame_?????.dat files will be written.

  • include_unfitted (bool, default: False ) –

    Passed to :func:convert_spotsfile2peaklist.

  • r_squared_min (float, default: 0.9 ) –

    Passed to :func:convert_spotsfile2peaklist.

  • n_workers (int or None, default: None ) –

    Number of worker processes. Defaults to os.cpu_count().

  • overwrite (bool, default: False ) –

    If False (default), skip files that already exist in target_dir.

Returns:
  • int –

    int Number of files successfully converted.

Source code in src/nrxrdct/laue/segmentation.py
def convert_spotsfiles_to_dat(
    seg_dir: str,
    target_dir: str,
    *,
    include_unfitted: bool = False,
    r_squared_min: float = 0.9,
    n_workers: int | None = None,
    overwrite: bool = False,
) -> int:
    """
    Convert all `frame_?????.h5` spot files in *seg_dir* to DAT files in
    *target_dir*, using a process pool for true parallelism.

    Args:
        seg_dir (str): Directory containing `frame_?????.h5` spot files.
        target_dir (str): Directory where `frame_?????.dat` files will be written.
        include_unfitted (bool): Passed to :func:`convert_spotsfile2peaklist`.
        r_squared_min (float): Passed to :func:`convert_spotsfile2peaklist`.
        n_workers (int or None): Number of worker processes.  Defaults to `os.cpu_count()`.
        overwrite (bool): If `False` (default), skip files that already exist in *target_dir*.

    Returns:
        int
            Number of files successfully converted.
"""
    os.makedirs(target_dir, exist_ok=True)

    h5_files = sorted(glob.glob(os.path.join(seg_dir, "frame_*.h5")))
    if not h5_files:
        print(f"No frame_*.h5 files found in {seg_dir!r}")
        return 0

    tasks = []
    for h5path in h5_files:
        stem = os.path.splitext(os.path.basename(h5path))[0]
        out_path = os.path.join(target_dir, stem + ".dat")
        if os.path.exists(out_path) and not overwrite:
            continue
        tasks.append((h5path, out_path, include_unfitted, r_squared_min))

    n_already = len(h5_files) - len(tasks)
    if not tasks:
        print(f"All {len(h5_files)} files already converted.")
        return len(h5_files)

    _n_workers = n_workers or os.cpu_count() or 1
    n_ok = n_already
    with concurrent.futures.ProcessPoolExecutor(max_workers=_n_workers) as pool:
        futs = {pool.submit(_convert_one_h5_to_dat, t): t for t in tasks}
        for fut in concurrent.futures.as_completed(futs):
            if fut.result():
                n_ok += 1

    print(f"Converted {n_ok}/{len(h5_files)} spot files → {target_dir!r}")
    return n_ok

fill_gaps_nearest

fill_gaps_nearest(image: ndarray, valid_mask: ndarray) -> np.ndarray

Fast nearest-neighbor gap filling.

Source code in src/nrxrdct/laue/segmentation.py
def fill_gaps_nearest(image:np.ndarray, valid_mask:np.ndarray)-> np.ndarray:
    """Fast nearest-neighbor gap filling."""
    _, indices = ndi.distance_transform_edt(
        ~valid_mask,
        return_indices=True
    )
    return image[tuple(indices)]

filter_and_rescale_images

filter_and_rescale_images(im_array: ndarray, filter_type: str = 'max', cutoff_freq: float = 0.005)

Reduce a stack of images (N, ny, nx) to a 2D image by applying a reduction along axis 0 (min/max/mean/std/median), then apply a Butterworth filter and rescale to float32 in a [0,1]-like range (min-subtracted).

Source code in src/nrxrdct/laue/segmentation.py
def filter_and_rescale_images(
    im_array: np.ndarray, filter_type: str = "max", cutoff_freq: float = 0.005
):
    """
    Reduce a stack of images (N, ny, nx) to a 2D image by applying a reduction
    along axis 0 (min/max/mean/std/median), then apply a Butterworth filter and
    rescale to float32 in a [0,1]-like range (min-subtracted).
"""
    if im_array.ndim == 3:
        print(f"3D image will be reduced with the {filter_type} filter along axis 0.")

        if filter_type not in ("min", "max", "mean", "std", "median"):
            print("Filter not implemented. Quiting...")
            return 1

        if filter_type == "max":
            filt_im = im_array.max(axis=0)
        elif filter_type == "min":
            filt_im = im_array.min(axis=0)
        elif filter_type == "mean":
            filt_im = im_array.mean(axis=0)
        elif filter_type == "std":
            filt_im = im_array.std(axis=0)
        elif filter_type == "median":
            filt_im = np.median(im_array, axis=0)
    else:
        filt_im = im_array

    # sk.filters.butterworth exists in skimage >=0.19-ish; keep as-is
    filt_im = sk.filters.butterworth(filt_im, cutoff_frequency_ratio=cutoff_freq)

    # subtract minimum and cast to float32
    filt_im = sk.util.img_as_float32(filt_im - filt_im.min())
    return filt_im

fit_gaussian_2d_rotated

fit_gaussian_2d_rotated(image)

Fit a single rotated 2D gaussian to an image using curve_fit. Returns (popt, pcov, fit_img, x, y)

Source code in src/nrxrdct/laue/segmentation.py
def fit_gaussian_2d_rotated(image):
    """
    Fit a single rotated 2D gaussian to an image using curve_fit.
    Returns (popt, pcov, fit_img, x, y)
"""
    image = np.asarray(image)
    ny, nx = image.shape

    x = np.arange(nx)
    y = np.arange(ny)
    x, y = np.meshgrid(x, y)

    A0 = image.max() - np.abs(image.min())
    C0 = np.abs(image.min())

    total = image.sum()
    x0 = (x * image).sum() / total
    y0 = (y * image).sum() / total

    sigma_x0 = nx / 4
    sigma_y0 = ny / 4
    theta0 = 0.0

    p0 = (A0, x0, y0, sigma_x0, sigma_y0, theta0, C0)

    coords = np.vstack((x.ravel(), y.ravel()))
    data = image.ravel()

    lower = [0, 0, 0, 1e-6, 1e-6, -np.pi / 2, -np.inf]
    upper = [np.inf, nx, ny, nx, ny, np.pi / 2, np.inf]
    bounds = (lower, upper)

    popt, pcov = curve_fit(
        gaussian_2d_rotated, coords, data, p0=p0, bounds=bounds, maxfev=10000
    )

    fit_img = gaussian_2d_rotated(coords, *popt).reshape(ny, nx)

    return popt, pcov, fit_img, x, y

fit_gaussian_mixture_2d

fit_gaussian_mixture_2d(image, n_components: int, init_params)

Fit mixture of n_components rotated Gaussians + constant background. init_params should be a list of length 6*n_components + 1 (including C). Returns (popt, pcov, fitted, X, Y)

Source code in src/nrxrdct/laue/segmentation.py
def fit_gaussian_mixture_2d(image, n_components: int, init_params):
    """
    Fit mixture of n_components rotated Gaussians + constant background.
    init_params should be a list of length 6*n_components + 1 (including C).
    Returns (popt, pcov, fitted, X, Y)
"""
    image = np.asarray(image)
    ny, nx = image.shape

    x = np.arange(nx)
    y = np.arange(ny)
    X, Y = np.meshgrid(x, y)

    coords = np.vstack((X.ravel(), Y.ravel()))
    data = image.ravel()

    lower = []
    upper = []
    for _ in range(n_components):
        lower += [0, 0, 0, 1e-6, 1e-6, -np.pi / 2]
        upper += [np.inf, nx, ny, nx, ny, np.pi / 2]

    lower += [-np.inf]
    upper += [np.inf]
    bounds = (lower, upper)

    popt, pcov = curve_fit(
        gaussian_mixture_2d, coords, data, p0=init_params, bounds=bounds, maxfev=20000
    )

    fitted = gaussian_mixture_2d(coords, *popt).reshape(ny, nx)
    return popt, pcov, fitted, X, Y

fwhm_from_sigma

fwhm_from_sigma(s)

Convert Gaussian sigma to FWHM: FWHM = 2√(2 ln 2) · σ ≈ 2.355 σ.

Source code in src/nrxrdct/laue/segmentation.py
def fwhm_from_sigma(s):
    """Convert Gaussian sigma to FWHM: ``FWHM = 2√(2 ln 2) · σ ≈ 2.355 σ``."""
    return 2 * np.sqrt(2 * np.log(2)) * s

gaussian_2d_rotated

gaussian_2d_rotated(coords, A, x0, y0, sigma_x, sigma_y, theta, C)

Rotated 2D Gaussian + offset, returns raveled model. coords = (x, y) as 2 arrays (meshgrid flattened later).

Source code in src/nrxrdct/laue/segmentation.py
def gaussian_2d_rotated(coords, A, x0, y0, sigma_x, sigma_y, theta, C):
    """
    Rotated 2D Gaussian + offset, returns raveled model.
    coords = (x, y) as 2 arrays (meshgrid flattened later).
"""
    x, y = coords

    x0 = float(x0)
    y0 = float(y0)

    cos_t = np.cos(theta)
    sin_t = np.sin(theta)

    a = (cos_t**2) / (2 * sigma_x**2) + (sin_t**2) / (2 * sigma_y**2)
    b = (-np.sin(2 * theta)) / (4 * sigma_x**2) + (np.sin(2 * theta)) / (4 * sigma_y**2)
    c = (sin_t**2) / (2 * sigma_x**2) + (cos_t**2) / (2 * sigma_y**2)

    g = (
        A
        * np.exp(-(a * (x - x0) ** 2 + 2 * b * (x - x0) * (y - y0) + c * (y - y0) ** 2))
        + C
    )

    return g.ravel()

gaussian_background

gaussian_background(image, valid_mask, sigma=251)

Estimate a smooth background via FFT-based Gaussian filtering.

Uses FFT convolution (O(N log N)) so large sigma values are fast. workers=-1 lets scipy use all available CPU cores for the FFT.

Source code in src/nrxrdct/laue/segmentation.py
def gaussian_background(image, valid_mask, sigma=251):
    """Estimate a smooth background via FFT-based Gaussian filtering.

    Uses FFT convolution (O(N log N)) so large sigma values are fast.
    `workers=-1` lets scipy use all available CPU cores for the FFT.
"""
    def _fft_gauss(arr):
        f = sp_fft.fft2(arr, workers=-1)
        ndi.fourier_gaussian(f, sigma=sigma, output=f)
        return sp_fft.ifft2(f, workers=-1).real.astype(np.float32)

    img = image.astype(np.float32).copy()
    img[~valid_mask] = 0.0

    smooth = _fft_gauss(img)
    norm   = _fft_gauss(valid_mask.astype(np.float32))
    norm[norm < 1e-6] = 1.0

    return smooth / norm

gaussian_mixture_2d

gaussian_mixture_2d(coords, *params)

Sum of n rotated Gaussians + constant background C (last param). params layout: [A1, x01, y01, sx1, sy1, th1, A2, x02, y02, sx2, sy2, th2, ..., C]

Source code in src/nrxrdct/laue/segmentation.py
def gaussian_mixture_2d(coords, *params):
    """
    Sum of n rotated Gaussians + constant background C (last param).
    params layout:
      [A1, x01, y01, sx1, sy1, th1,  A2, x02, y02, sx2, sy2, th2, ..., C]
"""
    x, y = coords
    n = (len(params) - 1) // 6
    C = params[-1]

    model = np.zeros_like(x, dtype=float)

    for i in range(n):
        A, x0, y0, sx, sy, th = params[6 * i : 6 * i + 6]

        cos_t = np.cos(th)
        sin_t = np.sin(th)

        a = (cos_t**2) / (2 * sx**2) + (sin_t**2) / (2 * sy**2)
        b = (-np.sin(2 * th)) / (4 * sx**2) + (np.sin(2 * th)) / (4 * sy**2)
        c = (sin_t**2) / (2 * sx**2) + (cos_t**2) / (2 * sy**2)

        model += A * np.exp(
            -(a * (x - x0) ** 2 + 2 * b * (x - x0) * (y - y0) + c * (y - y0) ** 2)
        )

    return (model + C).ravel()

get_spot_limits

get_spot_limits(image_array, ycen, xcen, d)

Return (ymin, ymax, xmin, xmax) for a 2d × 2d ROI centred at (ycen, xcen), clipped to the image boundaries.

Source code in src/nrxrdct/laue/segmentation.py
def get_spot_limits(image_array, ycen, xcen, d):
    """Return (ymin, ymax, xmin, xmax) for a ``2d × 2d`` ROI centred at (ycen, xcen),
    clipped to the image boundaries."""
    ymin, ymax = int(ycen - d), int(ycen + d)
    xmin, xmax = int(xcen - d), int(xcen + d)

    if ymin < 0:
        ymin = 0

    if ymax > image_array.shape[0]:
        ymax = image_array.shape[0]
    if xmin < 0:
        xmin = 0

    if xmax > image_array.shape[0]:
        xmax = image_array.shape[0]

    return ymin, ymax, xmin, xmax

hybrid_segmentation

hybrid_segmentation(image: ndarray, mask: ndarray, log_sigmas=None, wth_disk_radius=None, threshold_percentile: float = 99.9, local_threshold: bool = False, local_block_size: int = 256) -> np.ndarray

Segment diffraction spots by combining LoG (large/round spots) and WTH (small/sharp spots) responses.

All scales from both methods are submitted to a single ThreadPoolExecutor so every allocated CPU is used without thread-pool nesting or oversubscription. The two families are thresholded independently at threshold_percentile and the results are combined with a logical OR.

Parameters:
  • image ((Nv, Nh) ndarray) –

    Raw detector image.

  • mask ((Nv, Nh) bool ndarray) –

    Valid-pixel mask.

  • log_sigmas (float or list of float, default: None ) –

    Sigma(s) for the Laplacian-of-Gaussian filter. Default [2, 4, 8].

  • wth_disk_radius (int or list of int, default: None ) –

    Disk radius/radii for the white top-hat transform. Default [5, 7].

  • threshold_percentile (float, default: 99.9 ) –

    Detection threshold percentile applied independently to each family. Default 99.9.

Returns:
  • mask_final( (Nv, Nh) bool ndarray ) –

    Union of the LoG and WTH binary masks.

Source code in src/nrxrdct/laue/segmentation.py
def hybrid_segmentation(
    image: np.ndarray,
    mask: np.ndarray,
    log_sigmas=None,
    wth_disk_radius=None,
    threshold_percentile: float = 99.9,
    local_threshold: bool = False,
    local_block_size: int = 256,
) -> np.ndarray:
    """
    Segment diffraction spots by combining LoG (large/round spots) and WTH
    (small/sharp spots) responses.

    All scales from both methods are submitted to a single
    `ThreadPoolExecutor` so every allocated CPU is used without
    thread-pool nesting or oversubscription.  The two families are
    thresholded independently at *threshold_percentile* and the results
    are combined with a logical OR.

    Args:
        image ((Nv, Nh) ndarray): Raw detector image.
        mask ((Nv, Nh) bool ndarray): Valid-pixel mask.
        log_sigmas (float or list of float): Sigma(s) for the Laplacian-of-Gaussian filter.  Default `[2, 4, 8]`.
        wth_disk_radius (int or list of int): Disk radius/radii for the white top-hat transform.  Default `[5, 7]`.
        threshold_percentile (float): Detection threshold percentile applied independently to each family.
            Default `99.9`.

    Returns:
        mask_final ((Nv, Nh) bool ndarray): Union of the LoG and WTH binary masks.
"""
    from concurrent.futures import ThreadPoolExecutor

    if log_sigmas is None:
        log_sigmas = [2, 4, 8]
    if wth_disk_radius is None:
        wth_disk_radius = [5, 7]

    image = fill_gaps_nearest(image, mask)
    img = np.log1p(image.astype(float))
    vmin, vmax = img[mask].min(), img[mask].max()
    if vmax > vmin:
        img = sk.exposure.rescale_intensity(img, in_range=(vmin, vmax))

    _log_sigmas = [log_sigmas] if np.isscalar(log_sigmas) else list(log_sigmas)
    _radii      = [wth_disk_radius] if np.isscalar(wth_disk_radius) else list(wth_disk_radius)

    def _log(s):
        return -ndi.gaussian_laplace(img, sigma=s)

    def _wth(r):
        return sk.morphology.white_tophat(img, sk.morphology.disk(r))

    with ThreadPoolExecutor() as pool:
        log_futures = [pool.submit(_log, s) for s in _log_sigmas]
        wth_futures = [pool.submit(_wth, r) for r in _radii]
        log_responses = [f.result() for f in log_futures]
        wth_responses = [f.result() for f in wth_futures]

    def _threshold(responses):
        enhanced = np.max(responses, axis=0)
        enhanced[~mask] = 0.0
        if local_threshold:
            thresh = _local_threshold_map(enhanced, mask, local_block_size, threshold_percentile)
        else:
            thresh = np.percentile(enhanced[mask], threshold_percentile)
        return (enhanced >= thresh) & mask

    return _threshold(log_responses) | _threshold(wth_responses)

label_segmented_image

label_segmented_image(im_array: ndarray, intensity_image=None)

Label segmented boolean image, clear borders, return: (label_image, n_labels, label_img_rgb)

Source code in src/nrxrdct/laue/segmentation.py
def label_segmented_image(im_array: np.ndarray, intensity_image=None):
    """
    Label segmented boolean image, clear borders, return:
    (label_image, n_labels, label_img_rgb)
"""
    if im_array.dtype != bool:
        print("I need a boolean array. Quiting...")
        return 1

    im_array = sk.segmentation.clear_border(im_array)

    label_image, n_labels = sk.measure.label(im_array, return_num=True, connectivity=2)

    label_img_rgb = sk.color.label2rgb(label_image, image=intensity_image, bg_label=0)

    return label_image, n_labels, label_img_rgb

load_images

load_images(dirpath: str) -> np.ndarray

Load all .tif images in a directory into a 3D array: (Nimages, ny, nx). Uses ProcessPoolExecutor to parallelize skimage.io.imread.

Source code in src/nrxrdct/laue/segmentation.py
def load_images(dirpath: str) -> np.ndarray:
    """
    Load all .tif images in a directory into a 3D array: (Nimages, ny, nx).
    Uses ProcessPoolExecutor to parallelize skimage.io.imread.
"""
    im_files = glob.glob(f"{dirpath}/*.tif")
    im_files.sort()

    images = [None] * len(im_files)

    with concurrent.futures.ProcessPoolExecutor() as pool:
        for ii, image in enumerate(pool.map(sk.io.imread, im_files)):
            images[ii] = image

    return np.array(images)

measure_peaks

measure_peaks(labeled_image, intensity_image)

Wrapper for skimage.measure.regionprops.

Source code in src/nrxrdct/laue/segmentation.py
def measure_peaks(labeled_image, intensity_image):
    """
    Wrapper for skimage.measure.regionprops.
"""
    return sk.measure.regionprops(labeled_image, intensity_image=intensity_image)

r_squared_image

r_squared_image(data, model, mask=None)

R^2 = 1 - SS_res / SS_tot, computed on flattened arrays, optionally using boolean mask.

Source code in src/nrxrdct/laue/segmentation.py
def r_squared_image(data, model, mask=None):
    """
    R^2 = 1 - SS_res / SS_tot, computed on flattened arrays,
    optionally using boolean mask.
"""
    data = np.asarray(data, float)
    model = np.asarray(model, float)

    if mask is not None:
        data = data[mask]
        model = model[mask]
    else:
        data = data.ravel()
        model = model.ravel()

    ss_res = np.sum((data - model) ** 2)
    ss_tot = np.sum((data - np.mean(data)) ** 2)
    return 1 - ss_res / ss_tot

reduced_chi_squared

reduced_chi_squared(data, model, n_params: int = 2, noise_std=None, mask=None)

Reduced chi^2 with optional per-pixel noise_std. If noise_std is None, estimate using MAD of residuals.

Source code in src/nrxrdct/laue/segmentation.py
def reduced_chi_squared(data, model, n_params: int = 2, noise_std=None, mask=None):
    """
    Reduced chi^2 with optional per-pixel noise_std.
    If noise_std is None, estimate using MAD of residuals.
"""
    data = np.asarray(data, float)
    model = np.asarray(model, float)

    if mask is not None:
        data = data[mask]
        model = model[mask]
        N = mask.sum()
    else:
        data = data.ravel()
        model = model.ravel()
        N = data.size

    residuals = data - model

    if noise_std is None:
        mad = np.median(np.abs(residuals - np.median(residuals)))
        noise_std = 1.4826 * mad + 1e-12

    # if noise_std is an array, flatten or mask it
    if np.ndim(noise_std) > 0:
        if mask is not None:
            noise_std = noise_std[mask]
        else:
            noise_std = np.ravel(noise_std)

    chi2 = np.sum((residuals / noise_std) ** 2)
    dof = max(N - n_params, 1)
    return chi2 / dof

reduced_chi_squared_poisson

reduced_chi_squared_poisson(data, model, n_params: int = 2, gain: float = 1.0, read_noise: float = 0.0, eps: float = 1e-12, mask=None)

Reduced chi^2 assuming Poisson + read noise. Converts ADU->e- using gain. variance = model_e + read_noise^2, clipped by eps.

Source code in src/nrxrdct/laue/segmentation.py
def reduced_chi_squared_poisson(
    data,
    model,
    n_params: int = 2,
    gain: float = 1.0,
    read_noise: float = 0.0,
    eps: float = 1e-12,
    mask=None,
):
    """
    Reduced chi^2 assuming Poisson + read noise.
    Converts ADU->e- using gain.
    variance = model_e + read_noise^2, clipped by eps.
"""
    data = np.asarray(data, float)
    model = np.asarray(model, float)

    if mask is not None:
        data = data[mask]
        model = model[mask]
        N = mask.sum()
    else:
        data = data.ravel()
        model = model.ravel()
        N = data.size

    model_e = model * gain
    data_e = data * gain

    variance = model_e + (read_noise**2)
    variance = np.maximum(variance, eps)

    chi2 = np.sum((data_e - model_e) ** 2 / variance)
    dof = max(N - n_params, 1)
    return chi2 / dof

run_segmentation_local

run_segmentation_local(image_stack: ndarray, seg_dir: str, detector_mask: ndarray | None = None, method: str = 'LoG', method_kwargs: dict | None = None, min_size: int = 3, max_size: int = 500, gap_exclude: int = 3, gap_closing: int = 3, bg_sigma: float = 251.0, max_components: int = 1, n_workers: int | None = None, overwrite: bool = False, frame_indices=None) -> list

Run the Laue segmentation pipeline locally using multiple CPU cores.

Mirrors the SLURM worker pipeline (background subtraction → segmentation → cleaning → Gaussian fitting → HDF5 output) but runs in-process using a ProcessPoolExecutor instead of submitting cluster jobs.

Parameters:
  • image_stack ((N, Ny, Nx) ndarray) –

    Stack of raw detector frames, already loaded into memory.

  • seg_dir (str) –

    Output directory. One frame_{idx:05d}.h5 file is written per frame.

  • detector_mask ((Ny, Nx) bool ndarray or None, default: None ) –

    Valid-pixel mask (True = active pixel). None → all pixels active.

  • method ({LoG, WTH, HYBRID}, default: 'LoG' ) –

    Segmentation method passed to the corresponding function.

  • method_kwargs (dict or None, default: None ) –

    Extra keyword arguments forwarded to the segmentation function.

  • min_size, max_size (int) –

    Minimum / maximum spot area in pixels after cleaning.

  • gap_exclude (int, default: 3 ) –

    Dilation radius (pixels) around detector gaps excluded during cleaning.

  • gap_closing (int, default: 3 ) –

    Closing radius (pixels) applied to the valid-pixel mask before the gap-exclusion dilation. Fills isolated dead pixels so spots near bad pixels are not incorrectly excluded. Default 3.

  • bg_sigma (float, default: 251.0 ) –

    Sigma (pixels) for the Gaussian background estimate.

  • max_components (int, default: 1 ) –

    Maximum number of Gaussian components fitted per spot.

  • n_workers (int or None, default: None ) –

    Number of worker processes. None → os.cpu_count().

  • overwrite (bool, default: False ) –

    If False (default), skip frames whose output file already exists.

  • frame_indices (sequence of int or None, default: None ) –

    Subset of frame indices to process. None → all frames.

Returns:
  • out_paths( list of str ) –

    Paths of successfully written HDF5 files, sorted by frame index.

Source code in src/nrxrdct/laue/segmentation.py
def run_segmentation_local(
    image_stack: np.ndarray,
    seg_dir: str,
    detector_mask: np.ndarray | None = None,
    method: str = "LoG",
    method_kwargs: dict | None = None,
    min_size: int = 3,
    max_size: int = 500,
    gap_exclude: int = 3,
    gap_closing: int = 3,
    bg_sigma: float = 251.0,
    max_components: int = 1,
    n_workers: int | None = None,
    overwrite: bool = False,
    frame_indices=None,
) -> list:
    """
    Run the Laue segmentation pipeline locally using multiple CPU cores.

    Mirrors the SLURM worker pipeline (background subtraction → segmentation
    → cleaning → Gaussian fitting → HDF5 output) but runs in-process using
    a `ProcessPoolExecutor` instead of submitting cluster jobs.

    Args:
        image_stack ((N, Ny, Nx) ndarray): Stack of raw detector frames, already loaded into memory.
        seg_dir (str): Output directory.  One `frame_{idx:05d}.h5` file is written per frame.
        detector_mask ((Ny, Nx) bool ndarray or None): Valid-pixel mask (True = active pixel).  None → all pixels active.
        method ({'LoG', 'WTH', 'HYBRID'}): Segmentation method passed to the corresponding function.
        method_kwargs (dict or None): Extra keyword arguments forwarded to the segmentation function.
        min_size, max_size (int): Minimum / maximum spot area in pixels after cleaning.
        gap_exclude (int): Dilation radius (pixels) around detector gaps excluded during cleaning.
        gap_closing (int): Closing radius (pixels) applied to the valid-pixel mask before the
            gap-exclusion dilation.  Fills isolated dead pixels so spots near bad
            pixels are not incorrectly excluded.  Default `3`.
        bg_sigma (float): Sigma (pixels) for the Gaussian background estimate.
        max_components (int): Maximum number of Gaussian components fitted per spot.
        n_workers (int or None): Number of worker processes.  None → `os.cpu_count()`.
        overwrite (bool): If False (default), skip frames whose output file already exists.
        frame_indices (sequence of int or None): Subset of frame indices to process.  None → all frames.

    Returns:
        out_paths (list of str): Paths of successfully written HDF5 files, sorted by frame index.
"""
    import time

    os.makedirs(seg_dir, exist_ok=True)

    if frame_indices is None:
        frame_indices = range(image_stack.shape[0])
    frame_indices = list(frame_indices)
    method_kwargs = method_kwargs or {}

    print(
        f"run_segmentation_local — {len(frame_indices)} frames  "
        f"method={method}  workers={n_workers or os.cpu_count()}",
        flush=True,
    )

    t0        = time.time()
    n_ok      = 0
    n_fail    = 0
    out_paths = []
    n_total   = len(frame_indices)
    tick      = max(1, n_total // 20)   # print every ~5 %

    with concurrent.futures.ProcessPoolExecutor(max_workers=n_workers) as pool:
        futures = {
            pool.submit(
                _seg_process_frame,
                fi,
                image_stack[fi].astype(np.float32),
                seg_dir,
                detector_mask,
                method,
                method_kwargs,
                min_size,
                max_size,
                gap_exclude,
                gap_closing,
                bg_sigma,
                max_components,
                overwrite,
            ): fi
            for fi in frame_indices
        }

        done = 0
        for fut in concurrent.futures.as_completed(futures):
            done += 1
            fi, ok, result = fut.result()
            if ok:
                n_ok += 1
                out_paths.append(result)
            else:
                n_fail += 1
                print(f"  ✗  frame {fi}: {result}", flush=True)

            if done % tick == 0 or done == n_total:
                elapsed = time.time() - t0
                rate    = done / elapsed
                eta     = (n_total - done) / rate if rate > 0 else float("inf")
                print(
                    f"  {done}/{n_total}  "
                    f"({n_ok} ok, {n_fail} failed)  "
                    f"{elapsed:.0f}s elapsed  ETA {eta:.0f}s",
                    flush=True,
                )

    out_paths.sort()
    print(
        f"\nDone — {n_ok}/{n_total} OK, {n_fail} failed  "
        f"({time.time() - t0:.1f}s total)",
        flush=True,
    )
    return out_paths

segment_image

segment_image(im_array: ndarray, kernel_size: int = 3, sigma: float = 0.1, iterations: int = 1, threshold: float = None)

Segment image into a boolean mask.

Parameters:
  • im_array (ndarray) –

    2-D intensity image, or 3-D stack reduced by max(axis=0).

  • kernel_size (int, default: 3 ) –

    Side length of the square structuring element used for binary opening.

  • sigma (float, default: 0.1 ) –

    Gaussian smoothing applied to the binary mask before returning. Set to 0 to skip. Note: smoothing is applied to the float representation of the mask and then thresholded at 0.5 so the output remains boolean.

  • iterations (int, default: 1 ) –

    Number of binary-opening iterations. Each iteration with a 3×3 element erodes features by ~1 pixel per side; spots smaller than roughly (2*iterations + 1)² pixels may be completely erased. Default 1 (single pass) to preserve small spots. Set to 0 to disable opening.

  • threshold (float or None, default: None ) –

    Intensity threshold. If None (default), the triangle auto-threshold from skimage.filters.threshold_triangle is used.

Returns:
  • mask( ndarray of bool ) –

    Boolean segmentation mask, same spatial shape as the input.

Source code in src/nrxrdct/laue/segmentation.py
def segment_image(
    im_array: np.ndarray,
    kernel_size: int = 3,
    sigma: float = 0.1,
    iterations: int = 1,
    threshold: float = None,
):
    """
    Segment image into a boolean mask.

    Args:
        im_array (ndarray): 2-D intensity image, or 3-D stack reduced by max(axis=0).
        kernel_size (int): Side length of the square structuring element used for binary opening.
        sigma (float): Gaussian smoothing applied to the binary mask before returning.
            Set to 0 to skip. Note: smoothing is applied to the float representation
            of the mask and then thresholded at 0.5 so the output remains boolean.
        iterations (int): Number of binary-opening iterations. Each iteration with a 3×3 element
            erodes features by ~1 pixel per side; spots smaller than roughly
            `(2*iterations + 1)² ` pixels may be completely erased. Default 1
            (single pass) to preserve small spots. Set to 0 to disable opening.
        threshold (float or None): Intensity threshold. If None (default), the triangle auto-threshold
            from `skimage.filters.threshold_triangle` is used.

    Returns:
        mask (ndarray of bool): Boolean segmentation mask, same spatial shape as the input.
"""
    if im_array.ndim != 2:
        im_array = im_array.max(axis=0)

    if threshold is None:
        thrs = sk.filters.threshold_triangle(im_array)
    else:
        thrs = threshold

    mask = im_array >= thrs

    if iterations > 0:
        mask = ndi.binary_opening(
            mask,
            structure=np.ones((kernel_size, kernel_size)),
            iterations=iterations,
        )
    if sigma > 0:
        # gaussian_filter returns float; threshold back to bool so callers
        # that check dtype (e.g. label_segmented_image) receive the right type
        mask = ndi.gaussian_filter(mask.astype(np.float32), sigma=sigma) > 0.5
    return mask

simulation_guided_segmentation

simulation_guided_segmentation(image: ndarray, spots: list, mask: ndarray, outpath: str | None = None, *, psf_sigma: float = 1.0, search_radius: int = 7, min_distance: int = 1, min_snr: float = 1.0, bg_sigma: float = 60.0, d: int = 10, r_squared_min: float = 0.8, include_unfitted: bool = True, fit_spots: bool = False, overwrite: bool = False) -> np.ndarray

Simulation-guided peak search optimised for small and faint spots.

Unlike the blind segmentation methods (LoG, WTH, Hybrid), this function starts from a list of predicted spot positions obtained from :func:~nrxrdct.laue.simulate_laue_stack or :func:~nrxrdct.laue.simulate_laue_darwin and restricts the search to small imagettes around each prediction. This makes it insensitive to the global frame background and is effective for:

  • Faint or small spots that fall below the threshold of blind methods.
  • Dense patterns where blind thresholding merges neighbouring spots.
  • Frames with strong parasitic background (fluorescence streaks, beam stop shadows) that produce many false positives in a global search.

The output is fully compatible with the standard pipeline — :func:convert_spotsfile2peaklist, :func:plot_measured_vs_simulated, and :func:~nrxrdct.laue.fitting.fit_orientation_stack all accept it unchanged. At the :class:~nrxrdct.laue.LayeredMap scale the function is wrapped by :meth:~nrxrdct.laue.LayeredMap.submit_guided_segmentation for parallel SLURM execution.

Per-spot pipeline
  1. Extract a (2·search_radius) × (2·search_radius) imagette from the background-subtracted image centred on the predicted position.
  2. Apply a light Gaussian smoothing (sigma = psf_sigma) to suppress single-pixel noise before peak finding.
  3. Run :func:skimage.feature.peak_local_max with minimum peak separation min_distance to collect all local maxima candidates.
  4. For each candidate: compute SNR against a background annulus (outer radius 3×search_radius, inner exclusion search_radius) so that a bright neighbouring streak does not inflate the threshold for a faint spot sitting next to it. Reject if SNR < min_snr.
  5. Optionally fit a 2-D rotated Gaussian to the raw image ROI around each accepted candidate for sub-pixel position refinement.
  6. Write results to HDF5 in the same format as :func:write_h5_spotsfile, fully compatible with :func:convert_spotsfile2peaklist.

Note that multiple peaks can be found per predicted position — useful when the simulation predicts one reflection but the actual pattern contains a satellite or split spot nearby.

Parameters:
  • image (ndarray) –

    Raw detector frame (Nv, Nh) float32.

  • spots (list) –

    Predicted spot positions. Two forms are accepted:

    • List of dicts — direct output of :func:~nrxrdct.laue.simulate_laue_stack or :func:~nrxrdct.laue.simulate_laue_darwin. Each dict must have 'pix': (xcam, ycam); entries with pix=None (off-detector) are silently skipped.
    • numpy array (N, 2) — columns [xcam, ycam].
  • mask (ndarray) –

    Boolean valid-pixel mask (True = active pixel). Dead pixels and detector gaps must be excluded before peak finding.

  • outpath (str | None, default: None ) –

    Output HDF5 file path. If None (default), no file is written and only the peaklist is returned.

  • psf_sigma (float, default: 1.0 ) –

    Gaussian smoothing sigma (pixels) applied to the imagette before local-maxima finding. Set to roughly FWHM / 2.35 of a typical spot. 0 disables smoothing.

  • search_radius (int, default: 7 ) –

    Half-size (pixels) of the search imagette extracted around each predicted position. Should be at least as large as the expected position error between the prediction and the true peak.

  • min_distance (int, default: 1 ) –

    Minimum pixel separation between two accepted local maxima within the same imagette. Prevents the same intensity maximum from being reported as two separate spots.

  • min_snr (float, default: 1.0 ) –

    Minimum signal-to-noise ratio to accept a local maximum. SNR is computed as (peak − annulus_median) / annulus_MAD, where the annulus has inner radius search_radius and outer radius 3 × search_radius.

  • bg_sigma (float, default: 60.0 ) –

    If > 0, subtract a Gaussian background of this sigma (pixels) from the full image before imagette extraction. Gaussian fitting always uses the original image intensities.

  • d (int, default: 10 ) –

    Half-size of the Gaussian fit ROI in pixels.

  • r_squared_min (float, default: 0.8 ) –

    Minimum Gaussian fit R² to accept a fitted position. Spots whose fit does not converge or falls below this threshold are handled according to include_unfitted.

  • include_unfitted (bool, default: True ) –

    If True (default), store peaks that pass the SNR gate but whose Gaussian fit did not reach r_squared_min, using the local-maximum pixel as position.

  • fit_spots (bool, default: False ) –

    If False, skip Gaussian fitting entirely and write each accepted local maximum directly. Faster; sufficient for orientation indexing when shape parameters are not needed.

  • overwrite (bool, default: False ) –

    Overwrite an existing HDF5 output file.

Returns:
  • ndarray –

    (N, 9) float32 array with the same column layout as

  • ndarray –

    func:convert_spotsfile2peaklist:

  • ndarray –

    ``peak_X, peak_Y, peak_Isub, peak_fwaxmaj, peak_fwaxmin,

  • ndarray –

    peak_inclination, Xdev, Ydev, peak_bkg``.

  • ndarray –

    Directly compatible with :func:plot_measured_vs_simulated and

  • ndarray –

    func:~nrxrdct.laue.fitting.fit_orientation_stack.

  • ndarray –

    Returns an empty (0, 9) array when no peaks pass the SNR gate.

Source code in src/nrxrdct/laue/segmentation.py
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
def simulation_guided_segmentation(
    image: np.ndarray,
    spots: list,
    mask: np.ndarray,
    outpath: "str | None" = None,
    *,
    psf_sigma: float = 1.0,
    search_radius: int = 7,
    min_distance: int = 1,
    min_snr: float = 1.0,
    bg_sigma: float = 60.0,
    d: int = 10,
    r_squared_min: float = 0.8,
    include_unfitted: bool = True,
    fit_spots: bool = False,
    overwrite: bool = False,
) -> np.ndarray:
    """
    Simulation-guided peak search optimised for small and faint spots.

    Unlike the blind segmentation methods (LoG, WTH, Hybrid), this function
    starts from a list of **predicted spot positions** obtained from
    :func:`~nrxrdct.laue.simulate_laue_stack` or
    :func:`~nrxrdct.laue.simulate_laue_darwin` and restricts the search to
    small imagettes around each prediction.  This makes it insensitive to
    the global frame background and is effective for:

    * Faint or small spots that fall below the threshold of blind methods.
    * Dense patterns where blind thresholding merges neighbouring spots.
    * Frames with strong parasitic background (fluorescence streaks, beam
      stop shadows) that produce many false positives in a global search.

    The output is fully compatible with the standard pipeline —
    :func:`convert_spotsfile2peaklist`, :func:`plot_measured_vs_simulated`,
    and :func:`~nrxrdct.laue.fitting.fit_orientation_stack` all accept it
    unchanged.  At the :class:`~nrxrdct.laue.LayeredMap` scale the function
    is wrapped by
    :meth:`~nrxrdct.laue.LayeredMap.submit_guided_segmentation`
    for parallel SLURM execution.

    Per-spot pipeline
    -----------------
    1. Extract a ``(2·search_radius) × (2·search_radius)`` imagette from
       the background-subtracted image centred on the predicted position.
    2. Apply a light Gaussian smoothing (sigma = *psf_sigma*) to suppress
       single-pixel noise before peak finding.
    3. Run :func:`skimage.feature.peak_local_max` with minimum peak
       separation *min_distance* to collect all local maxima candidates.
    4. For each candidate: compute SNR against a background annulus
       (outer radius 3×*search_radius*, inner exclusion *search_radius*)
       so that a bright neighbouring streak does not inflate the threshold for
       a faint spot sitting next to it.  Reject if ``SNR < min_snr``.
    5. Optionally fit a 2-D rotated Gaussian to the raw image ROI around
       each accepted candidate for sub-pixel position refinement.
    6. Write results to HDF5 in the same format as :func:`write_h5_spotsfile`,
       fully compatible with :func:`convert_spotsfile2peaklist`.

    Note that **multiple peaks can be found per predicted position** — useful
    when the simulation predicts one reflection but the actual pattern contains
    a satellite or split spot nearby.

    Args:
        image: Raw detector frame ``(Nv, Nh) float32``.
        spots: Predicted spot positions.  Two forms are accepted:

            * **List of dicts** — direct output of
              :func:`~nrxrdct.laue.simulate_laue_stack` or
              :func:`~nrxrdct.laue.simulate_laue_darwin`.  Each dict must
              have ``'pix': (xcam, ycam)``; entries with ``pix=None``
              (off-detector) are silently skipped.
            * **numpy array** ``(N, 2)`` — columns ``[xcam, ycam]``.
        mask: Boolean valid-pixel mask (``True`` = active pixel).  Dead
            pixels and detector gaps must be excluded before peak finding.
        outpath: Output HDF5 file path.  If ``None`` (default), no file is
            written and only the peaklist is returned.
        psf_sigma: Gaussian smoothing sigma (pixels) applied to the
            imagette before local-maxima finding.  Set to roughly
            ``FWHM / 2.35`` of a typical spot.  ``0`` disables smoothing.
        search_radius: Half-size (pixels) of the search imagette extracted
            around each predicted position.  Should be at least as large
            as the expected position error between the prediction and the
            true peak.
        min_distance: Minimum pixel separation between two accepted local
            maxima within the same imagette.  Prevents the same intensity
            maximum from being reported as two separate spots.
        min_snr: Minimum signal-to-noise ratio to accept a local maximum.
            SNR is computed as ``(peak − annulus_median) / annulus_MAD``,
            where the annulus has inner radius *search_radius* and outer
            radius ``3 × search_radius``.
        bg_sigma: If > 0, subtract a Gaussian background of this sigma
            (pixels) from the full image before imagette extraction.
            Gaussian fitting always uses the original *image* intensities.
        d: Half-size of the Gaussian fit ROI in pixels.
        r_squared_min: Minimum Gaussian fit R² to accept a fitted position.
            Spots whose fit does not converge or falls below this threshold
            are handled according to *include_unfitted*.
        include_unfitted: If ``True`` (default), store peaks that pass the
            SNR gate but whose Gaussian fit did not reach *r_squared_min*,
            using the local-maximum pixel as position.
        fit_spots: If ``False``, skip Gaussian fitting entirely and write
            each accepted local maximum directly.  Faster; sufficient for
            orientation indexing when shape parameters are not needed.
        overwrite: Overwrite an existing HDF5 output file.

    Returns:
        ``(N, 9)`` float32 array with the same column layout as
        :func:`convert_spotsfile2peaklist`:
        ``peak_X, peak_Y, peak_Isub, peak_fwaxmaj, peak_fwaxmin,
        peak_inclination, Xdev, Ydev, peak_bkg``.
        Directly compatible with :func:`plot_measured_vs_simulated` and
        :func:`~nrxrdct.laue.fitting.fit_orientation_stack`.
        Returns an empty ``(0, 9)`` array when no peaks pass the SNR gate.
    """
    from skimage.feature import peak_local_max

    if outpath is not None:
        if os.path.exists(outpath):
            if not overwrite:
                raise FileExistsError(
                    f"Output file exists: {outpath!r}. Pass overwrite=True to replace it."
                )
            os.remove(outpath)

    image = np.asarray(image, dtype=np.float32)
    nv, nh = image.shape
    valid = np.asarray(mask, dtype=bool)

    # Normalise spots input:
    #   • numpy (N, 2) array            → each row is [xcam, ycam]
    #   • simulate_laue / simulate_laue_stack output (list of dicts with 'pix')
    #     → passed through unchanged; dicts that have pix=None are already skipped below
    if isinstance(spots, np.ndarray):
        _arr = np.asarray(spots, dtype=np.float32)
        spots = [{"pix": (float(r[0]), float(r[1]))} for r in _arr]

    # Background subtraction — used for detection only; Gaussian fit uses raw image
    if bg_sigma > 0:
        bg = gaussian_background(image, valid, sigma=bg_sigma)
        det_img = (image - bg).astype(np.float32)
    else:
        det_img = image.copy().astype(np.float32)
    det_img[~valid] = 0.0

    n_written = 0
    n_success = 0
    found_peaks: list = []   # collected (xcam, ycam) for every accepted peak

    def _write_spot(hout, y_pk, x_pk, xcam_pred, ycam_pred,
                    r2, popt, n_comp, fit_roi, ymin, xmin, det_img):
        """Record one accepted peak: append to found_peaks and optionally write HDF5."""
        nonlocal n_written, n_success
        Ipix = int(image[y_pk, x_pk])

        if not fit_spots:
            found_peaks.append([
                float(x_pk), float(y_pk),
                float(det_img[y_pk, x_pk]),   # Isub
                0.0, 0.0, 0.0,                 # fwaxmaj, fwaxmin, inclination
                float(x_pk) - xcam_pred,       # Xdev
                float(y_pk) - ycam_pred,       # Ydev
                0.0,                           # peak_bkg
            ])
            if hout is not None:
                key = f"spot_{n_written:04d}_0"
                hout[f"{key}/r_squared"]       = np.float32(-1)
                hout[f"{key}/image"]            = fit_roi
                hout[f"{key}/yxcen"]            = np.array([float(y_pk), float(x_pk)])
                hout[f"{key}/bbox"]             = np.array([ymin, xmin,
                                                            ymin + fit_roi.shape[0],
                                                            xmin + fit_roi.shape[1]])
                hout[f"{key}/peak_X"]           = round(float(x_pk), 2)
                hout[f"{key}/peak_Y"]           = round(float(y_pk), 2)
                hout[f"{key}/peak_Itot"]        = round(float(image[y_pk, x_pk]), 2)
                hout[f"{key}/peak_Isub"]        = round(float(det_img[y_pk, x_pk]), 2)
                hout[f"{key}/peak_fwaxmaj"]     = 0.0
                hout[f"{key}/peak_fwaxmin"]     = 0.0
                hout[f"{key}/peak_inclination"] = 0.0
                hout[f"{key}/Xdev"]             = round(float(x_pk) - xcam_pred, 2)
                hout[f"{key}/Ydev"]             = round(float(y_pk) - ycam_pred, 2)
                hout[f"{key}/peak_bkg"]         = 0.0
                hout[f"{key}/Ipixmax"]          = Ipix
            n_written += 1
            n_success += 1
            return

        if popt is None or r2 < r_squared_min:
            if not include_unfitted:
                return
            # Fallback: use local-maximum position
            try:
                ip1 = auto_init_gaussian_mixture_global(fit_roi, n_components=1,
                                                        smooth_sigma=0.5)
                A, xm, ym, sx, sy, th = ip1[0:6]
                C0 = float(ip1[-1])
            except Exception:
                xm = float(x_pk - xmin)
                ym = float(y_pk - ymin)
                sx, sy, th, C0 = 2.0, 2.0, 0.0, 0.0
            found_peaks.append([
                float(xm + xmin), float(ym + ymin),
                float(det_img[y_pk, x_pk]),
                fwhm_from_sigma(max(sx, sy)), fwhm_from_sigma(min(sx, sy)),
                float(np.rad2deg(th)),
                float(xm + xmin) - xcam_pred,
                float(ym + ymin) - ycam_pred,
                C0,
            ])
            if hout is not None:
                key = f"spot_{n_written:04d}_0"
                hout[f"{key}/r_squared"]       = np.float32(r2)
                hout[f"{key}/image"]            = fit_roi
                hout[f"{key}/yxcen"]            = np.array([float(y_pk), float(x_pk)])
                hout[f"{key}/bbox"]             = np.array([ymin, xmin,
                                                            ymin + fit_roi.shape[0],
                                                            xmin + fit_roi.shape[1]])
                hout[f"{key}/peak_X"]           = round(float(xm + xmin), 2)
                hout[f"{key}/peak_Y"]           = round(float(ym + ymin), 2)
                hout[f"{key}/peak_Itot"]        = 65535
                hout[f"{key}/peak_Isub"]        = 65535
                hout[f"{key}/peak_fwaxmaj"]     = round(fwhm_from_sigma(max(sx, sy)), 2)
                hout[f"{key}/peak_fwaxmin"]     = round(fwhm_from_sigma(min(sx, sy)), 2)
                hout[f"{key}/peak_inclination"] = round(float(np.rad2deg(th)), 2)
                hout[f"{key}/Xdev"]             = round(float(xm + xmin) - xcam_pred, 2)
                hout[f"{key}/Ydev"]             = round(float(ym + ymin) - ycam_pred, 2)
                hout[f"{key}/peak_bkg"]         = round(C0, 2)
                hout[f"{key}/Ipixmax"]          = Ipix
            n_written += 1
            return

        # Successful fit — use first component position for the peaklist
        n_success += 1
        C = float(popt[-1])
        A0, xm0, ym0, sx0, sy0, th0 = popt[0:6]
        found_peaks.append([
            float(xm0 + xmin), float(ym0 + ymin),
            float(A0 - C),
            fwhm_from_sigma(max(sx0, sy0)), fwhm_from_sigma(min(sx0, sy0)),
            float(np.rad2deg(th0)),
            float(xm0 + xmin) - xcam_pred,
            float(ym0 + ymin) - ycam_pred,
            C,
        ])
        if hout is not None:
            for jj in range(1, n_comp + 1):
                A, xm, ym, sx, sy, th = popt[6 * (jj - 1):6 * jj]
                key = f"spot_{n_written:04d}_{jj}"
                hout[f"{key}/r_squared"]       = np.float32(r2)
                hout[f"{key}/image"]            = fit_roi
                hout[f"{key}/yxcen"]            = np.array([float(y_pk), float(x_pk)])
                hout[f"{key}/bbox"]             = np.array([ymin, xmin,
                                                            ymin + fit_roi.shape[0],
                                                            xmin + fit_roi.shape[1]])
                hout[f"{key}/peak_X"]           = round(float(xm + xmin), 2)
                hout[f"{key}/peak_Y"]           = round(float(ym + ymin), 2)
                hout[f"{key}/peak_Itot"]        = round(float(A), 2)
                hout[f"{key}/peak_Isub"]        = round(float(A - C), 2)
                hout[f"{key}/peak_fwaxmaj"]     = round(fwhm_from_sigma(max(sx, sy)), 2)
                hout[f"{key}/peak_fwaxmin"]     = round(fwhm_from_sigma(min(sx, sy)), 2)
                hout[f"{key}/peak_inclination"] = round(float(np.rad2deg(th)), 2)
                hout[f"{key}/Xdev"]             = round(float(xm + xmin) - xcam_pred, 2)
                hout[f"{key}/Ydev"]             = round(float(ym + ymin) - ycam_pred, 2)
                hout[f"{key}/peak_bkg"]         = round(float(C), 2)
                hout[f"{key}/Ipixmax"]          = Ipix
        n_written += 1

    def _run(hout):
        for spot in spots:
            pix = spot.get("pix")
            if pix is None:
                continue

            xcam_pred = float(pix[0])
            ycam_pred = float(pix[1])

            # ── Imagette extraction ───────────────────────────────────────────
            r0 = int(max(0,  round(ycam_pred) - search_radius))
            r1 = int(min(nv, round(ycam_pred) + search_radius + 1))
            c0 = int(max(0,  round(xcam_pred) - search_radius))
            c1 = int(min(nh, round(xcam_pred) + search_radius + 1))
            if r1 <= r0 or c1 <= c0:
                continue

            imagette_valid = valid[r0:r1, c0:c1]
            if not imagette_valid.any():
                continue
            imagette = det_img[r0:r1, c0:c1].copy()
            imagette[~imagette_valid] = 0.0

            # Light smoothing for robust local-max finding
            smoothed = (ndi.gaussian_filter(imagette, sigma=psf_sigma)
                        if psf_sigma > 0 else imagette)

            # ── Local background (annulus outside the search window) ──────────
            bg_r0 = int(max(0,  round(ycam_pred) - 3 * search_radius))
            bg_r1 = int(min(nv, round(ycam_pred) + 3 * search_radius + 1))
            bg_c0 = int(max(0,  round(xcam_pred) - 3 * search_radius))
            bg_c1 = int(min(nh, round(xcam_pred) + 3 * search_radius + 1))
            rr = (np.arange(bg_r0, bg_r1)[:, None] - round(ycam_pred)) ** 2
            cc = (np.arange(bg_c0, bg_c1)[None, :] - round(xcam_pred)) ** 2
            annulus_mask = (rr + cc) > search_radius ** 2
            bg_vals = det_img[bg_r0:bg_r1, bg_c0:bg_c1][
                annulus_mask & valid[bg_r0:bg_r1, bg_c0:bg_c1]
            ]
            if bg_vals.size >= 10:
                local_med   = float(np.median(bg_vals))
                local_noise = max(float(np.median(np.abs(bg_vals - local_med))) / 0.6745,
                                  1e-12)
            else:
                local_med   = 0.0
                local_noise = max(float(smoothed.std()), 1e-12)

            # ── Find all local maxima in the smoothed imagette ────────────────
            candidates = peak_local_max(
                smoothed,
                min_distance=min_distance,
                threshold_abs=local_med,   # pre-filter: must be above background
            )
            # candidates is (N, 2) array of (row, col) in imagette coordinates

            for local_r, local_c in candidates:
                y_pk = r0 + local_r
                x_pk = c0 + local_c
                if not valid[y_pk, x_pk]:
                    continue

                peak_val = float(smoothed[local_r, local_c])
                snr = (peak_val - local_med) / local_noise
                if snr < min_snr:
                    continue

                # Gaussian fit ROI on raw image intensities
                ymin, ymax, xmin, xmax = get_spot_limits(image, y_pk, x_pk, d)
                fit_roi = image[ymin:ymax, xmin:xmax].copy()

                if not fit_spots:
                    _write_spot(hout, y_pk, x_pk, xcam_pred, ycam_pred,
                                -1, None, 1, fit_roi, ymin, xmin, det_img)
                    continue

                r2, popt, n_comp = 0.0, None, 1
                try:
                    best_r2, best_popt, best_n = -np.inf, None, 1
                    for nc in range(1, 2):
                        try:
                            ip = auto_init_gaussian_mixture_global(
                                fit_roi, n_components=nc, smooth_sigma=0.5
                            )
                            popt_, _, fitted, _, _ = fit_gaussian_mixture_2d(
                                fit_roi, n_components=nc, init_params=ip
                            )
                            r2_ = r_squared_image(fit_roi, fitted)
                        except (ValueError, RuntimeError):
                            break
                        if r2_ > best_r2:
                            best_r2, best_popt, best_n = r2_, popt_, nc
                        if r2_ >= r_squared_min:
                            break
                    r2, popt, n_comp = best_r2, best_popt, best_n
                except Exception:
                    pass

                _write_spot(hout, y_pk, x_pk, xcam_pred, ycam_pred,
                            r2, popt, n_comp, fit_roi, ymin, xmin, det_img)

        if hout is not None:
            hout.attrs["n_spots"]   = n_written
            hout.attrs["n_success"] = n_success

    # Run with or without HDF5 output
    if outpath is not None:
        with h5py.File(outpath, "a") as hout:
            _run(hout)
    else:
        _run(None)

    print(
        f"simulation_guided_segmentation: {n_success}/{n_written} peaks accepted "
        f"(search_radius={search_radius}, min_distance={min_distance}, "
        f"min_snr={min_snr:.1f})"
    )
    return (np.array(found_peaks, dtype=np.float32)
            if found_peaks else np.empty((0, 9), dtype=np.float32))

write_h5_spotsfile

write_h5_spotsfile(image_array: ndarray, regionprops, outpath: str = 'segmented_spotsfile.h5', d: int = 10, overwrite: bool = False, max_components: int = 2, include_unfitted: bool = True, r_squared_min: float = 0.9, fit_spots: bool = True)

Writes per-spot images and fitted parameters into an HDF5 file.

Tries to fit a Gaussian mixture on a cropped ROI of size 2d around the region weighted centroid. Spots whose fit reaches r² ≥ r_squared_min are stored in spot_{ii}_{jj} groups (jj = 1, 2, …).

Parameters:
  • image_array ((Nv, Nh) ndarray) –

    Full detector image from which ROIs are extracted.

  • regionprops (list) –

    Region properties from :func:measure_peaks.

  • outpath (str, default: 'segmented_spotsfile.h5' ) –

    Output HDF5 file path.

  • d (int, default: 10 ) –

    Half-size of the ROI crop around each centroid (pixels).

  • overwrite (bool, default: False ) –

    If True, delete an existing file at outpath before writing.

  • max_components (int, default: 2 ) –

    Maximum number of Gaussian components tried per spot.

  • include_unfitted (bool, default: True ) –

    If True (default), spots whose best fit has r² < r_squared_min are still written to the file in a spot_{ii}_0 group (fallback position from the weighted centroid, shape fields set to 0). If False, those spots are silently skipped. Ignored when fit_spots is False.

  • r_squared_min (float, default: 0.9 ) –

    Minimum r² to consider a Gaussian fit acceptable (default 0.9). Ignored when fit_spots is False.

  • fit_spots (bool, default: True ) –

    If True (default), attempt a 2-D Gaussian mixture fit for each spot ROI. If False, skip fitting entirely and write each spot using the weighted centroid from regionprops directly; shape fields are set to 0 and r_squared is stored as -1 to indicate that no fit was attempted. This is much faster and suitable when peak positions are all that is needed.

Source code in src/nrxrdct/laue/segmentation.py
def write_h5_spotsfile(
    image_array: np.ndarray,
    regionprops,
    outpath: str = "segmented_spotsfile.h5",
    d: int = 10,
    overwrite: bool = False,
    max_components: int = 2,
    include_unfitted: bool = True,
    r_squared_min: float = 0.9,
    fit_spots: bool = True,
):
    """
    Writes per-spot images and fitted parameters into an HDF5 file.

    Tries to fit a Gaussian mixture on a cropped ROI of size 2d around the
    region weighted centroid.  Spots whose fit reaches r² ≥ r_squared_min are
    stored in `spot_{ii}_{jj}` groups (jj = 1, 2, …).

    Args:
        image_array ((Nv, Nh) ndarray): Full detector image from which ROIs are extracted.
        regionprops (list): Region properties from :func:`measure_peaks`.
        outpath (str): Output HDF5 file path.
        d (int): Half-size of the ROI crop around each centroid (pixels).
        overwrite (bool): If True, delete an existing file at *outpath* before writing.
        max_components (int): Maximum number of Gaussian components tried per spot.
        include_unfitted (bool): If True (default), spots whose best fit has r² < r_squared_min are
            still written to the file in a `spot_{ii}_0` group (fallback
            position from the weighted centroid, shape fields set to 0).
            If False, those spots are silently skipped.  Ignored when
            *fit_spots* is `False`.
        r_squared_min (float): Minimum r² to consider a Gaussian fit acceptable (default 0.9).
            Ignored when *fit_spots* is `False`.
        fit_spots (bool): If `True` (default), attempt a 2-D Gaussian mixture fit for each
            spot ROI.  If `False`, skip fitting entirely and write each spot
            using the weighted centroid from *regionprops* directly; shape
            fields are set to 0 and `r_squared` is stored as `-1` to
            indicate that no fit was attempted.  This is much faster and
            suitable when peak positions are all that is needed.
"""
    if fit_spots and (not isinstance(max_components, int) or isinstance(max_components, bool) or max_components < 1):
        raise ValueError(
            f"max_components must be a positive int, got {max_components!r}. "
            "Use max_components=1 for a single-Gaussian-only fit, or "
            "fit_spots=False to skip fitting entirely."
        )

    n_labels = len(regionprops)
    n_success = 0

    if os.path.exists(outpath):
        if not overwrite:
            raise FileExistsError(
                f"Output file already exists: {outpath!r}. "
                "Pass overwrite=True to replace it."
            )
        os.remove(outpath)

    with h5py.File(outpath, "a") as hout:
        for ii, region in enumerate(regionprops):
            ycen, xcen = region.centroid_weighted

            ymin, ymax, xmin, xmax = get_spot_limits(image_array, ycen, xcen, d)

            image = image_array[
                ymin:ymax,
                xmin:xmax,
            ]

            # ── no-fit bypass ─────────────────────────────────────────────────
            if not fit_spots:
                Ipix = int(region.image_intensity.max())
                hout[f"spot_{ii:04d}_0/r_squared"]       = -1
                hout[f"spot_{ii:04d}_0/image"]            = image
                hout[f"spot_{ii:04d}_0/yxcen"]            = region.centroid_weighted
                hout[f"spot_{ii:04d}_0/bbox"]             = region.bbox
                hout[f"spot_{ii:04d}_0/peak_X"]           = round(float(xcen), 2)
                hout[f"spot_{ii:04d}_0/peak_Y"]           = round(float(ycen), 2)
                hout[f"spot_{ii:04d}_0/peak_Itot"]        = 65535
                hout[f"spot_{ii:04d}_0/peak_Isub"]        = 65535
                hout[f"spot_{ii:04d}_0/peak_fwaxmaj"]     = 0.0
                hout[f"spot_{ii:04d}_0/peak_fwaxmin"]     = 0.0
                hout[f"spot_{ii:04d}_0/peak_inclination"] = 0.0
                hout[f"spot_{ii:04d}_0/Xdev"]             = 0.0
                hout[f"spot_{ii:04d}_0/Ydev"]             = 0.0
                hout[f"spot_{ii:04d}_0/peak_bkg"]         = 0.0
                hout[f"spot_{ii:04d}_0/Ipixmax"]          = Ipix
                n_success += 1
                continue

            init_params_1 = None
            try:
                # Single-component initial guess — used as position fallback
                # when the Gaussian fit does not meet r_squared_min.
                init_params_1 = auto_init_gaussian_mixture_global(
                    image, n_components=1, smooth_sigma=0.2
                )

                for n_comp in range(1, max_components + 1):
                    try:
                        init_params = auto_init_gaussian_mixture_global(
                            image, n_components=n_comp, smooth_sigma=0.2
                        )
                        popt, pcov, fitted, X, Y = fit_gaussian_mixture_2d(
                            image, n_components=n_comp, init_params=init_params
                        )
                        r2 = r_squared_image(image, fitted)

                        C = popt[-1]
                    except ValueError:
                        n_comp -= 1
                        init_params = auto_init_gaussian_mixture_global(
                            image, n_components=n_comp, smooth_sigma=0.2
                        )
                        popt, pcov, fitted, X, Y = fit_gaussian_mixture_2d(
                            image, n_components=n_comp, init_params=init_params
                        )
                        r2 = r_squared_image(image, fitted)
                        C = popt[-1]
                        break
                    if r2 > r_squared_min:
                        break


                if r2 < r_squared_min:
                    if not include_unfitted:
                        continue
                    # Fit did not reach r_squared_min — write the initial-guess
                    # parameters (position from local maximum, shape from
                    # weighted covariance) rather than a poor converged fit.
                    A, xm, ym, sigma_x, sigma_y, theta = init_params_1[0:6]
                    C0 = init_params_1[-1]
                    hout[f"spot_{ii:04d}_0/r_squared"]       = r2
                    hout[f"spot_{ii:04d}_0/image"]            = image
                    hout[f"spot_{ii:04d}_0/yxcen"]            = region.centroid_weighted
                    hout[f"spot_{ii:04d}_0/bbox"]             = region.bbox
                    hout[f"spot_{ii:04d}_0/peak_X"]           = round(xm + (int(xcen) - d), 2)
                    hout[f"spot_{ii:04d}_0/peak_Y"]           = round(ym + (int(ycen) - d), 2)
                    hout[f"spot_{ii:04d}_0/peak_Itot"]        = 65535
                    hout[f"spot_{ii:04d}_0/peak_Isub"]        = 65535
                    hout[f"spot_{ii:04d}_0/peak_fwaxmaj"]     = round(fwhm_from_sigma(max(sigma_x, sigma_y)), 2)
                    hout[f"spot_{ii:04d}_0/peak_fwaxmin"]     = round(fwhm_from_sigma(min(sigma_x, sigma_y)), 2)
                    hout[f"spot_{ii:04d}_0/peak_inclination"] = round(np.rad2deg(theta), 2)
                    hout[f"spot_{ii:04d}_0/Xdev"]             = round(d - xm, 2)
                    hout[f"spot_{ii:04d}_0/Ydev"]             = round(d - ym, 2)
                    hout[f"spot_{ii:04d}_0/peak_bkg"]         = round(C0, 2)
                    hout[f"spot_{ii:04d}_0/Ipixmax"]          = int(region.image_intensity.max())
                    continue
                n_success += 1

                for jj in range(1, n_comp + 1):
                    A, xm, ym, sigma_x, sigma_y, theta = popt[
                        6 * (jj - 1) : 6 * (jj - 1) + 6
                    ]
                    hout[f"spot_{ii:04d}_{jj}/r_squared"] = r2
                    hout[f"spot_{ii:04d}_{jj}/image"] = image
                    hout[f"spot_{ii:04d}_{jj}/yxcen"] = region.centroid_weighted
                    hout[f"spot_{ii:04d}_{jj}/bbox"] = region.bbox

                    hout[f"spot_{ii:04d}_{jj}/peak_X"] = round(xm + (int(xcen) - d), 2)
                    hout[f"spot_{ii:04d}_{jj}/peak_Y"] = round(ym + (int(ycen) - d), 2)

                    hout[f"spot_{ii:04d}_{jj}/peak_Itot"] = round(A, 2)
                    hout[f"spot_{ii:04d}_{jj}/peak_Isub"] = round(A - C, 2)

                    hout[f"spot_{ii:04d}_{jj}/peak_fwaxmaj"] = round(
                        fwhm_from_sigma(max(sigma_x, sigma_y)), 2
                    )
                    hout[f"spot_{ii:04d}_{jj}/peak_fwaxmin"] = round(
                        fwhm_from_sigma(min(sigma_x, sigma_y)), 2
                    )

                    hout[f"spot_{ii:04d}_{jj}/peak_inclination"] = round(
                        np.rad2deg(theta), 2
                    )

                    hout[f"spot_{ii:04d}_{jj}/Xdev"] = round(
                        ((xcen - (xcen - d)) - xm), 2
                    )
                    hout[f"spot_{ii:04d}_{jj}/Ydev"] = round(
                        ((ycen - (ycen - d)) - ym), 2
                    )

                    hout[f"spot_{ii:04d}_{jj}/peak_bkg"] = round(C, 2)
                    hout[f"spot_{ii:04d}_{jj}/Ipixmax"] = int(
                        region.image_intensity.max()
                    )

            except RuntimeError as exc:
                if not include_unfitted:
                    continue
                r2 = 0
                print(f"Runtime error at spot {ii}: {exc}")
                Ipix = int(region.image_intensity.max())
                hout[f"spot_{ii:04d}_0/r_squared"] = r2
                hout[f"spot_{ii:04d}_0/image"]     = image
                hout[f"spot_{ii:04d}_0/yxcen"]     = region.centroid_weighted
                hout[f"spot_{ii:04d}_0/bbox"]       = region.bbox
                if init_params_1 is not None:
                    A, xm, ym, sigma_x, sigma_y, theta = init_params_1[0:6]
                    C0 = init_params_1[-1]
                    hout[f"spot_{ii:04d}_0/peak_X"]           = round(xm + (int(xcen) - d), 2)
                    hout[f"spot_{ii:04d}_0/peak_Y"]           = round(ym + (int(ycen) - d), 2)
                    hout[f"spot_{ii:04d}_0/peak_Itot"]        = 65535
                    hout[f"spot_{ii:04d}_0/peak_Isub"]        = 65535
                    hout[f"spot_{ii:04d}_0/peak_fwaxmaj"]     = round(fwhm_from_sigma(max(sigma_x, sigma_y)), 2)
                    hout[f"spot_{ii:04d}_0/peak_fwaxmin"]     = round(fwhm_from_sigma(min(sigma_x, sigma_y)), 2)
                    hout[f"spot_{ii:04d}_0/peak_inclination"] = round(np.rad2deg(theta), 2)
                    hout[f"spot_{ii:04d}_0/Xdev"]             = round(d - xm, 2)
                    hout[f"spot_{ii:04d}_0/Ydev"]             = round(d - ym, 2)
                    hout[f"spot_{ii:04d}_0/peak_bkg"]         = round(C0, 2)
                else:
                    # init_params_1 itself failed — last resort: centroid only
                    hout[f"spot_{ii:04d}_0/peak_X"]           = round(float(xcen), 2)
                    hout[f"spot_{ii:04d}_0/peak_Y"]           = round(float(ycen), 2)
                    hout[f"spot_{ii:04d}_0/peak_Itot"]        = 65535
                    hout[f"spot_{ii:04d}_0/peak_Isub"]        = 65535
                    hout[f"spot_{ii:04d}_0/peak_fwaxmaj"]     = 0.0
                    hout[f"spot_{ii:04d}_0/peak_fwaxmin"]     = 0.0
                    hout[f"spot_{ii:04d}_0/peak_inclination"] = 0.0
                    hout[f"spot_{ii:04d}_0/Xdev"]             = 0.0
                    hout[f"spot_{ii:04d}_0/Ydev"]             = 0.0
                    hout[f"spot_{ii:04d}_0/peak_bkg"]         = 0.0
                hout[f"spot_{ii:04d}_0/Ipixmax"] = Ipix
                continue

        hout.attrs["n_spots"] = n_labels
        hout.attrs["n_success"] = n_success

    if fit_spots:
        print(
            f"I successfully segmented {n_success} out of {n_labels} spots. "
            f"Rate of success: {n_success / n_labels:.3f}"
        )
    else:
        print(f"Saved {n_labels} spots (centroid only, no Gaussian fit).")

write_peaklist_dat

write_peaklist_dat(peaklist, outname)

Write an (N, 9) peaklist array to a space-separated DAT file.

The column order matches :func:convert_spotsfile2peaklist: peak_X peak_Y peak_I peak_fwaxmaj peak_fwaxmin peak_inclination Xdev Ydev peak_bkg. A .dat extension is appended automatically if absent.

Source code in src/nrxrdct/laue/segmentation.py
def write_peaklist_dat(peaklist, outname):
    """Write an (N, 9) peaklist array to a space-separated DAT file.

    The column order matches :func:`convert_spotsfile2peaklist`:
    ``peak_X  peak_Y  peak_I  peak_fwaxmaj  peak_fwaxmin
      peak_inclination  Xdev  Ydev  peak_bkg``.
    A ``.dat`` extension is appended automatically if absent.
"""
    if not outname.endswith(".dat"):
        outname = f"{outname}.dat"
    df = pd.DataFrame(
        data=peaklist,
        columns=[
            "peak_X",
            "peak_Y",
            "peak_I",
            "peak_fwaxmaj",
            "peak_fwaxmin",
            "peak_inclination",
            "Xdev",
            "Ydev",
            "peak_bkg",
        ],
    )

    df.to_csv(outname, sep=" ", index=False)