I have a 512^3 boolean array. I am currently calculating a distance transform using scipy.ndimage.distance_transform_edt. The calculation is taking quite a while (tens of seconds). I only need to know the distances for a small set of pixels (a few hundred or thousand) in the image.
Is there any way that I can speed up the calculation by only calculating the distance transform for those pixels, leaving the rest to be zeros? Note that the "shapes" of the regions for both the array and the mask are not regular in any way.
Here's an example with a small 2D array:
import numpy as np
from scipy import ndimage
np.set_printoptions(precision=3)
n = 10
x = np.zeros((n,n),dtype=bool)
x[2:6,2:4] = True
x[1:4,3:7] = True
mask = np.zeros_like(x)
mask[7:9,6:9] = True
mask[8,4:9] = True
print(x*1)
# [[0 0 0 0 0 0 0 0 0 0]
# [0 0 0 1 1 1 1 0 0 0]
# [0 0 1 1 1 1 1 0 0 0]
# [0 0 1 1 1 1 1 0 0 0]
# [0 0 1 1 0 0 0 0 0 0]
# [0 0 1 1 0 0 0 0 0 0]
# [0 0 0 0 0 0 0 0 0 0]
# [0 0 0 0 0 0 0 0 0 0]
# [0 0 0 0 0 0 0 0 0 0]
# [0 0 0 0 0 0 0 0 0 0]]
print(mask*1)
# [[0 0 0 0 0 0 0 0 0 0]
# [0 0 0 0 0 0 0 0 0 0]
# [0 0 0 0 0 0 0 0 0 0]
# [0 0 0 0 0 0 0 0 0 0]
# [0 0 0 0 0 0 0 0 0 0]
# [0 0 0 0 0 0 0 0 0 0]
# [0 0 0 0 0 0 0 0 0 0]
# [0 0 0 0 0 0 1 1 1 0]
# [0 0 0 0 1 1 1 1 1 0]
# [0 0 0 0 0 0 0 0 0 0]]
dist = ndimage.distance_transform_edt(~x)
print(dist)
# [[2.828 2.236 1.414 1. 1. 1. 1. 1.414 2.236 3.162]
# [2.236 1.414 1. 0. 0. 0. 0. 1. 2. 3. ]
# [2. 1. 0. 0. 0. 0. 0. 1. 2. 3. ]
# [2. 1. 0. 0. 0. 0. 0. 1. 2. 3. ]
# [2. 1. 0. 0. 1. 1. 1. 1.414 2.236 3.162]
# [2. 1. 0. 0. 1. 2. 2. 2.236 2.828 3.606]
# [2.236 1.414 1. 1. 1.414 2.236 3. 3.162 3.606 4.243]
# [2.828 2.236 2. 2. 2.236 2.828 3.606 4.123 4.472 5. ]
# [3.606 3.162 3. 3. 3.162 3.606 4.243 5. 5.385 5.831]
# [4.472 4.123 4. 4. 4.123 4.472 5. 5.657 6.325 6.708]]
#desired output without having to calculate full dist array
#by only calculating at the mask locations
print(dist*mask)
# [[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]
# [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]
# [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]
# [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]
# [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]
# [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]
# [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]
# [0. 0. 0. 0. 0. 0. 3.606 4.123 4.472 0. ]
# [0. 0. 0. 0. 3.162 3.606 4.243 5. 5.385 0. ]
# [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]]