如何选择 NumPy 数组中的所有非黑色像素?

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

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

http://img3.mukewang.com/60ecf95d00012dd901530245.jpg

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

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

但是当我尝试这样做时:

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

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

http://img1.mukewang.com/60ecf9660001e9f001680245.jpg

看起来 NumPy 只返回了 R、G 和 B 非 0 的索引


这是我正在尝试做的一个最小的例子:


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)


扬帆大鱼
浏览 253回答 3
3回答

Helenr

必要性:需要具有这种形状的矩阵 = (any,any,3)解决方案:COLOR = (255,0,0)indices = np.where(np.all(mask == COLOR, axis=-1))indexes = zip(indices[0], indices[1])for i in indexes:&nbsp; &nbsp; print(i)解决方案2:获取特定颜色的间隔,例如 RED:COLOR1 = [250,0,0]COLOR2 = [260,0,0] # doesnt matter its over limitindices1 = np.where(np.all(mask >= COLOR1, axis=-1))indexes1 = zip(indices[0], indices[1])indices2 = np.where(np.all(mask <= COLOR2, axis=-1))indexes2 = zip(indices[0], indices[1])# You now want indexes that are in both indexes1 and indexes2解决方案 3 - 证明有效如果以前的不起作用,那么有一种解决方案可以 100% 有效从 RGB 通道转换为 HSV。从 3D 图像制作 2D 蒙版。2D 蒙版将包含色调值。比较色相比 RGB 更容易,因为色相是 1 个值,而 RGB 是具有 3 个值的向量。在您拥有带有 Hue 值的 2D 矩阵后,请执行上述操作:HUE1 = 0.5HUE2 = 0.7&nbsp;indices1 = np.where(HUEmask >= HUE1)indexes1 = zip(indices[0], indices[1])indices2 = np.where(HUEmask <= HUE2)indexes2 = zip(indices[0], indices[1])您可以对 Saturation 和 Value 执行相同的操作。

人到中年有点甜

对于选择非黑色像素的特殊情况,在查找非零像素之前将图像转换为灰度会更快:non_black_indices&nbsp;=&nbsp;np.nonzero(cv2.cvtColor(img,cv2.COLOR_BGR2GRAY))然后将所有黑色像素更改为白色,例如:img[non_black_indices]&nbsp;=&nbsp;[255,255,255]同样,这仅适用于选择非 [0,0,0] 像素,但如果您正在处理数千张图像,则较一般方法的速度提升变得显着。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python