我有一个3D ndarray ( X )表示的卷,它的值在0和255之间,还有另一个3D ndarray ( Y ),它是第一个数组的任意掩码,值为0或1。
我想找出一个随机样本的50个体素,在X中大于零,在‘图像’,等于1在Y,‘面具’。
我在R方面的经验如下:
idx <- sample(which(X>0 & Y==1), 50)也许R的优点是我可以对3D数组进行线性索引,因为在numpy中只使用一个索引就可以得到一个2D矩阵。
我想它可能涉及到numpy.random.choice,但似乎我不能有条件地使用它,更不用说在两个不同的数组上设置条件了。还有别的方法我应该用吗?
发布于 2017-12-07 21:05:00
有一种方法-
N = 50 # number of samples needed (50 for your actual case)
# Get mask based on conditionals
mask = (X>0) & (Y==1)
# Get corresponding linear indices (easier to random sample in next step)
idx = np.flatnonzero(mask)
# Get random sample
rand_idx = np.random.choice(idx, N)
# Format into three columnar output (each col for each dim/axis)
out = np.c_[np.unravel_index(rand_idx, X.shape)]如果您需要没有替换的随机示例,可以使用np.random.choice()和可选的arg replace=False。
样本运行-
In [34]: np.random.seed(0)
...: X = np.random.randint(0,4,(2,3,4))
...: Y = np.random.randint(0,2,(2,3,4))
In [35]: N = 5 # number of samples needed (50 for your actual case)
...: mask = (X>0) & (Y==1)
...: idx = np.flatnonzero(mask)
...: rand_idx = np.random.choice(idx, N)
...: out = np.c_[np.unravel_index(rand_idx, X.shape)]
In [37]: mask
Out[37]:
array([[[False, True, True, False],
[ True, False, True, False],
[ True, False, True, True]],
[[False, True, True, False],
[False, False, False, True],
[ True, True, True, True]]], dtype=bool)
In [38]: out
Out[38]:
array([[1, 0, 1],
[0, 0, 1],
[0, 0, 2],
[1, 1, 3],
[1, 1, 3]])将输出out与True值在mask中的位置关联起来,以进行快速验证。
如果你不想为了得到线性指数而变平,直接得到每个暗/轴的指数,我们可以这样做-
i0,i1,i2 = np.where(mask)
rand_idx = np.random.choice(len(i0), N)
out = np.c_[i0,i1,i2][rand_idx]为了提高性能,首先索引,然后在最后一步与np.c_连接-
out = np.c_[i0[rand_idx], i1[rand_idx], i2[rand_idx]]https://stackoverflow.com/questions/47703598
复制相似问题