← Back to Pull requests

regionprops: fix bugs in `cucim.skimage.measure.regionprops_table` #1196

Merged
grlee77 merged 13 files (1686 lines) on Nov 24, 2026 03:29 UTC
View on GitHub
grlee77 grlee77 commented on Oct 31, 2026 13:31 UTC
Author

Summary

This PR fixes bugs in cuCIM's batch region properties
(regionprops_table(..., batch_processing=True), which calls
regionprops_dict). This includes wrong coordinates and pixel counts on label
images of 2³² or more pixels. It also fixes two closely related bugs: one in
the per-label path (batch_processing=False) and one in cuCIM's vendored
binary_fill_holes. The bugs were found while writing a technical explainer
of the batch implementation and while optimizing it.

Each bug has its own commit with its own tests, so the commits can be reviewed
one at a time (22 commits, listed at the end). The branch is based on main
(a0e27d1e) and does not depend on the intensity_median PR.

Is the bug also in scikit-image?

None of the bugs fixed here is present in scikit-image 0.26. Every fix
either makes cuCIM return what scikit-image returns, or fixes a cuCIM-only
property, parameter, option or vendored function that has no scikit-image
counterpart. In every case where a scikit-image counterpart exists, the fixed
cuCIM result now matches it, apart from the rounding of intensity_std (see
"Not addressed here").

