[英]Find distance between all pairs of pixels in an image
I have a numpy.array
of shape (H, W)
, storing pixel intensities of an image.我有一个形状为
(H, W)
的numpy.array
,用于存储图像的像素强度。 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).我想生成一个新的形状数组
(H, W, H, W)
,它存储图像中每对像素之间的欧几里德距离(像素之间的“空间”距离;而不是它们的强度差异)。
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 )
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.
上面更简单问题的解决方案可能足以让我弄清楚其余的问题。
numpy.array
of shape (H, W, D)
).(H, W, D)
的numpy.array
)。We can setup open grids with 1D
ranged arrays using np.ogrid
, which could be operated upon in the same iterator notation for a vectorized solution and this will leverage broadcasting
for the perf.我们可以使用
np.ogrid
设置具有1D
范围数组的开放网格,它可以在矢量化解决方案的相同迭代器符号中进行操作,这将利用broadcasting
进行性能。 boost :促进 :
X1,Y1,X2,Y2 = np.ogrid[:H,:W,:H,:W]
d_out = numpy.sqrt( (X2-X1)**2 + (Y2-Y1)**2 )
To save on two open grids :要保存在两个开放网格上:
X,Y = np.ogrid[:H,:W]
d_out = numpy.sqrt( (X[:,:,None,None]-X)**2 + (Y[:,:,None,None]-Y)**2 )
If we are working with large arrays, consider using numexpr
for further boost :如果我们正在处理大型数组,请考虑使用
numexpr
进一步提升:
import numexpr as ne
d_out = ne.evaluate('sqrt( (X2-X1)**2 + (Y2-Y1)**2 )')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.