numpy操作:将绿色转换为红色

时间:2022-03-07 00:23:28

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:

图像处于numpy数组中,如下所示:

x.shape (50, 15, 3)

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.

在第一个实例中,我想取第三维(R和G)的前两个元素的最大值,并将相应的值设置为R(第一个元素)。然后我想设置第三个维度零的第二个元素(G)。

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

我怎样才能做到这一点?基本上它需要是这样的:

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

1 个解决方案

#1


1  

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 -

或者,我们也可以使用np.maximum进行元素方式的最大计算 -

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]

#1


1  

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 -

或者,我们也可以使用np.maximum进行元素方式的最大计算 -

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]