Question
I have a numpy.array of shape (H, W), storing pixel intensities of an image. I want to generate a new array of shape (H, W, H, W), which stores the Euclidean distance between each pair of pixels in the image (the "spatial" distance between the pixels; not the difference in their intensities).
Solution attempt
The following method does exactly what I want, but very slowly. I'm looking for a fast way to do this.
d = numpy.zeros((H, W, H, W)) # array to store distances.
for x1 in range(H):
for y1 in range(W):
for x2 in range(H):
for y2 in range(W):
d[x1, y1, x2, y2] = numpy.sqrt( (x2-x1)**2 + (y2-y1)**2 )
Extra details
Here are more details for my problem. A solution to the simpler problem above would probably be enough for me to figure out the rest.
- In my case, the image is actually a 3D medical image (i.e. a
numpy.arrayof shape(H, W, D)). - The 3D pixels might not be cubic (e.g. each pixel might represent a volume of 1mm x 2mm x 3mm).