如何通过在 python 中移除黑色像素,即 [0,0,0],从图像的 3D 数组中获取 2D 数组

How to get 2D array from 3D array of an image by removing black pixels, i.e. [0,0,0], in python

我有一张面部皮肤的照片,周围有黑色像素。

图片是由像素(RGB)组成的3d数组

图片的数组=宽*高*RGB

问题是图片中有很多不属于皮肤的黑色像素点

黑色像素表示为零数组。 [0,0,0]

我想得到非黑色像素的二维数组 [[218,195,182]。 ... [229,0, 133]] - 只有面部肤色的像素

我尝试通过查找所有 RGB 等于 0 的所有像素来弹出黑色像素 仅像 [0,0,0]:

        def eject_black_color(skin):
            list=[]
            #loop over pixels of skin-image
            for i in range(skin.shape[0]):
                for j in range(skin.shape[1]):
                    if(not (skin[i][j][0]==0 and skin[i][j][1]==0 and skin[i][j][2]==0)):
                        #add only non-black pixels to list
                        list.append(skin[i][j])
            return list

请注意,我不想从像素中提取零,例如:[255,0,125] [0,0,255] 等等,因此 numpy 的非零方法不适合

如何编写更高效快捷?

谢谢

假设您的图像是 img,形状为 (w, h, 3)(h, w, 3)。那么你可以这样做:

import numpy as np
img = np.array(img)                          # If your image is not a numpy array
myList = img[np.sum(img, axis = -1) != 0]    # Get 2D list

假设您的图像在 img 中。您可以使用以下代码:

import numpy as np

img=np.array([[[1,2,0],[24,5,67],[0,0,0],[8,4,5]],[[0,0,0],[24,5,67],[10,0,0],[8,4,5]]])
filter_zero=img[np.any(img!=0,axis=-1)]   #remove black pixels 
print(filter_zero)

输出(二维数组)为:

[[ 1  2  0]
 [24  5 67]
 [ 8  4  5]
 [24  5 67]
 [10  0  0]
 [ 8  4  5]]