如何在NumPy数组中选择所有非黑色像素? [英] How to select all non-black pixels in a NumPy array?

查看:155
本文介绍了如何在NumPy数组中选择所有非黑色像素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用NumPy获取与特定颜色不同的图像像素列表.

I am trying to get a list of an image's pixels that are different from a specific color using NumPy.

例如,在处理以下图像时:

For example, while processig the following image:

我设法使用以下方法获得了所有黑色像素的列表:

I've managed to get a list of all black pixels using:

np.where(np.all(mask == [0,0,0], axis=-1))

但是当我尝试这样做时:

But when I try to do:

np.where(np.all(mask != [0,0,0], axis=-1))

我得到一个非常奇怪的结果:

I get a pretty strange result:

NumPy似乎只返回了R,G和B的索引都不为0

It looks like NumPy has returned only the indices were R, G, and B are non-0

这是我要尝试做的一个最小示例:

Here is a minimal example of what I'm trying to do:

import numpy as np
import cv2

# Read mask
mask = cv2.imread("path/to/img")
excluded_color = [0,0,0]

# Try to get indices of pixel with different colors
indices_list = np.where(np.all(mask != excluded_color, axis=-1))

# For some reason, the list doesn't contain all different colors
print("excluded indices are", indices_list)

# Visualization
mask[indices_list] = [255,255,255]

cv2.imshow(mask)
cv2.waitKey(0)

推荐答案

您应使用 np.any 而不是 np.all 用于选择除黑色像素以外的所有像素的第二种情况:

You should use np.any instead of np.all for the second case of selecting all but black pixels:

np.any(image != [0, 0, 0], axis=-1)

或者通过


工作示例:

import numpy as np
import matplotlib.pyplot as plt


image = plt.imread('example.png')
plt.imshow(image)
plt.show()

image_copy = image.copy()

black_pixels_mask = np.all(image == [0, 0, 0], axis=-1)

non_black_pixels_mask = np.any(image != [0, 0, 0], axis=-1)  
# or non_black_pixels_mask = ~black_pixels_mask

image_copy[black_pixels_mask] = [255, 255, 255]
image_copy[non_black_pixels_mask] = [0, 0, 0]

plt.imshow(image_copy)
plt.show()

如果有人使用matplotlib绘制结果并获得全黑图像或警告,请参阅以下文章:

In case if someone is using matplotlib to plot the results and gets completely black image or warnings, see this post: Converting all non-black pixels into one colour doesn't produce expected output

这篇关于如何在NumPy数组中选择所有非黑色像素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