简体   繁体   中英

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') . Also note that dtype is a string, not the python built-in int.

Now returning to the problem, you need to use numpy's smart indexing to better manipulate the arrays. 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".

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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