为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

扬帆大鱼 2021-07-02 10:01:10
我正在尝试使用 NumPy 获取与特定颜色不同的图像像素列表。例如,在处理以下图像时:我设法使用以下方法获得所有黑色像素的列表:np.where(np.all(mask == [0,0,0], axis=-1))但是当我尝试这样做时:np.where(np.all(mask != [0,0,0], axis=-1))我得到了一个非常奇怪的结果:看起来 NumPy 只返回了 R、G 和 B 非 0 的索引这是我正在尝试做的一个最小的例子:import numpy as npimport cv2# Read maskmask = cv2.imread("path/to/img")excluded_color = [0,0,0]# Try to get indices of pixel with different colorsindices_list = np.where(np.all(mask != excluded_color, axis=-1))# For some reason, the list doesn't contain all different colorsprint("excluded indices are", indices_list)# Visualizationmask[indices_list] = [255,255,255]cv2.imshow(mask)cv2.waitKey(0)
查看完整描述

3 回答

?
Helenr

TA贡献1780条经验 获得超4个赞

必要性:需要具有这种形状的矩阵 = (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:

    print(i)

解决方案2:


获取特定颜色的间隔,例如 RED:


COLOR1 = [250,0,0]

COLOR2 = [260,0,0] # doesnt matter its over limit


indices1 = 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.5

HUE2 = 0.7 


indices1 = np.where(HUEmask >= HUE1)

indexes1 = zip(indices[0], indices[1])


indices2 = np.where(HUEmask <= HUE2)

indexes2 = zip(indices[0], indices[1])

您可以对 Saturation 和 Value 执行相同的操作。



查看完整回答
反对 回复 2021-07-13
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

对于选择非黑色像素的特殊情况,在查找非零像素之前将图像转换为灰度会更快:

non_black_indices = np.nonzero(cv2.cvtColor(img,cv2.COLOR_BGR2GRAY))

然后将所有黑色像素更改为白色,例如:

img[non_black_indices] = [255,255,255]

同样,这仅适用于选择非 [0,0,0] 像素,但如果您正在处理数千张图像,则较一般方法的速度提升变得显着。


查看完整回答
反对 回复 2021-07-13
  • 3 回答
  • 0 关注
  • 252 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号