在Numpy中使用meshgrid/数组索引切片数组

2 投票
1 回答
1459 浏览
提问于 2025-04-18 09:06

我有以下这段代码:

    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])

我遇到了这个错误:

    z = np.sum(img * big_k[height-rr:2*height-rr, width-pp:2*width-pp])
IndexError: invalid slice

我明白这个错误是怎么回事。问题在于,你不能用索引数组来切割数组。其实,使用meshgrid是一种很棒的方法,可以加快速度并且避免我代码中的嵌套循环(否则我得遍历angularSlices * radialSlices)。有没有办法让我用meshgrid来切割big_k呢?

1 个回答

0

你需要自己广播这个索引,比如:

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

这个图片看起来是这样的:

在这里输入图片描述

撰写回答