[英]Slicing arrays with meshgrid/array indices in Numpy
I have the following code: 我有以下代码:
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])
I get this error: 我收到此错误:
z = np.sum(img * big_k[height-rr:2*height-rr, width-pp:2*width-pp])
IndexError: invalid slice
I understand this error and why it has happened. 我了解此错误以及发生原因。 The problem is you can't slice arrays with arrays of indices.
问题是您无法使用索引数组对数组进行切片。 The thing is, using meshgrid is a fabulous way to speed things up & get rid of the nested loops in my code (otherwise I would have to iterate over
angularSlices * radialSlices
). 事实是,使用meshgrid是加快速度并摆脱代码中嵌套循环的绝佳方法(否则,我将不得不遍历
angularSlices * radialSlices
)。 Is there a way I can use meshgrid
to slice big_k
? 有什么办法可以使用
meshgrid
切片big_k
吗?
You need to broadcast the index yourself, for example: 您需要自己广播索引,例如:
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
the image looks like: 图像看起来像:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.