Search code examples
pythonnumpyimage-processingscikit-image

Extract spherical region in image at a certain position (with skimage et al.)


I have (a bunch of 3D) stacks of tomographic data, in those I have deduced a certain (3D) coordinate around which I need to cut out a spherical region.

My code produces me the following image which gives an overview of what I do. I calculate the orange and green points, based on the dashed white and dashed green region. Around the midpoint of these, I'd like to cut out a spherical region, the representation of it is now marked with a circle in the image (also drawn by my code).

Screenshot out of my Jupyter notebook

Constructing a sphere with skimage.morphology.ball and multiplying this with the original image is easy to do, but how can I set the center of the sphere at the desired 3D location in the image? The ~30 3D stacks of images are all of different size with different regions, but I have all the necessary coordinates ready for further use.


Solution

    1. you have some radius r and an index (i,j,k) into the data.

    2. kernel = skimage.morphology.ball(r) returns a mask/kernel which is a = 2*r + 1 along each side. It's cube-shaped.

    3. Take a cube-shaped slice, the size of your kernel, out of the tomograph. Starting indices depend on where you need the center to be and what radius the kernel has.

      piece = data[i-r:i-r+a, j-r:j-r+a, k-r:k-r+a]

    4. Apply the binary "ball" mask/kernel to the slice.

      piece *= kernel