Extract Center of masses from binary LabelMapVolume and convert to Fiducials?

Hi Slicer developers

I have a binary labelMapVolume (512x512x173). It contains a large number of regions almost circular (approximately each area of about 20 pixels) at its axial sections.

I have two questions:
1- How can I determine the center of masses these regions as a pixel, separately?
2- How can I convert these center of masses to fiducials?

Please guide me,
Thanks a lot.
Shahrokh

You can use Islands effect to split the segment so that each island is put in a separate segment. You can then use numpy or VTK or SimpleITK to compute center of gravity.

You may also find SimpleITK or vtkITK label filters to get island properties directly from the original (non-split) labelmap image.

@shahrokh as you find a good working solutions for your questions please post them so others can benefit.

Hi everyone!
I have same problem as @shahrokh and I´ve explore @lassoan solutions.

For center of mass by numpy, I´ve found something like:

def center_of_mass(array: np.ndarray):
    total = array.sum()
    # alternatively with np.arange as well
    x_coord = (array.sum(axis=1) @ range(array.shape[0])) / total
    y_coord = (array.sum(axis=0) @ range(array.shape[1])) / total
    return x_coord, y_coord

What I really have trouble with is the way to access labels inside labelmap…

labelmapNode = slicer.util.loadLabelVolume(mask_file_path)
labelmapArray = slicer.util.arrayFromVolume(labelmapNode)
secondLabelVoxels = labelmapArray[labelmapArray==1]
print(center_of_mass(secondLabelVoxels ))

Print result:

(nan, nan)

I´ll appreciate some help with this…
Thanks in advance!

Your probably get NaN site to division by zero. Make sure your never attempt to divide by total if the value is zero.

Similar questions have come up several times since this topic was created 5 years ago. Please search a bit in this forum (the built-in search in discourse is not that great, so you may have better luck with Google or Bing Chat). If you ask here or at other related topics then make sure you describe what you want to achieve, because center of a segment can be interpreted in many different ways (e.g., do you need a center point that is inside the segment?).