Home > database >  Creating a Cylindrical Mask of a 3D Image using Numpy
Creating a Cylindrical Mask of a 3D Image using Numpy

Time:01-11

I attempting to create cylindrical mask for a 3D image in order to remove the green circle seen around the image.

With the script I have written I am able to mask the image but I am cutting out a large portion of the image in the end. I want to create a mask that does not lose the central image but removes the circle.

I think the issue is that the mask I am generating is too small, would the solution be to adjust the size of meshgrid object I made with np.linspace?

image,header = nrrd.read(image) #load image 


s = image.shape

x = np.linspace(-100, 100, s[0])
y = np.linspace(-100, 100, s[1])
z = np.linspace(-100, 100, s[2])
x,y,z = np.meshgrid(x,y,z) # Meshgrid based on image size 

mask = (x)**2   (y)**2 <= (z)**2 # Cylindrical mask to remove circle 
print("masked")

maskimg = plt.imshow(mask[:,:,400],cmap="gray")
plt.show()
z_masked = np.multiply(mask,image) # Apply mask to image 
zimg_masked = plt.imshow(z_masked[:,:,400])
plt.show()

Image of object I am trying to mask

Result from my current script, the image appears to be cutoff losing a lot of vital information.

CodePudding user response:

image,header = nrrd.read(image)

s = image.shape

mask = np.zeros_like(image,dtype=bool)
center = (s[1] // 2, s[0] // 2, s[2] // 2)
radius = 900  # radius in pixels

x, y, z = np.meshgrid(np.arange(mask.shape[1]), np.arange(mask.shape[0]), np.arange(mask.shape[2]))
mask = (x - center[2])**2   (y - center[1])**2   (z - center[0])**2 <= radius**2
masked_image = image * mask
plt.imshow(masked_image[:,:,400]);plt.show()

This seems to do what I want. I have added lines of code that automatically creates the mask at the center of the image. I also included a variable that will add a radius that can be defined across the whole image.

  • Related