2

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.

MSS
  • 3,306
  • 1
  • 19
  • 50
Mary
  • 103
  • 2
  • 11

1 Answers1

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.

MSS
  • 3,306
  • 1
  • 19
  • 50
Roy Smart
  • 664
  • 4
  • 12
  • 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
  • I understand, now it is clear to me. Thank you very very much! – Mary Jan 31 '23 at 19:45