在Numpy中使用meshgrid/array索引对数组进行切片

2024-10-03 00:31:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

    big_k = gabor((height * 2, width *2), (height, width)) #Returns a 2d-array
    r = np.arange(0, radialSlices, radialWidth)
    p = np.arange(0, angularSlices, angularWidth)
    pp, rr = np.meshgrid(p, r, sparse=False)
    z = np.sum(img * big_k[height-rr:2*height-rr, width-pp:2*width-pp])

我得到这个错误:

^{pr2}$

我理解这个错误以及为什么会发生。问题是不能用索引数组对数组进行切片。问题是,使用meshgrid是一种非常好的方法来加快速度并消除代码中的嵌套循环(否则我将不得不迭代angularSlices * radialSlices)。有没有办法可以用meshgrid来切片big_k?在


Tags: 代码错误nprrgabor切片数组width
1条回答
网友
1楼 · 发布于 2024-10-03 00:31:03

您需要自己广播索引,例如:

a = np.zeros((200, 300))

yy, xx = np.meshgrid([10, 40, 90], [30, 60])
hh, ww = np.meshgrid(np.arange(5), np.arange(8))

YY = yy[..., None, None] + hh[None, None, ...]
XX = xx[..., None, None] + ww[None, None, ...]

a[YY, XX] = 1

图像看起来像:

enter image description here

相关问题 更多 >