python cv2 eject black color from skin-mask 3d array image

471 Views Asked by At

From face image i get a skin-mask of image with cv2 as i find here

The result is an array of arrays (image) made up of pixels (RGB)

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

skin picture

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:

Note that I do not want to extract zeros from pixels like: [255,0,125] [0,0,255] and so on.

        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

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

Thanks

2

There are 2 best solutions below

0
to-b On BEST ANSWER

I asked this question here in a different way and got a great answer.

Good luck!

3
Farhood ET On

if the values are zeros, they are essentially not contributing to your image in matrix multiplications. But if you want to show your image without black pixels, you can add an alpha mask and make those pixels transparent.

def make_transparent(img):
    tmp = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    _,alpha = cv2.threshold(tmp,0,255,cv2.THRESH_BINARY)
    b, g, r = cv2.split(img)
    rgba = [b,g,r, alpha]
    dst = cv2.merge(rgba,4)
    return dst

EDIT: if you want to find non-black pixels, you can use numpy's nonzero method.

desired_pixels = img[img.nonzero()]