简体   繁体   English

一个数组中的 Select 值使用 numpy 中另一个数组的值

[英]Select values from one array using values of another array in numpy

In numpy, I have a 3D array.在 numpy 中,我有一个 3D 阵列。 Along the 0 axis, it stores multiple 2D planes.沿 0 轴,它存储多个 2D 平面。 I need to get the gradient of each of these planes, select the median gradient magnitude at each point across these planes, and hence isolate the corresponding x and y gradient components.我需要获得这些平面中每个平面的梯度,select 这些平面上每个点的中值梯度幅度,从而隔离相应的 x 和 y 梯度分量。 But I'm having difficulty carrying this out properly.但是我很难正确执行此操作。

So far, to get the gradient and median, I have:到目前为止,要获得梯度和中位数,我有:

img_l = #My 3D array of 2D planes
grad = np.gradient(img_l,axis=[1,2]) #Get gradient of each image. This is a list with 2 elements.
mag_grad = np.sqrt(grad[0]**2 + grad[1]**2) #Get magnitude of gradient in each case
med = np.median(mag_grad, axis=0) #Get median value at each point in the planes

Then to select the correct x & y components of the gradient, I use:然后到 select 梯度的正确 x & y 分量,我使用:

pos=(mag_grad==med).argmax(axis=0) #This returns the first instance where the median element encountered along axis=0
G = np.stack([np.zeros(med.shape),np.zeros(med.shape)], axis=0) #Will store y and x median components of the gradient, respectively.
for i in range(med.shape[0]):
    for j in range(med.shape[1]):
        G[0,i,j], G[1,i,j] = grad[0][pos[i,j],i,j], grad[1][pos[i,j],i,j] #Manually select the median y and x components of the gradient, and save to G.

I believe the 2nd code block works correctly.我相信第二个代码块可以正常工作。 However, it is very inelegant, and because I couldn't find a way to do this in NumPy, I had to use a Python loop which adds a large amount of overhead.但是,它非常不优雅,并且因为我在 NumPy 中找不到执行此操作的方法,所以我不得不使用 Python 循环,这会增加大量开销。 In addition, since this operation occurs frequently in NumPy, I suspect there should be an in-built way to do this.另外,由于这个操作在 NumPy 中经常发生,我怀疑应该有一个内置的方法来做到这一点。

How can I implement this code more effectively and elegantly?我怎样才能更有效、更优雅地实现这段代码?

Using itertools to index your array can make it more efficient/elegant.使用 itertools 索引您的数组可以使其更高效/优雅。

import itertools

idxs = np.array(list(itertools.product(range(med.shape[0]), range(med.shape[1]))))
G[0,idxs], G[1,idxs] = grad[0][pos[idxs],idxs], grad[1][pos[idxs],idxs]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM