如何逐行解析numpy数组

how to parse numpy array by line

使用cv2处理PNG图片,希望部分区域透明。 将点 [0, 0, 0, 255] 更改为 [0, 0, 0, 0].

例如,

# 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],
      ...,
     ]]

谢谢。

您需要创建一个遮罩。

这是一个简单的例子:

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()

现在创建一个蒙版:

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]])

现在将必要的值设置为 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]]])
​