1

I am new to numpy and I want to replace specefic elements in a 3D numpy array. My 3D numpy array represents an image. The shape of the array is: (1080, 1920, 3). The number 3 represents RGB of each pixel in the image.

All I want to know is how to change all the elements that are equal to [0,0,0] into [255,255,255] Which means i want all black pixels in the image to be white.. How can i do it? Thanks!

1 Answer 1

1

Say you have stored your array in data; this should work:

data[(data == 0).all(axis=2)] = [255, 255, 255]

This is due to numpy's broadcasting rules, which compare each value to 0, resulting in a boolean array with True values where they compare equal and False elsewhere.

The next step is to take only those sub-arrays where all of the individual values do compare equal, with .all(axis=2) - the last axis, which is the one you want.

Then, with the resulting boolean array, you can index back into data, which will give you only those sub-arrays equal to [0, 0, 0], and set those to [255, 255, 255].

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

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.