title: How to speed up dilating a 3D region in a boolean numpy array?
body: <p>I have a 3D numpy array boolean mask which has been segmented from a MRI brain volume.<br>
  Brain voxels = True. Everything else = False.</p>
  
  <p>What I would like to do is to enlarge this mask such that it would encompass the surrounding tissues in the MRI volume, not just the segmented organ, perhaps a 10mm rind of non-brain all around the brain.</p>
  
  <p>I tried using a 2D dilation using the skimage.morphology.dilation with a diamond filter.  While this is nice and fast for a single image, I need to repeat this in multiple slices through the volume and in at least 2 planes to come even close to uniformly dilating the 3D mask.</p>
  
  <p>I largely took my code from here: <a href="https://scipy-lectures.org/packages/scikit-image/index.html" rel="nofollow noreferrer">https://scipy-lectures.org/packages/scikit-image/index.html</a></p>
  
  <p>typical volume shape = 512, 512, 270</p>
  
  <pre><code># 1st pass in axial plane
  (x, y, z) = np.shape(3dMask)
  for slice_number in range(z):
      image_slice = 3dMask[:, :, slice_number]
      3dMask[:, :, slice_number] = morphology.binary_dilation(image_slice, morphology.diamond(30))
  # repeat in coronal plane...
  </code></pre>
  
  <p>This works very nicely with the desired effect in each slice, but is very slow for 3D.
  I can speed things up by only dilating those slices containing at least one 'True', but that inevitably leaves 100+ slices in each plane. Still slow.</p>
  
  <p>In the hope that the python side looping is slowing everything down, I have looked for a 3D equivalent single function in numpy and skimage but have found nothing that I can recognise as useful.</p>
  
  <p>I toyed with the idea of finding the geometric centre and simply zooming the volume by 5%, but there will necessarily be holes in the mask (the space in-between the 2 halves of the brain) which will no longer match up with the MRI volume and so is of no use...</p>
  
  <p>I assume this means that I am doing it wrong as I am new to both numpy and skimage.</p>
  
  <p>Is there a fast way to do this? Perhaps a 3D alternative to the 2D skimage dilation?</p>