0

Is there a numpythonic way to do this? Original array is of dimension N x M x 3, I'd like to make a N x M mask as shown. I thought there was a simple way to write this with Numpy but I'm having brain freeze.

While there may be alternative ways to implement this, I'm trying to do it this way to maintain my skills at using Numpy indexing.

This fails because img2[test] looses the original shape. Do I have to .reshape() somehow, or is there simpler way where I don't need to explicitly restate the dimensions of the axes?

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

2 Answers 2

1

Here's a one-liner showcasing the very useful keepdims kwarg

np.where(np.logical_and.reduce(test, axis=-1, keepdims=True), [0, 0, 0], img)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the mini numpyphany! It isn't every day one can learn several new things from a one-line answer.
@uhoh Thanks! Glad you're enjoying it.
0

Brain has un-frozen. Forgot to use .all() to collape the test to a single boolean value for each N x M location. Once that is corrected, Numpy does it's thing very nicely.

enter image description here

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).all(axis=-1)

img2[test] = np.zeros(3)  # probem, img2[test] looses its shape

plt.figure()
plt.imshow(np.hstack((img, img2)))
plt.show()

Comments

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.