Reputation: 161
I have a numpy pixel array (either 0 or 255), using .where I pull the tuples of where it is > 0. I now want to use those tuples to add 1 to a separate 2D numpy array. Is the best way to just use a for loop as shown below or is there a better numpy-like way?
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
Upvotes: 1
Views: 247
Reputation: 280301
movearray[imageasarray.T > 0] += 1
where
is redundant. You can index an array with a boolean mask, like that produced by imageasarray.T > 0
, to select all array cells where the mask has a True. The +=
then adds 1 to all those cells. Finally, the T
is a transpose, since it looks like you're switching the indices around when you increment the cells of movearray
.
Upvotes: 1