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

妖精的绣舞 提交于 2021-02-10 16:54:29

问题


I have a picture of the facial skin with black pixels around it.

The picture is an 3d array made up of pixels (RGB)

picture's array = width * height * RGB

The problem is that in the picture there are so many black pixels that do not belong to the skin.

The black pixels represent as an array of zero. [0,0,0]

I want to get 2d array with non-black pixels as [[218,195,182]. ... [229,0, 133]] -with only the pixels of facial skin color

I try to eject the black pixels by finding all the pixels whose all RGB is equal to 0 like [0,0,0] only:

        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

Note that I do not want to extract zeros from pixels like: [255,0,125] [0,0,255] and so on, therefore the numpy's nonzero method is not suitable

How to write it in a more efficient and fast way?

Thanks


回答1:


Suppose your image is in img. You can use the code below:

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)

The output (2D array) is:

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



回答2:


Say your image is img with shape (w, h, 3) or (h, w, 3). Then you could do:

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


来源:https://stackoverflow.com/questions/63240730/how-to-get-2d-array-from-3d-array-of-an-image-by-removing-black-pixels-i-e-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!