1

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

1 Answer 1

1
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.

Sign up to request clarification or add additional context in comments.

2 Comments

That's perfect, thanks. If I remove the where I can still check for no movement with all but how do I check the first condition, if over 50% (or whatever threshold) is greater than 0 to disregard the movement?
@DTC: Save the mask, so you don't have to compute it twice (mask = imageasarray.T > 0). Then, mask.sum() is the number of True entries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.