问题描述
我有一张面部皮肤的照片,周围有黑色像素.
I have a picture of the facial skin with black pixels around it.
图片是由像素(RGB)组成的3d阵列
The picture is an 3d array made up of pixels (RGB)
图片的数组=宽度*高度* 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.
黑色像素表示为零的数组.[0,0,0]
The black pixels represent as an array of zero. [0,0,0]
我想获取带有非黑色像素的2d数组,作为[[218,195,182].... [229,0,133] -仅包含面部肤色的像素
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
我尝试通过查找所有RGB等于0的所有像素来弹出黑色像素,仅类似于[0,0,0] :
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
请注意,我不想从像[255,0,125] [0,0,255]之类的像素中提取零,因此numpy的非零方法不适合
如何以更高效,更快捷的方式编写它?
How to write it in a more efficient and fast way?
谢谢
推荐答案
假设您的图片位于 img
中.您可以使用以下代码:
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)
输出(二维数组)为:
[[ 1 2 0]
[24 5 67]
[ 8 4 5]
[24 5 67]
[10 0 0]
[ 8 4 5]]
这篇关于如何在Python中通过删除黑色像素(即[0,0,0])从图像的3D数组中获取2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!