1

I have two 2D-numpy arrays of equal shape, one containing data, and one of type 'ubyte' storing bitflags per pixel. I want to visit every pixel in the data-array that has a particular flag in the bitflags-array.

I could just iterate over every pixel in either array and use the multi-index to get the bitflags and the value of the pixel, e.g.

it = np.nditer(array, flags=['multi_index'])
while not it.finished:
    if bitflags[it.multi_index] & FLAG:
        do_something(array[it.multi_index])
    it.iternext()

Since most pixels do not have the corresponding bitflag set, I would rather like to find all pixels with the given bitflag (for example using numpy.where(bitflags & FLAG) and iterate only over these pixels - something like

pixels = np.where(bitflags & FLAG)
for pixel in array[pixels]:
    do_something()

Is there a way I can still get the indices of the original array to use them in do_something()?

1 Answer 1

1

Not completely sure if I understand your question correctly, but are you looking for this:

pixels, = np.where(bitflags & FLAG)
for i, pixel in zip(pixels, array[pixels]):
    do_something(i, pixel)
Sign up to request clarification or add additional context in comments.

1 Comment

Such an easy solution! Thank you! Since my arrays are two-dimensional, len(pixels) is 2, so your code does not work directly, but I can get the actual indices using p,y,x in zip(array[pixels], *pixels) I totally missed this, since I rarely need zip

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.