The one bug with an upstream history is the sign of orientation for ±45°
regions. scikit-image fixed it in 0.21 (scikit-image PR #6836, "Sign error fix
in measure.regionprops for orientations of 45 degrees"), but both cuCIM paths
still had the old sign.

Fixes that restore agreement with scikit-image

Examples are from the commit messages and tests; "spacing (2, 2)" values are
for a test image with two ellipses.

| Commit | Properties | cuCIM path | Before → after (= scikit-image) |
|---|---|---|---|
| 1 | orientation | batch and per-label | cp.eye(10): −π/4 → π/4 |
| 2 | eccentricity | batch | single-pixel region: NaN → 0 |
| 3 | intensity_std | batch | constant float32 region of 0.1 or 1000.3: NaN → 0 |
| 6 | centroid, centroid_weighted | batch | spacing (2, 2): centroid-0 28 → 40 |
| 7 | centroid_weighted | per-label | region starting at row 3, spacing 2: 7.95 → 10.95 |
| 8 | area_bbox, extent | batch | spacing (2, 2): area_bbox 493 → 1972 |
| 9 | moments_normalized, moments_weighted_normalized | batch | spacing (2, 2): moments_normalized-2-0 0.179 → 0.045 |
| 9 | moments_hu, moments_weighted_hu | batch | non-unit spacing: values → NotImplementedError |
| 10 | area_convex, solidity | batch | spacing (2, 2): area_convex 373 → 1492 |
| 11 | perimeter, perimeter_crofton | batch | spacing (2, 2): 73.9 → 147.9; anisotropic spacing: values → NotImplementedError |
| 14 | area_filled | batch | filled pixel count → filled area (× pixel area) |
| 16 | area_filled, image_filled | batch | labels not in raster order: [36, 4, 36] → [36, 36, 4]; touching regions: [128, 0] → [64, 64] |
| 18 | bbox, centroid, centroid_local, moments and properties derived from them | batch | (65537, 65536) image, region on the last row: bbox rows [0, 1) → [65536, 65537) |
| 22 | intensity_min, intensity_max | batch | float64 image of uniform values in [0.1, 1): off by up to 1.7e-9 (minimum) and 2e-8 (maximum), rounded to float32 → the exact pixel values |

Notes:

  • Spacing (commits 6–11, 14). regionprops_dict did not pass spacing

  • to these functions (or, for the perimeters, did not scale the result),
    although scikit-image applies it. The NotImplementedErrors are the ones
    scikit-image and cuCIM's per-label path already raise.
  • Per-label centroid_weighted (commit 7). This is the only spacing bug

  • that was also in cuCIM's per-label path. RegionProperties.centroid_weighted
    added the bounding-box start without multiplying it by the spacing;
    scikit-image uses slc.start spc.
  • intensity_std (commit 3). The one-pass variance

  • (sumsq − mean²·count) / count can round to a small negative number for a
    constant region, and sqrt then returns NaN. It is now clipped at 0, using a
    comparison rather than CUDA's max (which is fmax). That way, regions that
    contain NaN or ±inf still return NaN, as numpy.std does.
  • Images of 2³² or more pixels (commit 18). See "Images of 2³² or more

  • pixels" below.
  • float64 minima and maxima (commit 22). The batch kernel combines the

  • threads' partial minima and maxima with atomicMin and atomicMax. For
    double, these are CuPy's overloads (cupy/_core/include/cupy/atomics.cuh),
    whose compare-and-swap loops compare with fminf and fmaxf, the
    single-precision functions, so every stored value was rounded to float32
    and could even lie outside the region's range. CuPy's development version
    (October 2026) still has them. CUDA has no native atomic minimum or maximum
    for double, so the shared kernel preamble now defines
    cucim_atomic_min and cucim_atomic_max: CUDA's atomicMin and
    atomicMax for every other type, and for double a compare-and-swap loop
    that compares in double precision. The fix in CuPy itself would be to use
    fmin and fmax there.
  • Filled properties (commit 16). scikit-image fills each region's holes on

  • its own crop. The batch path filled the union of all labels and relabeled it
    with measure.label, so values came back in the wrong order and touching
    regions were merged. See "Filled-region properties" below.

    Fixes without a scikit-image counterpart

    | Commit | What | Before → after |
    |---|---|---|
    | 4 | pixels_per_thread kernel parameter (batch only) | 128–255 overflowed the int8_t per-thread counters: num_pixels of a 64 × 64 region was 4294963200 (128) or 0 (255) → 4096 |
    | 5 | axis_lengths (cuCIM-only property) | properties=["axis_lengths"] alone: KeyError → works |
    | 12 | copy_output_to_host=True (cuCIM-only option) with batch_processing=False | TypeError for centroid_weighted with more than one region → works |
    | 13 | docstrings of regionprops_perimeter, regionprops_perimeter_crofton (batch module) | said perimeter skips the boundary along the image edge; both perimeters count it |
    | 15, 17 | vendored ndimage.binary_fill_holes | structure was ignored with the default origin and axes → it is used |
    | 16 | label_filled, num_pixels_filled (cuCIM-only properties) | relabeled values and a one-pixel padding (22 × 22 output for a 20 × 20 input); num_pixels_filled requested alone was the unfilled count → input label values and shape, filled count |
    | 19 | feret_diameter_max of a label value that does not occur (batch only) | RuntimeError: No coordinates to process → 0 |
    | 20 | regionprops_centroid (batch module) with num_pixels already in props_dict | TypeError: Wrong number of arguments → works |
    | 21 | regionprops_centroid, regionprops_centroid_local (batch module) | region of 2³² or more pixels: wrapped uint32 count, centroid row 2.1e9 → 32768 |
    | 23 | inertia_tensor_eigenvectors (cuCIM-only property) | the returned vectors were not eigenvectors of inertia_tensor (each eigenvector's components were reversed) → the columns are the eigenvectors, in the order of inertia_tensor_eigvals |

    Commit 15 is a bug in cuCIM's vendored copy only. SciPy and
    cupyx.scipy.ndimage.binary_fill_holes (CuPy 14.2) use the structuring
    element. No cuCIM function passed a structure to the vendored version
    before commit 16, whose per-label fallback does. Commit 17 completes commit
    15: the fast non-iterative algorithm labels the background with the
    structuring element, which is only valid for centrosymmetric 3 × 3 (× 3)
    structures that contain the center and all face neighbors. Other structures
    now use SciPy's iterative algorithm.

    The batch path returns a row for every label value 1 … max_label, also for
    values that do not occur (scikit-image returns only the labels present). Such
    rows have an area of 0, so commit 19 returns 0 for their
    feret_diameter_max, as for their area_convex, perimeter and axis
    lengths. Before, any label image with a gap in its label values made
    regionprops_table fail when feret_diameter_max was requested.

    regionprops_dict computes centroids from the raw moments, so commits 20 and
    21 only affect direct calls of the two helper functions.

    cupy.linalg.eigh returns each batch of eigenvectors as the columns of a
    (K, ndim, ndim) array. To put them in the descending order of
    inertia_tensor_eigvals, regionprops_inertia_tensor_eigvals reversed axis 1
    (the components of every eigenvector) instead of axis 2 (the eigenvectors).
    For an ellipse rotated by 30°, T @ v gave (−10.8, 25.2) instead of
    56.9 · (0.511, 0.860). The eigenvalues were correct. Commit 23 reverses the
    columns; the first eigenvector is then along the region's shortest axis (the
    largest eigenvalue of the inertia tensor).

    Behavior changes users may notice

  • orientation. Regions whose inertia tensor has equal diagonal entries

  • (±45°) change sign, in both paths. The values now match scikit-image ≥ 0.21.
  • New errors in batch mode, matching scikit-image and the per-label path:

  • - moments_hu and moments_weighted_hu raise NotImplementedError with
    non-unit spacing;
    - perimeter and perimeter_crofton raise it with anisotropic spacing.
  • Spacing. Batch values of the properties in commits 6–11 and 14 change

  • whenever the spacing is not 1.
  • label_filled. It now has the shape and the label values of the input,

  • with no padding and no relabeling.
  • feret_diameter_max of absent label values is 0 instead of an error.

  • inertia_tensor_eigenvectors returns actual eigenvectors (as columns).

  • bbox dtype for images of 2³² or more pixels is uint64 (it was

  • uint32 with wrapped values).
  • Speed. The filled-region properties are slower than before (next

  • section), because the old implementation did not compute per-region fills.

    Filled-region properties (commit 16)

    How the batch computation works:

    1. The label image is padded and its background labeled with full
    connectivity, as binary_fill_holes does with the 3ndim structuring
    element that scikit-image uses. Every background component except the one
    touching the padding is a hole.
    2. For each hole, the largest and smallest neighboring labels are found with a
    grey dilation and erosion. A hole with a single neighboring label is filled
    with that label. For that region, this is exactly what scikit-image's
    binary_fill_holes on the region's crop gives.
    3. scikit-image treats other labels as background. A label's result can
    therefore differ from step 2 only if:
    - (a) it borders a hole that also borders other labels, or
    - (b) a connected component of another label sits in one of its holes with
    no background in between. Such a component touches the label, and its
    bounding box lies strictly inside the label's bounding box.

    Labels matching (a) or (b) are recomputed one at a time with
    binary_fill_holes on their crop, as robust_perimeter does for close
    labels. The test is conservative: a flagged label may not need the
    recomputation, but every label that needs it is flagged. Test (b) uses the
    bounding box of the component, not of the whole label, because the other
    components of a nested label can lie anywhere.

    num_pixels_filled, area_filled and image_filled are all computed from
    this one result.

    area_filled timings, with the number of labels each version gets wrong
    compared with scikit-image 0.26:

    | Input | Labels | Recomputed per label | main (ms) | this PR (ms) | Wrong on main | Wrong here |
    |---|---:|---:|---:|---:|---:|---:|
    | tiles 2160 × 3840, 32 × 32 | 1024 | 0 | 5.8 | 16.0 | 1024 | 0 |
    | tiles 2160 × 3840, 127 × 128 | 16256 | 0 | 5.7 | 15.8 | 16256 | 0 |
    | binary_blobs 4096² | 240 | 0 | 9.6 | 20.4 | 0 | 0 |
    | 4 intensity levels 2048² | 1864 | 121 | 4.0 | 109.9 | 1864 | 0 |

    Setup:

  • RTX A6000, CuPy 14.2, regionprops_dict(labels, properties=["area_filled"]).

  • GPU time is the mean of 20 runs of cupyx.profiler.benchmark.

  • Inputs:

  • -
    Tiles: rectangular regions that all touch each other.
    -
    binary_blobs: blob_size_fraction=0.02, volume_fraction=0.5,
    labeled.
    -
    4 intensity levels: Gaussian-smoothed (σ = 8) uniform noise, split
    into 4 levels at its 10th, 50th and 90th percentiles. The connected
    components of each level are labeled, giving many regions nested inside
    others with no gap.

    Most of the added cost on images that need no recomputation comes from the
    extra full-image passes: the background labeling, the grey dilation and
    erosion, and the connected-component labeling for test (b). Test (b) alone
    adds about 3 ms on the tilings. On the intensity-levels image, the call takes
    11.2 ms when the recomputation is skipped, against 110.3 ms with it. Each of
    the 121 recomputed labels therefore costs about 0.8 ms, because the fallback
    loops over labels on the host. Batching that fallback would be a separate
    performance change.

    Images of 2³² or more pixels (commits 18 and 21)

    The batch bounding-box, centroid and moments kernels unravel each pixel's
    raveled index into coordinates in their coordinate type. That type was
    uint32 whenever every axis is shorter than 2³², so on larger images the
    raveled index wrapped. Commit 18 chooses uint64 coordinates when the image
    has 2³² or more pixels, in one helper (_get_coord_dtype) used by all four
    call sites. Commit 21 does the same for the pixel counts of the two centroid
    helpers, which were always uint32; the other count kernels already chose
    their type from the image size.

    Smaller images keep 32-bit coordinates and counts, whose integer divisions
    are much faster. Their generated kernels are unchanged: the sources of all
    57 kernels that regionprops_dict builds for 2D and 3D inputs with uint8,
    int32 and int64 labels (all non-convex properties) are identical before
    and after the commits.

    Checked on a (65537, 65536) uint8 label image (4.3 GB) with a uint8
    intensity image, outside the test suite:

  • Five regions before, straddling and after raveled index 2³² (one with a

  • hole) were compared with the same regions in a crop of a few rows around
    them, with the crop offset added back to bbox and the centroids.
  • 14 properties were compared, among them bbox, centroid,

  • centroid_weighted, centroid_local, moments_central,
    moments_weighted_central, inertia_tensor, intensity_mean and
    intensity_max.
  • Before commit 18 there were 16 mismatches, all for the two regions past

  • 2³². There are none after it.
  • A region of 2³² + 65521 pixels gets the exact bbox and centroid, with

  • either the moments or the coordinate sums.

    Two properties still cannot be computed on such an image with 48 GB of GPU
    memory (see "Not addressed here").

    Tests

    New tests:

  • Kernels: test_eccentricity_single_pixel_batch,

  • test_intensity_std_constant_regions, test_intensity_std_nonfinite,
    test_num_pixels_large_pixels_per_thread,
    test_intensity_min_and_max_float64_exact (float64 minima and maxima
    equal to scikit-image's exactly; the existing min/max tests used
    assert_allclose), test_inertia_tensor_eigenvectors (T·v = λ·v,
    orthonormality and descending order, 2D and 3D, with and without
    spacing)..
  • Batch regionprops_dict vs. scikit-image:

  • - test_regionprops_dict_spacing (2D and 3D, isotropic and anisotropic
    spacing, 10 properties);
    - test_regionprops_dict_perimeter_spacing,
    test_regionprops_dict_hu_spacing_not_implemented,
    test_regionprops_dict_area_filled_spacing,
    test_regionprops_dict_axis_lengths.
  • Filled regions: test_regionprops_dict_filled, with 8 cases: labels not

  • in raster order, touching, nested with a gap, nested and touching, nested
    with another component elsewhere, a ring open through a diagonal gap, a hole
    between two labels, and 3D. Also test_regionprops_dict_filled_random,
    test_label_filled and test_fill_holes_by_label_tiling_is_exact.
  • Both paths: test_orientation_continuity (ported from scikit-image),

  • test_orientation_diagonal_batch_matches_regionprops,
    test_centroid_weighted_offset_spacing,
    test_centroid_weighted_copy_to_host.
  • Vendored ndimage: test_binary_fill_holes_structure,

  • test_binary_fill_holes_iterative_structure.
  • Absent labels and helpers: test_feret_diameter_max_absent_label,

  • test_centroid_reuses_num_pixels.
  • Images of 2³² or more pixels:*

  • test_regionprops_dict_coordinates_beyond_2_32_pixels and
    test_centroid_region_of_2_32_pixels. Each uses a 4.3 GB label image and
    is skipped when less than 8.6 GB of GPU memory is free. They take about 2 s
    each on an RTX A6000.

    The expected values in the existing test_orientation were updated to
    scikit-image 0.26's.

    Every commit except the docstring one adds at least one test that fails
    without its fix. For the filled-region commit, this was checked against
    main's implementation: all 8 test_regionprops_dict_filled cases fail
    there. A few tests guard against regressions that main did not have.
    For example, test_intensity_std_nonfinite checks that clipping the variance
    keeps NaN for regions with NaN or inf values.

    Diff: 1686 lines (+1546 / -140) across 13 files Reviewer: gigony Review duration: 33958m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.61) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.61 · 1686 lines diff across 13 files
    0.61
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.94 · 5 substantive comment(s)
    0.94
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    88%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    28 items
    gigony gigony commented on code on Nov 24, 2026 00:27 UTC
    Code Review
    python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:1
    @@ -933,6 +934,130 @@ def regionprops_num_boundary_pixels(labels, max_label=None, props_dict=None):
         return edge_counts
     
     
    +def _fill_holes_by_label(labels, max_label, bbox=None):
    +    """Fill the background holes of each labeled region.
    +
    +    A hole is a connected component of the background (with full
    +    connectivity, as for ``binary_fill_holes`` with a ``3**ndim`` structuring
    +    element) that is not connected to the area outside of the image. A hole
    +    whose neighboring pixels all belong to a single region is filled with that
    +    region's label. This matches scikit-image's per-region ``image_filled`` for
    +    that region.
    +
    +    scikit-image fills each region's holes treating all other labels as
    +    background, so a region's filled image also contains holes bordered by
    +    several regions and any regions nested in its holes. For the labels where
    +    this can happen, the returned ``label_filled`` is not exact and the labels
    +    are returned in ``labels_inexact`` so that the caller can recompute them
    +    on per-label crops. These are the labels that (a) border a hole that also
    +    borders other labels, or (b) touch a connected component of another label
    +    whose bounding box lies strictly inside their own (a component nested in
    +    a hole of another region must lie strictly inside that region's bounding
    +    box, but the other components of its label can lie anywhere, so the test
    +    uses the bounding boxes of the components, not of the labels).
    +
    +    Returns
    +    -------
    +    label_filled : cupy.ndarray
    +        The label image with each single-region hole filled with its label.
    +    labels_inexact : numpy.ndarray
    +        Labels whose filled region may differ from scikit-image's.
    +    """
    +    ndim = labels.ndim
    +    footprint = ndi.generate_binary_structure(ndim, ndim)
    +    # with the padding, all background outside of the regions is a single
    +    # connected component
    +    padded = cp.pad(labels, 1, mode="constant", constant_values=0)
    +    work_dtype = cp.int32 if max_label < 2**31 - 1 else cp.int64
    +    padded = padded.astype(work_dtype, copy=False)
    +    background = padded == 0
    +    bg_labels = label(background, connectivity=ndim)
    +    num_bg = int(bg_labels.max())
    +    outer = int(bg_labels[(0,) * ndim])
    +
    +    # largest and smallest label in the 3**ndim neighborhood of each pixel
    +    # (the background is excluded from the minimum)
    +    no_label = max_label + 1
    +    nb_max = ndi.grey_dilation(padded, size=3, mode="constant", cval=0)
    +    nb_min = ndi.grey_erosion(
    +        cp.where(background, no_label, padded).astype(work_dtype, copy=False),
    +        size=3,
    +        mode="constant",
    +        cval=no_label,
    +    )
    +
    +    # labels bordering each background component
    +    bg_ids = bg_labels[background]
    +    hole_max = cp.zeros(num_bg + 1, dtype=work_dtype)
    +    hole_min = cp.full(num_bg + 1, no_label, dtype=work_dtype)
    +    cp.maximum.at(hole_max, bg_ids, nb_max[background])
    +    cp.minimum.at(hole_min, bg_ids, nb_min[background])
    +    component_ids = cp.arange(num_bg + 1)
    +    is_hole = (component_ids != 0) & (component_ids != outer)
    +    single = is_hole & (hole_min == hole_max)
    +    multi = is_hole & (hole_min != hole_max)
    +
    +    fill_value = cp.where(single, hole_max, 0).astype(work_dtype, copy=False)
    +    filled = cp.where(background, fill_value[bg_labels], padded)
    +    core = (slice(1, -1),) * ndim
    +    label_filled = cp.ascontiguousarray(filled[core].astype(labels.dtype))
    +
    +    # (a) labels bordering a hole that borders several labels
    +    inexact = []
    +    if bool(multi.any()):
    +        near_multi = ndi.binary_dilation(multi[bg_labels], structure=footprint)
    +        inexact.append(cp.unique(padded[near_multi & ~background]))
    +
    +    # (b) labels touching a connected component of another label whose
    +    # bounding box lies strictly inside their own
    +    touching = (~background) & ((nb_max != padded) | (nb_min != padded))
    +    touching &= padded != 0
    +    if bool(touching.any()):

    [P1-1] Negative labels can write outside the GPU bounding-box buffer

    AI-assisted review comment · Round 1 · New finding P1-1.

    Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.

    Normalize negative labels before narrowing the dtype or indexing the bounding-box array. The new nesting check turns −1 into ID 255 on the public batch path and indexes a box array sized for one label.

    CUDA Compute Sanitizer reproduced an invalid four-byte global atomic on the reviewed head. The same 2 × 2 input completed with zero memcheck errors on the base.

    <details>
    <summary>Evidence, proposed patch, and regression coverage</summary>

    Request area_filled for the signed image [[1, -1], [0, 0]]. The batch dispatcher derives a maximum of 1 and casts −1 to uint8, producing 255. The new fill sees touching labels and requests one four-element bounding box. The CUDA kernel uses (lab - 1) * 4, so label 255 addresses element 1016. The direct fill helper retains −1 and addresses element −8. The base filled and relabeled a binary mask before counting this example. CUDA Compute Sanitizer reported an invalid four-byte global atomic in cucim__bbox2d_batch16 followed by a launch failure on the reviewed head. The same public API call on the base completed with zero memcheck errors. The direct helper’s index follows from source inspection. python/cucim/src/cucim/skimage/measure/_regionprops_gpu.py:398-405 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:114-121 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:559-574 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:962-982

    Original hunk · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:1013-1017

        touching = (~background) & ((nb_max != padded) | (nb_min != padded))
        touching &= padded != 0
        if bool(touching.any()):
            if bbox is None:
                bbox, _ = regionprops_bbox_coords(labels, max_label=max_label)
    

    Recommended change

    Treat negative values as background before narrowing the batch image and before computing the direct helper’s maximum. Test both entry points with mixed-sign and all-negative inputs under Compute Sanitizer. The mixed example should leave label 1 with filled area 1.

    --- a/python/cucim/src/cucim/skimage/measure/_regionprops_gpu.py
    +++ b/python/cucim/src/cucim/skimage/measure/_regionprops_gpu.py
    @@ -398,2 +398,4 @@
         out = {}
    +    if label_image.dtype.kind == "i":
    +        label_image = cp.maximum(label_image, 0)
         if max_label is None:
    --- a/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py
    +++ b/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py
    @@ -1089,2 +1089,4 @@
         """
    +    if labels.dtype.kind == "i":
    +        labels = cp.maximum(labels, 0)
         if max_label is None:
    

    The proposed diff passed an application check against the reviewed head.

    </details>

    gigony gigony commented on code on Nov 24, 2026 00:27 UTC
    Code Review
    python/cucim/src/cucim/skimage/measure/_regionprops.py:1
    @@ -1023,10 +1042,7 @@ def _props_to_dict(
                     if copy_to_host:
                         column_data = np.empty((n,) + shape, dtype=dtype)
                         for k in range(n):
    -                        rp = regions[k][prop]
    -                        if isinstance(rp, cp.ndarray):
    -                            rp = cp.asnumpy(rp)
    -                        column_data[k] = rp
    +                        column_data[k] = _to_host(regions[k][prop])
                         out[orig_prop] = column_data

    [P2-1] Host conversion loses the channel axis of weighted centroids

    AI-assisted review comment · Round 1 · New finding P2-1.

    Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.

    Infer the complete shape of a multichannel weighted centroid before allocating host columns. The nested tuple holds one channel vector per coordinate, but the converter currently allocates storage for a single axis.

    Both split and unsplit host outputs raised ValueError on the RTX A6000 with a two-channel input and two labels.

    <details>
    <summary>Evidence, proposed patch, and regression coverage</summary>

    With two labels and a two-channel 2D intensity image, each per-label centroid_weighted is a tuple of two channel vectors. The converter records shape (2,). Its new recursive host copy then assigns a matrix to a vector in unsplit mode, or a vector to a scalar in split mode. Both calls raised ValueError on the GPU with batch_processing=False, copy_output_to_host=True. python/cucim/src/cucim/skimage/measure/_regionprops.py:722-732 · python/cucim/src/cucim/skimage/measure/_regionprops.py:1055-1071

    Original hunk · python/cucim/src/cucim/skimage/measure/_regionprops.py:1035-1045

            else:
                if isinstance(rp, cp.ndarray):
                    shape = rp.shape
                else:
                    shape = (len(rp),)
    
                if not to_table:
                    if copy_to_host:
                        column_data = np.empty((n,) + shape, dtype=dtype)
                        for k in range(n):
                            column_data[k] = _to_host(regions[k][prop])
    

    Recommended change

    Derive the complete shape of a host-bound tuple. Check four coordinate-by-channel columns in split mode and a (2, 2, 2) NumPy array in unsplit mode against the same reference centroids.

    --- a/python/cucim/src/cucim/skimage/measure/_regionprops.py
    +++ b/python/cucim/src/cucim/skimage/measure/_regionprops.py
    @@ -1037,2 +1037,4 @@
                     shape = rp.shape
    +            elif copy_to_host:
    +                shape = np.shape(_to_host(rp))
                 else:
    

    The proposed diff passed an application check against the reviewed head.

    </details>

    gigony gigony commented on code on Nov 24, 2026 00:27 UTC
    Code Review
    python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:1
    @@ -933,6 +934,130 @@ def regionprops_num_boundary_pixels(labels, max_label=None, props_dict=None):
         return edge_counts
     
     
    +def _fill_holes_by_label(labels, max_label, bbox=None):
    +    """Fill the background holes of each labeled region.
    +
    +    A hole is a connected component of the background (with full
    +    connectivity, as for ``binary_fill_holes`` with a ``3**ndim`` structuring
    +    element) that is not connected to the area outside of the image. A hole
    +    whose neighboring pixels all belong to a single region is filled with that
    +    region's label. This matches scikit-image's per-region ``image_filled`` for
    +    that region.
    +
    +    scikit-image fills each region's holes treating all other labels as
    +    background, so a region's filled image also contains holes bordered by
    +    several regions and any regions nested in its holes. For the labels where
    +    this can happen, the returned ``label_filled`` is not exact and the labels
    +    are returned in ``labels_inexact`` so that the caller can recompute them
    +    on per-label crops. These are the labels that (a) border a hole that also
    +    borders other labels, or (b) touch a connected component of another label
    +    whose bounding box lies strictly inside their own (a component nested in
    +    a hole of another region must lie strictly inside that region's bounding
    +    box, but the other components of its label can lie anywhere, so the test
    +    uses the bounding boxes of the components, not of the labels).
    +
    +    Returns
    +    -------
    +    label_filled : cupy.ndarray
    +        The label image with each single-region hole filled with its label.
    +    labels_inexact : numpy.ndarray
    +        Labels whose filled region may differ from scikit-image's.
    +    """
    +    ndim = labels.ndim
    +    footprint = ndi.generate_binary_structure(ndim, ndim)
    +    # with the padding, all background outside of the regions is a single
    +    # connected component
    +    padded = cp.pad(labels, 1, mode="constant", constant_values=0)
    +    work_dtype = cp.int32 if max_label < 2**31 - 1 else cp.int64
    +    padded = padded.astype(work_dtype, copy=False)
    +    background = padded == 0
    +    bg_labels = label(background, connectivity=ndim)
    +    num_bg = int(bg_labels.max())
    +    outer = int(bg_labels[(0,) * ndim])
    +
    +    # largest and smallest label in the 3**ndim neighborhood of each pixel
    +    # (the background is excluded from the minimum)
    +    no_label = max_label + 1
    +    nb_max = ndi.grey_dilation(padded, size=3, mode="constant", cval=0)
    +    nb_min = ndi.grey_erosion(
    +        cp.where(background, no_label, padded).astype(work_dtype, copy=False),
    +        size=3,
    +        mode="constant",
    +        cval=no_label,
    +    )
    +
    +    # labels bordering each background component
    +    bg_ids = bg_labels[background]
    +    hole_max = cp.zeros(num_bg + 1, dtype=work_dtype)
    +    hole_min = cp.full(num_bg + 1, no_label, dtype=work_dtype)
    +    cp.maximum.at(hole_max, bg_ids, nb_max[background])
    +    cp.minimum.at(hole_min, bg_ids, nb_min[background])
    +    component_ids = cp.arange(num_bg + 1)
    +    is_hole = (component_ids != 0) & (component_ids != outer)
    +    single = is_hole & (hole_min == hole_max)
    +    multi = is_hole & (hole_min != hole_max)
    +
    +    fill_value = cp.where(single, hole_max, 0).astype(work_dtype, copy=False)
    +    filled = cp.where(background, fill_value[bg_labels], padded)
    +    core = (slice(1, -1),) * ndim
    +    label_filled = cp.ascontiguousarray(filled[core].astype(labels.dtype))
    +
    +    # (a) labels bordering a hole that borders several labels
    +    inexact = []
    +    if bool(multi.any()):
    +        near_multi = ndi.binary_dilation(multi[bg_labels], structure=footprint)
    +        inexact.append(cp.unique(padded[near_multi & ~background]))
    +
    +    # (b) labels touching a connected component of another label whose
    +    # bounding box lies strictly inside their own
    +    touching = (~background) & ((nb_max != padded) | (nb_min != padded))
    +    touching &= padded != 0
    +    if bool(touching.any()):
    +        if bbox is None:
    +            bbox, _ = regionprops_bbox_coords(labels, max_label=max_label)

    [P2-2] Two touching pixels can require a 16 GiB temporary bounding-box array

    AI-assisted review comment · Round 1 · New finding P2-2.

    Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.

    Bound fill scratch storage by the number of present labels. The connected-component nesting check allocates one box per ID up to the maximum, even when the caller only needs the filled image. Compact sparse labels for the fill and restore the original IDs afterward.

    A two-pixel input with IDs 1 and 2³⁰ attempted a 16 GiB allocation on the reviewed head. A 256 MiB memory-pool limit stopped the allocation. The base completed under the same limit.

    <details>
    <summary>Evidence, proposed patch, and regression coverage</summary>

    For regionprops_label_filled([[1, 230]]) with uint32 input, the new nesting check asks for one 2D box per integer through the maximum. Its shape is (230, 4) with four bytes per entry. The helper discards the nesting result, and its image output has just two pixels. The same allocation occurs for a regionprops_dict request for label_filled alone. The base used image-sized component labels. Sparse IDs above 2⁵³ can also round in the grey filters’ double intermediates. python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:548-564 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:1090-1095 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu.py:757-765 · python/cucim/src/cucim/skimage/_vendored/_ndimage_filters.py:1462-1468

    Original hunk · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:1015-1017

        if bool(touching.any()):
            if bbox is None:
                bbox, _ = regionprops_bbox_coords(labels, max_label=max_label)
    

    Recommended change

    For the sparse case, assign compact integer IDs for the fill and map its two outputs back to the original IDs. The recursive call below runs once on a maximum bounded by the pixel count. Apply P1-1 first. Check the two-pixel example and a ring labeled 2**53 + 1 for exact labels and image-sized scratch storage. Per-label table rows still follow the existing dense-row convention.

    --- a/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py
    +++ b/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py
    @@ -965,2 +965,12 @@
         """
    +    if labels.size and max_label > labels.size:
    +        values, codes = cp.unique(labels, return_inverse=True)
    +        if int(values[0]) != 0:
    +            values = cp.pad(values, (1, 0))
    +            codes += 1
    +        n = values.size - 1
    +        dense = codes.reshape(labels.shape).astype(_get_min_integer_dtype(n))
    +        filled, inexact = _fill_holes_by_label(dense, n)
    +        return values[filled], cp.asnumpy(values[cp.asarray(inexact)])
    +
         ndim = labels.ndim
    @@ -1136,2 +1146,3 @@
             for lab in labels_inexact:
    +            lab = int(lab)
                 image = label_image[slices[lab - 1]] == lab
    

    The proposed diff passed an application check against the reviewed head.

    </details>

    gigony gigony commented on code on Nov 24, 2026 00:27 UTC
    Code Review
    python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:1
    @@ -479,8 +488,8 @@ def get_mean_var_kernel(dtype, sample_std=False):
                   var = 0.0;
                 }} else {{
                   m = static_cast<double>(sum) / count;
    -              var = sqrt(
    -                  (static_cast<double>(sumsq) - m * m * count) / count);
    +              double v = (static_cast<double>(sumsq) - m * m * count) / count;

    [P2-3] An overflowing squared sum gives a varying region zero standard deviation

    AI-assisted review comment · Round 1 · New finding P2-3.

    Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.

    Accumulate squared intensities in a type that can hold their sum. For a uint32 region containing 0 and two UINT32_MAX pixels, the uint64 sum of squares wraps, and the new variance clamp converts the negative result to zero.

    The RTX A6000 returned 0 for that region. NumPy returned 2,024,666,999.51.

    <details>
    <summary>Evidence, proposed patch, and regression coverage</summary>

    For one uint32 region with values [0, 232 - 1, 232 - 1], two squared maxima overflow the uint64 accumulator. The existing one-pass formula then produces a large negative variance. The new clamp turns the baseline NaN into 0, hiding variation in the measurements. The GPU returned 0 and NumPy returned 2,024,666,999.51. The sample and population branches both clip. python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:77-87 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:196-204 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:470-492

    Original hunk · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:489-492

                }} else {{
                  m = static_cast<double>(sum) / count;
                  double v = (static_cast<double>(sumsq) - m * m * count) / count;
                  var = sqrt(v < 0.0 ? 0.0 : v);
    

    Recommended change

    Use double accumulation before squaring and match the reduction’s output buffers to that type whenever squared sums are requested. Check both population and sample standard deviation against NumPy. This correction addresses integer overflow. The one-pass formula retains its existing sensitivity to cancellation for nearly equal large values.

    --- a/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py
    +++ b/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py
    @@ -259,2 +259,5 @@
         ) = _get_intensity_img_kernel_dtypes(image_dtype)
    +    if compute_sum_sq:
    +        sum_dtype = cp.dtype(cp.float64)
    +        c_sum_type = "double"
     
    @@ -527,3 +530,3 @@
         image_dtype = intensity_image.dtype
    -    sum_dtype, _, _, _ = _get_intensity_img_kernel_dtypes(image_dtype)
    +    sum_dtype = cp.dtype(cp.float64)
    

    The proposed diff passed an application check against the reviewed head.

    </details>

    gigony gigony commented on Nov 24, 2026 00:27 UTC
    Reviewer

    Round 1 review, reviewed source 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.

    Recommendation: Request changes. CUDA Compute Sanitizer confirmed an out-of-bounds GPU atomic write in the new fill path for a signed 2 × 2 input.

    11 active findings · 11 new · 0 previously reported (1 P1, 6 P2, 4 P3).

  • P1-1: Negative labels can write outside the GPU bounding-box buffer

  • P2-1: Host conversion loses the channel axis of weighted centroids

  • P2-2: Two touching pixels can require a 16 GiB temporary bounding-box array

  • P2-3: An overflowing squared sum gives a varying region zero standard deviation

  • P2-4: Float64 minima and maxima can return a finite value absent from the region

  • P2-5: Default 1D filling scans a long background vector quadratically

  • P2-6: Varying the maximum label generates new GPU erosion kernels

  • P3-1: Changing the footprint can make an in-place fill return None

  • P3-2: Per-label measurement copies the same device spacing to the host for each region

  • P3-3: A host footprint can raise TypeError only when it selects iterative filling

  • P3-4: The iterative-fill regression test passes when its footprint is ignored
  • Validation: All 39 reported GitHub checks and 11 focused RTX A6000 tests passed, including both large-image cases. Targeted GPU probes reproduced the signed-label, sparse-allocation, weighted-centroid, and intensity findings.

    <!-- code-review: round=1 sha=0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8 findings=P1:1,P2:6,P3:4 -->

    gigony gigony commented on code on Nov 24, 2026 00:27 UTC
    Code Review
    python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:1
    @@ -167,11 +170,11 @@ def _get_intensity_min_max_code(
         if compute_min:
             for c in range(num_channels):
                 source_post += f"""
    -            atomicMin(&minimums[{nc}(lab - 1) + {c}], min_vals[{nc}jj + {c}]);"""  # noqa: E501
    +            cucim_atomic_min(&minimums[{nc}(lab - 1) + {c}], min_vals[{nc}jj + {c}]);"""  # noqa: E501

    [P2-4] Float64 minima and maxima can return a finite value absent from the region

    AI-assisted review comment · Round 1 · New finding P2-4.

    Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.

    Initialize float64 extrema with positive and negative infinity at both reduction stages. Finite initializers cause an all-positive-infinity region to return a finite minimum and an all-negative-infinity region to return a finite maximum.

    Both errors reproduced on the RTX A6000. The base returned the expected infinities.

    <details>
    <summary>Evidence, proposed patch, and regression coverage</summary>

    An all-+inf region returned float64.max for its minimum. An all--inf region returned -float64.max for its maximum. Both the per-thread and the global reductions start at finite values. The new double-precision atomic now preserves those initializers even when every observation is more extreme. The finite-random regression test passes on this head. python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:222-236 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:624-634 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_utils.py:32-57

    Original hunk · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:275-286

        any_min_max = compute_min or compute_max
        if any_min_max:
            if min_max_dtype is None:
                raise ValueError("min_max_dtype must be specified")
            range_min, range_max = _get_intensity_range(min_max_dtype)
            min_max_pre, min_max_op, min_max_post = _get_intensity_min_max_code(
                min_max_dtype=min_max_dtype,
                c_min_max_type=c_min_max_type,
                array_size=array_size,
                num_channels=num_channels,
                initial_max_val=range_min,
                initial_min_val=range_max,
    

    Recommended change

    Use ±infinity at both reduction stages for float64. The diff covers present labels. For missing labels it also changes the exposed initial values to infinities. If callers rely on finite sentinels for gaps, restore those rows with a presence mask. Exercise both signs, a finite/infinite mixture, and an absent label.

    --- a/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py
    +++ b/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py
    @@ -279,2 +279,4 @@
             range_min, range_max = _get_intensity_range(min_max_dtype)
    +        if min_max_dtype == cp.float64:
    +            range_min, range_max = "-CUDART_INF", "CUDART_INF"
             min_max_pre, min_max_op, min_max_post = _get_intensity_min_max_code(
    @@ -627,2 +629,4 @@
         range_min, range_max = _get_intensity_range(image_dtype)
    +    if min_max_dtype == cp.float64:
    +        range_min, range_max = -math.inf, math.inf
         out_shape = (
    

    The proposed diff passed an application check against the reviewed head.

    </details>

    gigony gigony commented on code on Nov 24, 2026 00:27 UTC
    Code Review
    python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:1
    @@ -868,23 +868,44 @@ def _binary_fill_holes_non_iterative(input, structure=None, output=None):
         return output
     
     
    +def _can_use_label_for_fill_holes(structure, ndim):
    +    # In 1D the padding at opposite ends is not connected.
    +    if ndim < 2:
    +        return False

    [P2-5] Default 1D filling scans a long background vector quadratically

    AI-assisted review comment · Round 1 · New finding P2-5.

    Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.

    Keep the default 1D fill linear by finding the first and last foreground positions and filling the interval. Sending a long all-zero vector through brute-force dilation takes one full scan and a convergence check per propagation step.

    Source inspection and a SciPy propagation probe confirmed the mechanism and 513 steps for a 1,024-element vector. GPU timing was outside this check.

    <details>
    <summary>Evidence, proposed patch, and regression coverage</summary>

    The rank check sends even the default 1D footprint through brute-force dilation. On an all-zero vector the exterior advances one pixel from each end per full scan, followed by a device-wide equality check observed by the host. A length of 1,024 requires 513 passes including convergence, as confirmed with the same propagation in SciPy. The base labeling algorithm already gave the correct result for this input. python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:307-328 · python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:953-982

    Original hunk · python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:871-876

    def _can_use_label_for_fill_holes(structure, ndim):
        # In 1D the padding at opposite ends is not connected.
        if ndim < 2:
            return False
        if structure is None:
            return True
    

    Recommended change

    Allow labeling for the compatible 1D footprint and remove the background components at both padded ends. Keep the existing separated-ends test. Add a long all-zero vector and check that it takes the labeling path. Custom footprints still pass through the connectivity checks.

    --- a/python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py
    +++ b/python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py
    @@ -850,2 +850,4 @@
         inverse_binary_mask[inverse_labels == background_index] = 0
    +    if ndim == 1:
    +        inverse_binary_mask[inverse_labels == inverse_labels[-1]] = 0
     
    @@ -871,4 +873,3 @@
     def _can_use_label_for_fill_holes(structure, ndim):
    -    # In 1D the padding at opposite ends is not connected.
    -    if ndim < 2:
    +    if ndim == 0:
             return False
    @@ -902,3 +903,3 @@
                 one, as in SciPy. With the default origin and axes, inputs with
    -            at least two dimensions use a faster non-iterative algorithm
    +            at least one dimension use a faster non-iterative algorithm
                 when the structure is centrosymmetric, has size 3 on every axis,
    

    The proposed diff passed an application check against the reviewed head.

    </details>

    gigony gigony commented on code on Nov 24, 2026 00:27 UTC
    Code Review
    python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:1
    @@ -933,6 +934,130 @@ def regionprops_num_boundary_pixels(labels, max_label=None, props_dict=None):
         return edge_counts
     
     
    +def _fill_holes_by_label(labels, max_label, bbox=None):
    +    """Fill the background holes of each labeled region.
    +
    +    A hole is a connected component of the background (with full
    +    connectivity, as for ``binary_fill_holes`` with a ``3**ndim`` structuring
    +    element) that is not connected to the area outside of the image. A hole
    +    whose neighboring pixels all belong to a single region is filled with that
    +    region's label. This matches scikit-image's per-region ``image_filled`` for
    +    that region.
    +
    +    scikit-image fills each region's holes treating all other labels as
    +    background, so a region's filled image also contains holes bordered by
    +    several regions and any regions nested in its holes. For the labels where
    +    this can happen, the returned ``label_filled`` is not exact and the labels
    +    are returned in ``labels_inexact`` so that the caller can recompute them
    +    on per-label crops. These are the labels that (a) border a hole that also
    +    borders other labels, or (b) touch a connected component of another label
    +    whose bounding box lies strictly inside their own (a component nested in
    +    a hole of another region must lie strictly inside that region's bounding
    +    box, but the other components of its label can lie anywhere, so the test
    +    uses the bounding boxes of the components, not of the labels).
    +
    +    Returns
    +    -------
    +    label_filled : cupy.ndarray
    +        The label image with each single-region hole filled with its label.
    +    labels_inexact : numpy.ndarray
    +        Labels whose filled region may differ from scikit-image's.
    +    """
    +    ndim = labels.ndim
    +    footprint = ndi.generate_binary_structure(ndim, ndim)
    +    # with the padding, all background outside of the regions is a single
    +    # connected component
    +    padded = cp.pad(labels, 1, mode="constant", constant_values=0)
    +    work_dtype = cp.int32 if max_label < 2**31 - 1 else cp.int64
    +    padded = padded.astype(work_dtype, copy=False)
    +    background = padded == 0
    +    bg_labels = label(background, connectivity=ndim)
    +    num_bg = int(bg_labels.max())
    +    outer = int(bg_labels[(0,) * ndim])
    +
    +    # largest and smallest label in the 3**ndim neighborhood of each pixel
    +    # (the background is excluded from the minimum)
    +    no_label = max_label + 1
    +    nb_max = ndi.grey_dilation(padded, size=3, mode="constant", cval=0)
    +    nb_min = ndi.grey_erosion(
    +        cp.where(background, no_label, padded).astype(work_dtype, copy=False),
    +        size=3,
    +        mode="constant",
    +        cval=no_label,

    [P2-6] Varying the maximum label generates new GPU erosion kernels

    AI-assisted review comment · Round 1 · New finding P2-6.

    Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.

    Use a border mode that lets erosion reuse its compiled kernel across label counts. The current sentinel becomes both a kernel cache key and a CUDA literal. For a size-3 neighborhood, the existing one-pixel sentinel border is enough for the pixels of interest.

    Verified the memoization key and generated source path statically.

    <details>
    <summary>Evidence, proposed patch, and regression coverage</summary>

    Two tiles of the same shape and dtype with different maximum IDs pass different cval arguments to grey erosion. The separable filter includes that value in its per-device memoization key and embeds it as a literal in CUDA source. Streams of tiles with new object counts therefore accumulate distinct kernel variants and incur cold compilation on cache misses. Repeating one tile in a timing loop reuses its variant. python/cucim/src/cucim/skimage/_vendored/_ndimage_filters.py:1318-1330 · python/cucim/src/cucim/skimage/_vendored/_ndimage_filters.py:1436-1456 · python/cucim/src/cucim/skimage/_vendored/_ndimage_filters_core.py:348-353

    Original hunk · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:980-987

        no_label = max_label + 1
        nb_max = ndi.grey_dilation(padded, size=3, mode="constant", cval=0)
        nb_min = ndi.grey_erosion(
            cp.where(background, no_label, padded).astype(work_dtype, copy=False),
            size=3,
            mode="constant",
            cval=no_label,
        )
    

    Recommended change

    Use a fixed boundary mode. The existing one-pixel border supplies the entire size-three neighborhood for every interior output the algorithm uses. Vary the maximum across same-shape tiles and check that the erosion kernel is reused and the filled pixels agree with the reference. Compile latency was not timed.

    --- a/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py
    +++ b/python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py
    @@ -984,4 +984,3 @@
             size=3,
    -        mode="constant",
    -        cval=no_label,
    +        mode="nearest",
         )
    

    The proposed diff passed an application check against the reviewed head.

    </details>

    gigony gigony commented on code on Nov 24, 2026 00:27 UTC
    Code Review
    python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:1
    @@ -915,7 +936,15 @@ def binary_fill_holes(
         if isinstance(origin, int):
             origin = (origin,) * len(axes)
         if all(o == 0 for o in origin) and filter_all_axes:
    -        return _binary_fill_holes_non_iterative(input, output=output)
    +        # label uses a host footprint; keep the original device footprint
    +        # for the iterative path if the non-iterative assumptions do not hold.
    +        structure_cpu = structure
    +        if isinstance(structure, cupy.ndarray):
    +            structure_cpu = cupy.asnumpy(structure)
    +        if _can_use_label_for_fill_holes(structure_cpu, input.ndim):
    +            return _binary_fill_holes_non_iterative(

    [P3-1] Changing the footprint can make an in-place fill return None

    AI-assisted review comment · Round 1 · New finding P3-1.

    Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.

    Preserve the existing return value when the caller supplies an output array. A footprint that selects iterative filling updates that array but now returns None, while a footprint that selects labeling returns the array.

    Verified the two return paths in the pinned source.

    <details>
    <summary>Evidence, proposed patch, and regression coverage</summary>

    With default origin and axes, the base returned the supplied output array. On this head a compatible footprint still returns it. A horizontal device footprint selects the iterative branch, which writes the buffer and falls through with None. Code using the documented array result can fail on its next array operation. The new in-place test examines the buffer only. python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:855-868 · python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:919-921 · python/cucim/src/cucim/skimage/_vendored/tests/test_morphology.py:183-188

    Original hunk · python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:966-971

                brute_force=True,
                axes=axes,
            )
            cupy.logical_not(output, output)
        else:
            output = binary_dilation(
    

    Recommended change

    Return the output array on both branches to preserve cuCIM’s default-origin behavior. For a full and a horizontal footprint, check result is out and compare the updated pixels with SciPy.

    --- a/python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py
    +++ b/python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py
    @@ -982,3 +982,3 @@
             cupy.logical_not(output, output)
    -        return output
    +    return output
    

    The proposed diff passed an application check against the reviewed head.

    </details>

    gigony gigony commented on code on Nov 24, 2026 00:27 UTC
    Code Review
    python/cucim/src/cucim/skimage/measure/_regionprops.py:1
    @@ -344,11 +349,12 @@ def __init__(
             self._ndim = label_image.ndim
             self._multichannel = multichannel
             self._spatial_axes = tuple(range(self._ndim))
    -        self._spacing = spacing if spacing is not None else (1.0,) * self._ndim
    -        if isinstance(self._spacing, cp.ndarray):
    -            self._pixel_area = cp.product(self._spacing)
    +        if spacing is None:
    +            self._spacing = (1.0,) * self._ndim
             else:
    -            self._pixel_area = math.prod(self._spacing)
    +            # a scalar means the same spacing along every axis
    +            self._spacing = _normalize_spacing(spacing, self._ndim)

    [P3-2] Per-label measurement copies the same device spacing to the host for each region

    AI-assisted review comment · Round 1 · New finding P3-2.

    Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.

    Normalize a device spacing vector once per regionprops call. Each RegionProperties constructor now copies the same vector to the host, so a call with 1,024 labels can incur 1,024 synchronized transfers even when the caller only requests labels.

    Verified the construction loop and device-to-host transfer in the pinned source.

    <details>
    <summary>Evidence, proposed patch, and regression coverage</summary>

    A regionprops call with a CuPy spacing vector constructs a RegionProperties object for every present label. Each constructor now calls cp.asnumpy on the same vector. A label-only request with 1,024 regions thus performs 1,024 synchronous transfers. The base kept device spacing on the device. python/cucim/src/cucim/skimage/measure/_regionprops.py:349-357 · python/cucim/src/cucim/skimage/measure/_regionprops.py:1634-1652

    Original hunk · python/cucim/src/cucim/skimage/measure/_regionprops_utils.py:385-387

        if isinstance(spacing, cp.ndarray):
            spacing = cp.asnumpy(spacing)
        spacing = np.array(spacing)
    

    Recommended change

    Download the spacing once before the loop. Count transfers for a many-label request and verify that spacing (2, 3) still gives each single-pixel region area 6. Constructor validation continues to cover direct callers.

    --- a/python/cucim/src/cucim/skimage/measure/_regionprops.py
    +++ b/python/cucim/src/cucim/skimage/measure/_regionprops.py
    @@ -1633,2 +1633,5 @@
     
    +    if isinstance(spacing, cp.ndarray):
    +        spacing = cp.asnumpy(spacing)
    +
         regions = []
    

    The proposed diff passed an application check against the reviewed head.

    </details>

    gigony gigony commented on code on Nov 24, 2026 00:27 UTC
    Code Review
    python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:1
    @@ -915,7 +936,15 @@ def binary_fill_holes(
         if isinstance(origin, int):
             origin = (origin,) * len(axes)
         if all(o == 0 for o in origin) and filter_all_axes:
    -        return _binary_fill_holes_non_iterative(input, output=output)
    +        # label uses a host footprint; keep the original device footprint
    +        # for the iterative path if the non-iterative assumptions do not hold.
    +        structure_cpu = structure
    +        if isinstance(structure, cupy.ndarray):
    +            structure_cpu = cupy.asnumpy(structure)
    +        if _can_use_label_for_fill_holes(structure_cpu, input.ndim):

    [P3-3] A host footprint can raise TypeError only when it selects iterative filling

    AI-assisted review comment · Round 1 · New finding P3-3.

    Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.

    Convert host footprints before passing them to the iterative GPU path. A compatible NumPy footprint can take the labeling path, while a horizontal NumPy footprint falls through to dilation and raises TypeError.

    GPU comparison reproduced the TypeError. The vendored morphology suite passed with the proposed conversion and revised fixture, with 430 passes and 13 skips.

    <details>
    <summary>Evidence, proposed patch, and regression coverage</summary>

    With default origin and axes a full 3 × 3 NumPy footprint reaches the host-compatible labeling route. Change its values to a horizontal line and the dispatcher forwards a NumPy array into device dilation, raising TypeError. Nested lists encounter the dilation helper’s shape shorthand. The base accepted both by ignoring them. This is a low-priority compatibility issue in the vendored helper. Its docstring specifies a CuPy footprint and the region-measurement fallback supplies one. python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:898-908 · python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:953-968 · python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:341-356 · python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:1135-1139

    Original hunk · python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:941-947

            structure_cpu = structure
            if isinstance(structure, cupy.ndarray):
                structure_cpu = cupy.asnumpy(structure)
            if _can_use_label_for_fill_holes(structure_cpu, input.ndim):
                return _binary_fill_holes_non_iterative(
                    input, structure=structure_cpu, output=output
                )
    

    Recommended change

    Convert a host footprint when the default-origin dispatcher selects iteration. Preserve the shape shorthand for lower-rank lists. Compare a horizontal NumPy footprint, its nested-list equivalent and a CuPy copy with the same SciPy result.

    --- a/python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py
    +++ b/python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py
    @@ -947,2 +947,6 @@
                 )
    +        if isinstance(structure, numpy.ndarray) or (
    +            isinstance(structure, list) and numpy.ndim(structure) == input.ndim
    +        ):
    +            structure = cupy.asarray(structure, dtype=bool)
         elif filter_all_axes:
    

    The proposed diff passed an application check against the reviewed head.

    </details>

    gigony gigony commented on code on Nov 24, 2026 00:27 UTC
    Code Review
    python/cucim/src/cucim/skimage/_vendored/tests/test_morphology.py:1
    @@ -132,3 +132,66 @@ def test_grey_axes(func, expand_axis, origin, footprint_mode, mode):
         cucim_func = getattr(ndi, func)
         cucim_func(data, output=out, axes=axes, **kwargs)
         cp.testing.assert_array_almost_equal(out, expected)
    +
    +
    +@pytest.mark.parametrize("ndim", [2, 3])
    +@pytest.mark.parametrize("connectivity", [1, 2, 3])
    +def test_binary_fill_holes_structure(ndim, connectivity):
    +    # the non-iterative algorithm (used with the default origin and axes)
    +    # must also use the structuring element
    +    if connectivity > ndim:
    +        pytest.skip("connectivity > ndim")
    +    rng = np.random.default_rng(5)
    +    shape = (64, 64) if ndim == 2 else (16, 16, 16)
    +    data = rng.random(shape) > 0.35
    +    struct = ndi_cpu.generate_binary_structure(ndim, connectivity)
    +    expected = ndi_cpu.binary_fill_holes(data, struct)
    +    # the structuring element changes which background pixels are holes
    +    default = ndi_cpu.binary_fill_holes(data)
    +    assert np.array_equal(expected, default) == (connectivity == 1)
    +    out = ndi.binary_fill_holes(cp.asarray(data), cp.asarray(struct))
    +    cp.testing.assert_array_equal(out, expected)
    +
    +
    +@pytest.mark.parametrize("ndim", [2, 3])
    +@pytest.mark.parametrize(
    +    "footprint", ["horizontal", "large", "asymmetric", "diagonal"]
    +)
    +@pytest.mark.parametrize("empty", [False, True])
    +@pytest.mark.parametrize("inplace", [False, True])
    +def test_binary_fill_holes_iterative_structure(ndim, footprint, empty, inplace):
    +    if footprint == "horizontal":
    +        struct = np.zeros((3,) * ndim, dtype=bool)
    +        struct[(1,) * (ndim - 1) + (slice(None),)] = True
    +    elif footprint == "large":
    +        struct = np.ones((5,) * ndim, dtype=bool)
    +    elif footprint == "asymmetric":
    +        struct = np.ones((3,) * ndim, dtype=bool)
    +        struct[(0,) * ndim] = False
    +    else:
    +        struct = np.zeros((3,) * ndim, dtype=bool)
    +        for index in range(3):
    +            struct[(index,) * ndim] = True
    +
    +    data = np.zeros((9,) * ndim, dtype=bool)
    +    if not empty:
    +        data[(slice(1, -1),) * ndim] = True
    +        data[(slice(3, -3),) * ndim] = False

    [P3-4] The iterative-fill regression test passes when its footprint is ignored

    AI-assisted review comment · Round 1 · New finding P3-4.

    Reviewed commit 0bdfc1bf9f390a3df70fa4be32a8c7a8eadb5de8.

    Use a non-empty fixture whose expected result changes with the footprint. The padded hollow box gets the same result with each selected footprint and the default, so the test passes even when the implementation ignores structure.

    All 32 combinations passed against the original implementation. The revised non-empty fixture distinguished the requested footprints from the default in SciPy.

    <details>
    <summary>Evidence, proposed patch, and regression coverage</summary>

    The hollow box has thick walls. For all four footprints in both dimensions, SciPy produces the same mask with the supplied footprint and with the default. The empty controls also agree. All 32 combinations can therefore pass the old dispatch that ignored the footprint. The adjacent fast-path test already uses a fixture that distinguishes connectivity. python/cucim/src/cucim/skimage/_vendored/tests/test_morphology.py:144-153 · python/cucim/src/cucim/skimage/_vendored/tests/test_morphology.py:156-188

    Original hunk · python/cucim/src/cucim/skimage/_vendored/tests/test_morphology.py:176-182

        data = np.zeros((9,) * ndim, dtype=bool)
        if not empty:
            data[(slice(1, -1),) * ndim] = True
            data[(slice(3, -3),) * ndim] = False
        expected = ndi_cpu.binary_fill_holes(data, struct)
        data = cp.asarray(data)
        struct = cp.asarray(struct)
    

    Recommended change

    Keep the empty case and use a seeded non-empty input where the selected footprint changes the reference pixels. A SciPy comparison confirmed differing outputs for all eight rank/footprint pairs with the seed below.

    --- a/python/cucim/src/cucim/skimage/_vendored/tests/test_morphology.py
    +++ b/python/cucim/src/cucim/skimage/_vendored/tests/test_morphology.py
    @@ -175,7 +175,9 @@
     
    -    data = np.zeros((9,) * ndim, dtype=bool)
    +    if empty:
    +        data = np.zeros((9,) * ndim, dtype=bool)
    +    else:
    +        data = np.random.default_rng(5).random((24,) * ndim) > 0.35
    +    expected = ndi_cpu.binary_fill_holes(data, struct)
         if not empty:
    -        data[(slice(1, -1),) * ndim] = True
    -        data[(slice(3, -3),) * ndim] = False
    -    expected = ndi_cpu.binary_fill_holes(data, struct)
    +        assert not np.array_equal(expected, ndi_cpu.binary_fill_holes(data))
         data = cp.asarray(data)
    

    The proposed diff passed an application check against the reviewed head.

    </details>

    gigony gigony approved these changes on Nov 24, 2026 01:25 UTC
    Approved Reviewer

    Thank you @grlee77 for fixing bug on this. It looks good to me overall.
    Please find the ai review comments, before merge (at least P1 (+ P2)).
    Thank you!

    grlee77 grlee77 commented on code on Nov 24, 2026 02:30 UTC
    Code Review
    python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:1
    @@ -479,8 +488,8 @@ def get_mean_var_kernel(dtype, sample_std=False):
                   var = 0.0;
                 }} else {{
                   m = static_cast<double>(sum) / count;
    -              var = sqrt(
    -                  (static_cast<double>(sumsq) - m * m * count) / count);
    +              double v = (static_cast<double>(sumsq) - m * m * count) / count;

    This is addressed among other improvements in #1228, but can push a more minimal fix in this branch.

    grlee77 grlee77 commented on code on Nov 24, 2026 02:49 UTC
    Code Review
    python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:1
    @@ -933,6 +934,130 @@ def regionprops_num_boundary_pixels(labels, max_label=None, props_dict=None):
         return edge_counts
     
     
    +def _fill_holes_by_label(labels, max_label, bbox=None):
    +    """Fill the background holes of each labeled region.
    +
    +    A hole is a connected component of the background (with full
    +    connectivity, as for ``binary_fill_holes`` with a ``3**ndim`` structuring
    +    element) that is not connected to the area outside of the image. A hole
    +    whose neighboring pixels all belong to a single region is filled with that
    +    region's label. This matches scikit-image's per-region ``image_filled`` for
    +    that region.
    +
    +    scikit-image fills each region's holes treating all other labels as
    +    background, so a region's filled image also contains holes bordered by
    +    several regions and any regions nested in its holes. For the labels where
    +    this can happen, the returned ``label_filled`` is not exact and the labels
    +    are returned in ``labels_inexact`` so that the caller can recompute them
    +    on per-label crops. These are the labels that (a) border a hole that also
    +    borders other labels, or (b) touch a connected component of another label
    +    whose bounding box lies strictly inside their own (a component nested in
    +    a hole of another region must lie strictly inside that region's bounding
    +    box, but the other components of its label can lie anywhere, so the test
    +    uses the bounding boxes of the components, not of the labels).
    +
    +    Returns
    +    -------
    +    label_filled : cupy.ndarray
    +        The label image with each single-region hole filled with its label.
    +    labels_inexact : numpy.ndarray
    +        Labels whose filled region may differ from scikit-image's.
    +    """
    +    ndim = labels.ndim
    +    footprint = ndi.generate_binary_structure(ndim, ndim)
    +    # with the padding, all background outside of the regions is a single
    +    # connected component
    +    padded = cp.pad(labels, 1, mode="constant", constant_values=0)
    +    work_dtype = cp.int32 if max_label < 2**31 - 1 else cp.int64
    +    padded = padded.astype(work_dtype, copy=False)
    +    background = padded == 0
    +    bg_labels = label(background, connectivity=ndim)
    +    num_bg = int(bg_labels.max())
    +    outer = int(bg_labels[(0,) * ndim])
    +
    +    # largest and smallest label in the 3**ndim neighborhood of each pixel
    +    # (the background is excluded from the minimum)
    +    no_label = max_label + 1
    +    nb_max = ndi.grey_dilation(padded, size=3, mode="constant", cval=0)
    +    nb_min = ndi.grey_erosion(
    +        cp.where(background, no_label, padded).astype(work_dtype, copy=False),
    +        size=3,
    +        mode="constant",
    +        cval=no_label,
    +    )
    +
    +    # labels bordering each background component
    +    bg_ids = bg_labels[background]
    +    hole_max = cp.zeros(num_bg + 1, dtype=work_dtype)
    +    hole_min = cp.full(num_bg + 1, no_label, dtype=work_dtype)
    +    cp.maximum.at(hole_max, bg_ids, nb_max[background])
    +    cp.minimum.at(hole_min, bg_ids, nb_min[background])
    +    component_ids = cp.arange(num_bg + 1)
    +    is_hole = (component_ids != 0) & (component_ids != outer)
    +    single = is_hole & (hole_min == hole_max)
    +    multi = is_hole & (hole_min != hole_max)
    +
    +    fill_value = cp.where(single, hole_max, 0).astype(work_dtype, copy=False)
    +    filled = cp.where(background, fill_value[bg_labels], padded)
    +    core = (slice(1, -1),) * ndim
    +    label_filled = cp.ascontiguousarray(filled[core].astype(labels.dtype))
    +
    +    # (a) labels bordering a hole that borders several labels
    +    inexact = []
    +    if bool(multi.any()):
    +        near_multi = ndi.binary_dilation(multi[bg_labels], structure=footprint)
    +        inexact.append(cp.unique(padded[near_multi & ~background]))
    +
    +    # (b) labels touching a connected component of another label whose
    +    # bounding box lies strictly inside their own
    +    touching = (~background) & ((nb_max != padded) | (nb_min != padded))
    +    touching &= padded != 0
    +    if bool(touching.any()):

    Fixed in 96c68a5c; cleanup in 58415fce. Negative labels become background before narrowing or indexing. Mixed-sign and all-negative regressions pass Compute Sanitizer.

    grlee77 grlee77 commented on code on Nov 24, 2026 02:49 UTC
    Code Review
    python/cucim/src/cucim/skimage/measure/_regionprops.py:1
    @@ -1023,10 +1042,7 @@ def _props_to_dict(
                     if copy_to_host:
                         column_data = np.empty((n,) + shape, dtype=dtype)
                         for k in range(n):
    -                        rp = regions[k][prop]
    -                        if isinstance(rp, cp.ndarray):
    -                            rp = cp.asnumpy(rp)
    -                        column_data[k] = rp
    +                        column_data[k] = _to_host(regions[k][prop])
                         out[orig_prop] = column_data

    Fixed in 2e707fbb, aeba5e6b, and bb74afb1. Multichannel weighted centroids preserve both axes in split and unsplit host and device output. Device conversion stacks tuples of per-channel arrays, while scalar tuples such as bbox and centroid use their previous conversion

    grlee77 grlee77 commented on code on Nov 24, 2026 02:49 UTC
    Code Review
    python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:1
    @@ -933,6 +934,130 @@ def regionprops_num_boundary_pixels(labels, max_label=None, props_dict=None):
         return edge_counts
     
     
    +def _fill_holes_by_label(labels, max_label, bbox=None):
    +    """Fill the background holes of each labeled region.
    +
    +    A hole is a connected component of the background (with full
    +    connectivity, as for ``binary_fill_holes`` with a ``3**ndim`` structuring
    +    element) that is not connected to the area outside of the image. A hole
    +    whose neighboring pixels all belong to a single region is filled with that
    +    region's label. This matches scikit-image's per-region ``image_filled`` for
    +    that region.
    +
    +    scikit-image fills each region's holes treating all other labels as
    +    background, so a region's filled image also contains holes bordered by
    +    several regions and any regions nested in its holes. For the labels where
    +    this can happen, the returned ``label_filled`` is not exact and the labels
    +    are returned in ``labels_inexact`` so that the caller can recompute them
    +    on per-label crops. These are the labels that (a) border a hole that also
    +    borders other labels, or (b) touch a connected component of another label
    +    whose bounding box lies strictly inside their own (a component nested in
    +    a hole of another region must lie strictly inside that region's bounding
    +    box, but the other components of its label can lie anywhere, so the test
    +    uses the bounding boxes of the components, not of the labels).
    +
    +    Returns
    +    -------
    +    label_filled : cupy.ndarray
    +        The label image with each single-region hole filled with its label.
    +    labels_inexact : numpy.ndarray
    +        Labels whose filled region may differ from scikit-image's.
    +    """
    +    ndim = labels.ndim
    +    footprint = ndi.generate_binary_structure(ndim, ndim)
    +    # with the padding, all background outside of the regions is a single
    +    # connected component
    +    padded = cp.pad(labels, 1, mode="constant", constant_values=0)
    +    work_dtype = cp.int32 if max_label < 2**31 - 1 else cp.int64
    +    padded = padded.astype(work_dtype, copy=False)
    +    background = padded == 0
    +    bg_labels = label(background, connectivity=ndim)
    +    num_bg = int(bg_labels.max())
    +    outer = int(bg_labels[(0,) * ndim])
    +
    +    # largest and smallest label in the 3**ndim neighborhood of each pixel
    +    # (the background is excluded from the minimum)
    +    no_label = max_label + 1
    +    nb_max = ndi.grey_dilation(padded, size=3, mode="constant", cval=0)
    +    nb_min = ndi.grey_erosion(
    +        cp.where(background, no_label, padded).astype(work_dtype, copy=False),
    +        size=3,
    +        mode="constant",
    +        cval=no_label,
    +    )
    +
    +    # labels bordering each background component
    +    bg_ids = bg_labels[background]
    +    hole_max = cp.zeros(num_bg + 1, dtype=work_dtype)
    +    hole_min = cp.full(num_bg + 1, no_label, dtype=work_dtype)
    +    cp.maximum.at(hole_max, bg_ids, nb_max[background])
    +    cp.minimum.at(hole_min, bg_ids, nb_min[background])
    +    component_ids = cp.arange(num_bg + 1)
    +    is_hole = (component_ids != 0) & (component_ids != outer)
    +    single = is_hole & (hole_min == hole_max)
    +    multi = is_hole & (hole_min != hole_max)
    +
    +    fill_value = cp.where(single, hole_max, 0).astype(work_dtype, copy=False)
    +    filled = cp.where(background, fill_value[bg_labels], padded)
    +    core = (slice(1, -1),) * ndim
    +    label_filled = cp.ascontiguousarray(filled[core].astype(labels.dtype))
    +
    +    # (a) labels bordering a hole that borders several labels
    +    inexact = []
    +    if bool(multi.any()):
    +        near_multi = ndi.binary_dilation(multi[bg_labels], structure=footprint)
    +        inexact.append(cp.unique(padded[near_multi & ~background]))
    +
    +    # (b) labels touching a connected component of another label whose
    +    # bounding box lies strictly inside their own
    +    touching = (~background) & ((nb_max != padded) | (nb_min != padded))
    +    touching &= padded != 0
    +    if bool(touching.any()):
    +        if bbox is None:
    +            bbox, _ = regionprops_bbox_coords(labels, max_label=max_label)

    Fixed in 374513e6. Sparse labels are compacted before filling, then original IDs are restored. Tests cover IDs above 2**53 under a 256 MiB pool limit.

    grlee77 grlee77 commented on code on Nov 24, 2026 02:49 UTC
    Code Review
    python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:1
    @@ -479,8 +488,8 @@ def get_mean_var_kernel(dtype, sample_std=False):
                   var = 0.0;
                 }} else {{
                   m = static_cast<double>(sum) / count;
    -              var = sqrt(
    -                  (static_cast<double>(sumsq) - m * m * count) / count);
    +              double v = (static_cast<double>(sumsq) - m * m * count) / count;

    Fixed in 586a58d9, narrowed in 6e165c3e. Wide integers use double accumulation; bool and 8/16-bit integers retain integer accumulation below 2**32 pixels. Population/sample extreme-value tests match NumPy. Cancellation is handled separately in #1228.

    grlee77 grlee77 commented on code on Nov 24, 2026 02:50 UTC
    Code Review
    python/cucim/src/cucim/skimage/measure/_regionprops_gpu_intensity_kernels.py:1
    @@ -167,11 +170,11 @@ def _get_intensity_min_max_code(
         if compute_min:
             for c in range(num_channels):
                 source_post += f"""
    -            atomicMin(&minimums[{nc}(lab - 1) + {c}], min_vals[{nc}jj + {c}]);"""  # noqa: E501
    +            cucim_atomic_min(&minimums[{nc}(lab - 1) + {c}], min_vals[{nc}jj + {c}]);"""  # noqa: E501

    Fixed in 2b44e73b and 40672323. Both reduction stages use infinite identities for all floating dtypes. Tests cover infinite regions, finite/infinite mixtures, and absent labels.

    grlee77 grlee77 commented on code on Nov 24, 2026 02:50 UTC
    Code Review
    python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:1
    @@ -868,23 +868,44 @@ def _binary_fill_holes_non_iterative(input, structure=None, output=None):
         return output
     
     
    +def _can_use_label_for_fill_holes(structure, ndim):
    +    # In 1D the padding at opposite ends is not connected.
    +    if ndim < 2:
    +        return False

    Fixed in 8ae9bb0e. Compatible 1D inputs use connected-component filling, with both exterior components excluded. A long-vector regression verifies dilation is bypassed.

    grlee77 grlee77 commented on code on Nov 24, 2026 02:51 UTC
    Code Review
    python/cucim/src/cucim/skimage/measure/_regionprops_gpu_basic_kernels.py:1
    @@ -933,6 +934,130 @@ def regionprops_num_boundary_pixels(labels, max_label=None, props_dict=None):
         return edge_counts
     
     
    +def _fill_holes_by_label(labels, max_label, bbox=None):
    +    """Fill the background holes of each labeled region.
    +
    +    A hole is a connected component of the background (with full
    +    connectivity, as for ``binary_fill_holes`` with a ``3**ndim`` structuring
    +    element) that is not connected to the area outside of the image. A hole
    +    whose neighboring pixels all belong to a single region is filled with that
    +    region's label. This matches scikit-image's per-region ``image_filled`` for
    +    that region.
    +
    +    scikit-image fills each region's holes treating all other labels as
    +    background, so a region's filled image also contains holes bordered by
    +    several regions and any regions nested in its holes. For the labels where
    +    this can happen, the returned ``label_filled`` is not exact and the labels
    +    are returned in ``labels_inexact`` so that the caller can recompute them
    +    on per-label crops. These are the labels that (a) border a hole that also
    +    borders other labels, or (b) touch a connected component of another label
    +    whose bounding box lies strictly inside their own (a component nested in
    +    a hole of another region must lie strictly inside that region's bounding
    +    box, but the other components of its label can lie anywhere, so the test
    +    uses the bounding boxes of the components, not of the labels).
    +
    +    Returns
    +    -------
    +    label_filled : cupy.ndarray
    +        The label image with each single-region hole filled with its label.
    +    labels_inexact : numpy.ndarray
    +        Labels whose filled region may differ from scikit-image's.
    +    """
    +    ndim = labels.ndim
    +    footprint = ndi.generate_binary_structure(ndim, ndim)
    +    # with the padding, all background outside of the regions is a single
    +    # connected component
    +    padded = cp.pad(labels, 1, mode="constant", constant_values=0)
    +    work_dtype = cp.int32 if max_label < 2**31 - 1 else cp.int64
    +    padded = padded.astype(work_dtype, copy=False)
    +    background = padded == 0
    +    bg_labels = label(background, connectivity=ndim)
    +    num_bg = int(bg_labels.max())
    +    outer = int(bg_labels[(0,) * ndim])
    +
    +    # largest and smallest label in the 3**ndim neighborhood of each pixel
    +    # (the background is excluded from the minimum)
    +    no_label = max_label + 1
    +    nb_max = ndi.grey_dilation(padded, size=3, mode="constant", cval=0)
    +    nb_min = ndi.grey_erosion(
    +        cp.where(background, no_label, padded).astype(work_dtype, copy=False),
    +        size=3,
    +        mode="constant",
    +        cval=no_label,

    Fixed in 374513e6. Erosion uses nearest, allowing kernel reuse across label counts. The regression checks kernel identities; 1f9d8c5a removes its positional-argument assumption.

    grlee77 grlee77 commented on code on Nov 24, 2026 02:51 UTC
    Code Review
    python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:1
    @@ -915,7 +936,15 @@ def binary_fill_holes(
         if isinstance(origin, int):
             origin = (origin,) * len(axes)
         if all(o == 0 for o in origin) and filter_all_axes:
    -        return _binary_fill_holes_non_iterative(input, output=output)
    +        # label uses a host footprint; keep the original device footprint
    +        # for the iterative path if the non-iterative assumptions do not hold.
    +        structure_cpu = structure
    +        if isinstance(structure, cupy.ndarray):
    +            structure_cpu = cupy.asnumpy(structure)
    +        if _can_use_label_for_fill_holes(structure_cpu, input.ndim):
    +            return _binary_fill_holes_non_iterative(

    Fixed in 8ae9bb0e. Both filling paths return the supplied output array. Tests verify return identity.

    grlee77 grlee77 commented on code on Nov 24, 2026 02:51 UTC
    Code Review
    python/cucim/src/cucim/skimage/measure/_regionprops.py:1
    @@ -344,11 +349,12 @@ def __init__(
             self._ndim = label_image.ndim
             self._multichannel = multichannel
             self._spatial_axes = tuple(range(self._ndim))
    -        self._spacing = spacing if spacing is not None else (1.0,) * self._ndim
    -        if isinstance(self._spacing, cp.ndarray):
    -            self._pixel_area = cp.product(self._spacing)
    +        if spacing is None:
    +            self._spacing = (1.0,) * self._ndim
             else:
    -            self._pixel_area = math.prod(self._spacing)
    +            # a scalar means the same spacing along every axis
    +            self._spacing = _normalize_spacing(spacing, self._ndim)

    Fixed in 0a41163f. Device spacing is downloaded once before constructing regions. A 1,024-label regression verifies one transfer and correct scaled areas.

    grlee77 grlee77 commented on code on Nov 24, 2026 02:51 UTC
    Code Review
    python/cucim/src/cucim/skimage/_vendored/_ndimage_morphology.py:1
    @@ -915,7 +936,15 @@ def binary_fill_holes(
         if isinstance(origin, int):
             origin = (origin,) * len(axes)
         if all(o == 0 for o in origin) and filter_all_axes:
    -        return _binary_fill_holes_non_iterative(input, output=output)
    +        # label uses a host footprint; keep the original device footprint
    +        # for the iterative path if the non-iterative assumptions do not hold.
    +        structure_cpu = structure
    +        if isinstance(structure, cupy.ndarray):
    +            structure_cpu = cupy.asnumpy(structure)
    +        if _can_use_label_for_fill_holes(structure_cpu, input.ndim):

    Fixed in 8ae9bb0e and 4cbce3eb. Host footprints are converted before iterative filling, including nondefault origins. NumPy/list/device and in-place cases are covered.

    grlee77 grlee77 commented on code on Nov 24, 2026 02:52 UTC
    Code Review
    python/cucim/src/cucim/skimage/_vendored/tests/test_morphology.py:1
    @@ -132,3 +132,66 @@ def test_grey_axes(func, expand_axis, origin, footprint_mode, mode):
         cucim_func = getattr(ndi, func)
         cucim_func(data, output=out, axes=axes, **kwargs)
         cp.testing.assert_array_almost_equal(out, expected)
    +
    +
    +@pytest.mark.parametrize("ndim", [2, 3])
    +@pytest.mark.parametrize("connectivity", [1, 2, 3])
    +def test_binary_fill_holes_structure(ndim, connectivity):
    +    # the non-iterative algorithm (used with the default origin and axes)
    +    # must also use the structuring element
    +    if connectivity > ndim:
    +        pytest.skip("connectivity > ndim")
    +    rng = np.random.default_rng(5)
    +    shape = (64, 64) if ndim == 2 else (16, 16, 16)
    +    data = rng.random(shape) > 0.35
    +    struct = ndi_cpu.generate_binary_structure(ndim, connectivity)
    +    expected = ndi_cpu.binary_fill_holes(data, struct)
    +    # the structuring element changes which background pixels are holes
    +    default = ndi_cpu.binary_fill_holes(data)
    +    assert np.array_equal(expected, default) == (connectivity == 1)
    +    out = ndi.binary_fill_holes(cp.asarray(data), cp.asarray(struct))
    +    cp.testing.assert_array_equal(out, expected)
    +
    +
    +@pytest.mark.parametrize("ndim", [2, 3])
    +@pytest.mark.parametrize(
    +    "footprint", ["horizontal", "large", "asymmetric", "diagonal"]
    +)
    +@pytest.mark.parametrize("empty", [False, True])
    +@pytest.mark.parametrize("inplace", [False, True])
    +def test_binary_fill_holes_iterative_structure(ndim, footprint, empty, inplace):
    +    if footprint == "horizontal":
    +        struct = np.zeros((3,) * ndim, dtype=bool)
    +        struct[(1,) * (ndim - 1) + (slice(None),)] = True
    +    elif footprint == "large":
    +        struct = np.ones((5,) * ndim, dtype=bool)
    +    elif footprint == "asymmetric":
    +        struct = np.ones((3,) * ndim, dtype=bool)
    +        struct[(0,) * ndim] = False
    +    else:
    +        struct = np.zeros((3,) * ndim, dtype=bool)
    +        for index in range(3):
    +            struct[(index,) * ndim] = True
    +
    +    data = np.zeros((9,) * ndim, dtype=bool)
    +    if not empty:
    +        data[(slice(1, -1),) * ndim] = True
    +        data[(slice(3, -3),) * ndim] = False

    Fixed in 8ae9bb0e. Nonempty fixtures explicitly produce different results with the requested footprint versus the default, so ignoring the footprint fails the test.

    grlee77 grlee77 commented on Nov 24, 2026 02:52 UTC
    Author

    Thanks, @gigony. Pushed several new commits addressing the remaining issues identified during review.

    grlee77 grlee77 commented on Nov 24, 2026 03:29 UTC
    Author

    /merge

    Reviewers
    Assignees
    grlee77 grlee77
    Labels
    risk: low confidence: 88.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 60.6% (MEDIUM) · Higher = larger blast radius
    60.6%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 88.8% · Lower = rushed or shallow review
    88.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6.8% · Safe to merge
    6.8%
    Repository