Skip to content Skip to sidebar Skip to footer

How To Get 2d Array From 3d Array Of An Image By Removing Black Pixels, I.e. [0,0,0], In Python

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 th

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

Solution 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

Post a Comment for "How To Get 2d Array From 3d Array Of An Image By Removing Black Pixels, I.e. [0,0,0], In Python"