我有一个 numpy 像素数组(0 或 255),使用 .where 提取它 > 0 的元组。我现在想使用这些元组将 1 添加到单独的 2D numpy 数组中。如下所示,最好的方法是使用 for 循环,还是有更好的类似 numpy 的方法?
changedtuples = np.where(imageasarray > 0)
#If there's too much movement change nothing.
if frame_size[0]*frame_size[1]/2 < changedtuples[0].size:
print "No change- too much movement."
elif changedtuples[0].size == 0:
print "No movement detected."
else:
for x in xrange(changedtuples[0].size):
movearray[changedtuples[1][x],changedtuples[0][x]] = movearray[changedtuples[1][x],changedtuples[0][x]]+1
最佳答案
movearray[imageasarray.T > 0] += 1
其中
是多余的。您可以使用 bool 掩码对数组进行索引,例如由 imageasarray.T > 0
生成的数组,以选择掩码为 True 的所有数组单元格。然后,+=
将所有这些单元格加 1。最后,T
是一个转置,因为当您增加 movearray
的单元格时,看起来您正在切换索引。
关于python - 在 Python 中修改 Numpy 数组(元组定义)部分的更快/更好的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25102013/