Given the sphere center coordinates and radius and the image in 3D how to get all pixels within the sphere using numpy in python ?
Assuming for the 3D image we have indicesX, indicesY, indicesZ
arrays containing the pixels coordinates over X,Y and Z axis, centerX, centerY, centerZ
contains the coordinates of center for the sphere and r
is the radius.
Asked
Active
Viewed 120 times
2
-
Is `centerX`, `centerY`, and `centerZ` in pixel coordinates? – Roy Smart Jan 28 '23 at 23:55
-
What is the shape of indicesX, indicesY and indicesZ ? Also what is the order of indices in your 3d image ? – MSS Jan 29 '23 at 02:48
-
https://stackoverflow.com/questions/41656006/how-to-rasterize-a-sphere/41666156#41666156 – Matt Timmermans Jan 29 '23 at 02:52
-
@RoySmart yes, they are in pixels – Mary Jan 29 '23 at 07:11
-
@MSS all are the same, each of them is (255, 255, 170) – Mary Jan 29 '23 at 07:12
1 Answers
1
One way you could do this is to construct a boolean mask using the equation for a sphere
mask = (np.square(indicesX - centerX) + np.square(indicesY - centerY) + np.square(indicesZ - centerZ)) <= np.square(r)
indicesX_in_sphere = indicesX[mask]
indicesY_in_sphere = indicesY[mask]
indicesZ_in_sphere = indicesZ[mask]
or you could use the mask directly on the values of the 3D image depending on your needs.
-
Thank you so much, I have one more question, what you mena by using the mask directly on the values of the 3D image ? – Mary Jan 30 '23 at 11:39
-
Well, I'm not sure what you're trying to do with this 3D image, but say you wanted to sum up all the pixels in the image, for example. You could do `np.sum(image[mask])` instead of `np.sum(image[indicesX_in_sphere, indicesY_in_sphere, indicesZ_in_sphere])`. – Roy Smart Jan 30 '23 at 15:41
-
Thank you, in the end I need to calculate the median of the intensity of all pixels within the sphere – Mary Jan 31 '23 at 17:03
-
Is it correct to do like this ? `np.median(image[mask] > t)` if I need the median of all pixels with the intensity greater than a value `t` ? – Mary Jan 31 '23 at 18:39
-
You need to create a new mask and use [logical and](https://numpy.org/doc/stable/reference/generated/numpy.logical_and.html) with the original mask to isolate that quantity. `np.median(image[mask & (image > t)])` – Roy Smart Jan 31 '23 at 18:43
-