Reputation: 9745
I have a following numpy array:
a = np.array([[0, 1], [1, 0]])
What should I do with it to make it like this:
np.array([[[0, 0, 0], [255, 255, 255]], [[255, 255, 255], [0, 0, 0]]])
Each 0 is transformed to [0, 0, 0]
and each 1 to [255, 255, 255]
.
I have tried different ways of multiplication but it didn't help.
I need such transformation to be as fast as possible, because a
is supposed to have million elements and I want to store them into an image, so I need to prepare raw data for PIL.Image.fromarray
. I want exactly RGB format because after the transformation over a
I add some colored extra pixels in certain coordinaes.
Upvotes: 0
Views: 28
Reputation: 3276
You could either replace each of the values with a [[[256, 256, 256]]]
or [[[0, 0, 0]]]
:
np.where(a.reshape(*a.shape, 1), np.full([1, 1, 3], 255), np.full([1, 1, 3], 0))
Or repeat the entire array 3 times and then reshape accordingly:
np.repeat(a * 255, 3).reshape(*a.shape, 3)
Upvotes: 1
Reputation: 10792
With basic array indexing you can achieve what you want:
# Example input:
a = np.array([[0, 1], [1, 0]]) # Your index
x = np.array([[0, 0, 0], [255, 255, 255]]) # The mapped array
# Get the result:
r = x[a]
Upvotes: 2