【发布时间】:2017-02-10 12:42:52
【问题描述】:
有没有一种 numpythonic 方法可以做到这一点?原始数组的维度为N x M x 3,我想制作一个N x M 掩码,如图所示。我认为有一种简单的方法可以用 Numpy 编写此代码,但我的大脑冻结了。
虽然可能有其他方法可以实现这一点,但我正在尝试以这种方式来保持我使用 Numpy 索引的技能。
这失败了,因为img2[test] 失去了原来的形状。我是否必须以某种方式.reshape(),还是有更简单的方法不需要明确重申轴的尺寸?
import numpy as np
import matplotlib.pyplot as plt
img = np.random.random(100*100*3).reshape(100, 100, -1)
img2 = img.copy()
target = np.array([0.5, 0.3, 0.7])
test = np.abs(img - target) < 0.5
img2[test] = np.zeros(3) # probem, img2[test] looses its shape
plt.figure()
plt.imshow(np.hstack((img, img2)))
plt.show()
File "/Users/yournamehere/Documents/fishing/Eu;er diagram/stackexchange question v00.py", line 12, in <module>
img2[test] = target
ValueError: NumPy boolean array indexing assignment cannot assign 3 input values to the 11918 output values where the mask is true
【问题讨论】: