2

I have a 3D array (x, y, RGBA) and my goal is :

find which pixels are blank RGBA=[0,0,0,0] then change their color to blue, and for other pixels change color to green.

As far as i see it it can be done in 2 steps :

1- create a 500x500 array with bool True if pixel has value, False if blank

2- then apply a function to replace True by [0,0,255,255] and False by [0,255,0, 255]

after numerous searches (i'm not a python wizard) I managed to achieve 1- in a pythonic way (at least my hope...)

img.shape
>(500, 500, 4)
img_bool = np.equal(img[:,:], [0, 0, 0, 0]).all(axis=2)
img_bool.shape
>(500, 500)

my guess for step 2 was trying such syntax:

img_final = np.where(img_bool, [0,0,255,255], [0,255,0,255])

or

np.choose(img_bool, [[0,0,255,255],[0,255,0,255], out=img_final)

but they give same error (quite logical since both expressions might do the same in fact)

ValueError: shape mismatch: objects cannot be breascast to a single shape

in fact step 2 could be summerized by "how to replace a scalar/boolean by an array/vector in numpy.ndarray ?"

1 Answer 1

1

For your first task, using the fact that colors are positive integers, you can use

img_bool = img.sum(axis=2)>0

The second you can do with

img[img_bool] = [0, 0, 255, 255]
img[~img_bool] = [0, 255, 0, 255]

Note, that if I get your description right, you'll original expression returns inverse, i.e. you have to change it to

img_bool = ~np.equal(img[:,:], [0, 0, 0, 0]).all(axis=2)
Sign up to request clarification or add additional context in comments.

2 Comments

very neat syntax. thx, all your answers work perfectly. just one remark : img.sum(axis=2)>0 could return True if pixel array was [0, -15, 15, 0] no ? but in my case it works perfectly since all values are positives. thx again.
@comte yes, it can, I added clarification. I judged from values equal to 255, that your colors are ideed positive.

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.