Home > other >  How to filter a 3D RGB numpy array
How to filter a 3D RGB numpy array

Time:06-26

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related