Nickpick
Nickpick

Reputation: 6597

numpy operation: convert green to red

I have images that I would like to convert to red in case there is any green. If there's red, I'd like to keep it.

The images are in numpy arrays as follows:

x.shape (50, 15, 3)

In a fist instance I would like to take the max value of the first two elements of the third dimension (R and G) and set the corresponding value to R (the first element). Then I would like to set the second element (G) of the third dimension zo zero.

How can I do this? Essentially it woul need to be something like that:

x[:,:,0] = max(x[:,:,0],x[:,:,1])
x[:,:,1] = 0

Upvotes: 0

Views: 153

Answers (1)

Divakar
Divakar

Reputation: 221684

It seems you have already figured out the second step. Here's one way to do the first step -

x[...,0] = x[...,:2].max(axis=-1)

Alternatively, we can also use np.maximum for the element-wise max computation -

x[...,0] = np.maximum(x[...,0], x[...,1])

Alternatively, we can also use masking -

mask = x[...,0] < x[...,1]
x[mask,0] = x[mask,1]

Upvotes: 1

Related Questions