Home > other >  how to parse numpy array by line
how to parse numpy array by line

Time:05-07

Use cv2 to process PNG image, I want some areas to be transparent. change point [0, 0, 0, 255] to [0, 0, 0, 0].

for example,

# a is ndarray(880, 1330, 4)
a = [[[100, 90, 80, 255], 
      [80, 10, 10, 255],], 
      ...,
     [[0, 0, 0, 255],
      [0, 0, 0, 255],
      ...,
     ]]

# i want 
b = [[100, 90, 80, 255], 
      [80, 10, 10, 255],], 
      ...,
     [[0, 0, 0, 0],
      [0, 0, 0, 0],
      ...,
     ]]

thanks.

CodePudding user response:

You need to create a mask.

Here is a simple example:

import numpy as np
# Create some data
a = (np.random.rand(10, 10, 4)*255).astype(int)
a[ :5, :5, :] = 0
a[:, :, 3]    = 255
b = a.copy()

Now create a mask:

mask = (a[:,:,0] == 0) & (a[:,:,1] == 0) & (a[:,:,2] == 0)
print(mask*1)

array([[1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

Now set the requisite values to 0

b[mask, 3] = 0
print(b)

array([[[  0,   0,   0,   0],
        [  0,   0,   0,   0],
        [  0,   0,   0,   0],
        [  0,   0,   0,   0],
        [  0,   0,   0,   0],
        [204, 156, 208, 255],
        [ 59, 220, 240, 255],
        [217, 175,  19, 255],
 <. other rows..>
        [235, 127, 178, 255],
        [168,  29, 119, 255],
        [ 25, 228, 112, 255],
        [110, 237,  39, 255],
        [164,  23, 191, 255],
        [169, 232,   5, 255],
        [164,  59, 206, 255],
        [ 52,  65,  60, 255]]])
​

  • Related