Skip to content

BUG: label_image_centroids returned transposed, misplaced centroids - #964

Open
Srizdebnath wants to merge 1 commit into
ANTsX:mainfrom
Srizdebnath:fix/label-image-centroids
Open

Srizdebnath wants to merge 1 commit into
ANTsX:mainfrom
Srizdebnath:fix/label-image-centroids

Conversation

@Srizdebnath

Copy link
Copy Markdown

label_image_centroids returns wrong centroids for any image:

import ants, numpy as np
arr = np.zeros((10, 12, 14), dtype="float32")
arr[1:3, 2:5, 9:12] = 1     # centroid (1.5, 3, 10)
arr[6:9, 8:11, 0:2] = 2     # centroid (7, 9, 0.5)
img = ants.from_numpy(arr)

print(ants.label_image_centroids(img)["vertices"])
# [[4.56 5.94 1.5 ]
#  [4.72 5.78 9.  ]]
print(ants.label_stats(img, img)[["x", "y", "z"]][1:].to_numpy())
# [[ 1.5  3.  10. ]
#  [ 7.   9.   0.5]]

The coordinate arrays are built with x varying fastest (Fortran order), but the label mask is labels.flatten(), which is C order. So the mask selects coordinates of unrelated voxels. On top of that, zcoords repeats np.arange(d[1]) instead of np.arange(d[2]), which only goes unnoticed when d[1] == d[2].

For 2x2x2 images like the ones in the docstring and the test, the result is the true centroid with the axes reversed. The existing test asserted those reversed values: label 5 sits at numpy index [1, 1, 0] and the test expected [0, 1, 1].

Changes:

  • Voxel coordinates now come from np.argwhere(labels == label), so they are in the same order as image.numpy(), the same convention label_stats uses.
  • physical=True was documented but ignored; the conversion was commented out. It now maps the centroids with the image's origin, spacing and direction.
  • The 3-D-only check is gone, since nothing in the computation depends on the dimension, so 2-D and 4-D label images work.
  • The docstring said vertices is a DataFrame; it is an ndarray.

Tests:

  • The existing test's expected values are corrected.
  • A new test compares against label_stats on a 10x12x14 image, in index space and in physical space with non-unit spacing, an origin and a flipped direction.
  • A new 2-D test.

These fail on main and pass here.

The coordinate arrays were built with x varying fastest but matched
against labels.flatten(), which is C order, so every centroid was
computed from the wrong voxels. The z coordinates were also built from
d[1] instead of d[2]. The existing test encoded the transposed output.

Take voxel indices from np.argwhere so they line up with
image.numpy(), support any image dimension, and honor physical=True,
which was documented but ignored.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant