简体   繁体   English

如何过滤 3D RGB numpy 数组

[英]How to filter a 3D RGB numpy array

I want to get a 2d mask array of green color.我想得到一个绿色的二维掩码数组。 Code:代码:

W = 100; H = 100

Map = np.zeros((W,H,3), dtype=int)

Map[1,1] = [0,255,0]

MResult = (Map[:,:] == [0,255,0])

A = np.zeros((W,H))

A[MResult] = 1

Not works.不工作。

I think there is also a conceptual mistake in your code, the height should be the first dimension, so Map should be np.zeros((H,W,3), dtype='int') .我认为您的代码中还有一个概念错误,高度应该是第一个维度,所以 Map 应该是np.zeros((H,W,3), dtype='int') Also note that dtype is a string, not the python built-in int.另请注意,dtype 是一个字符串,而不是 python 内置的 int。

Now returning to the problem, you need to use numpy's smart indexing to better manipulate the arrays.现在回到问题上来,您需要使用numpy 的智能索引来更好地操作数组。 It seems that you want to set the green channel to 255 in Map, you would do so by doing Map[:,:,1] = 255 note that we use : to say "all the elements in the row and column, and in channel 1 should be set to 255".似乎您想在 Map 中将绿色通道设置为 255,您可以通过执行Map[:,:,1] = 255注意我们使用:来表示“行和列中的所有元素,并且在通道 1 应设置为 255"。

Then we get a binary mask for A, we should do MResult = Map[:,:,1] == 255 , and in the end we simply do the A[MResult] = 1 as you did.然后我们得到 A 的二进制掩码,我们应该做MResult = Map[:,:,1] == 255 ,最后我们像你一样简单地做A[MResult] = 1

To check only green channel is not good idea, we get white color too.只检查绿色通道不是一个好主意,我们也会得到白色。

But code:但是代码:

import numpy as np

W = 100; H = 100

Map = np.zeros((W,H,3), dtype=int)

Map[1,1] = [0,255,0]

A = np.zeros((W,H))

A[(0 == Map[:,:,0]) & (255 == Map[:,:,1]) & (0 == Map[:,:,2])] = 1

now to works.现在开始工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM