【问题标题】:Numpy masking in 3 channel array3 通道阵列中的 Numpy 掩码
【发布时间】:2022-11-19 08:46:12
【问题描述】:

以下代码段将创建一个测试图像

# Create 3x3x3 image
test_image = []
for i in range(9):
    if i < 6:
        image.append([255, 22, 96])
    else:
        image.append([255, 0, 0])

出去:

array([[[255,  22,  96],
        [255,  22,  96],
        [255,  22,  96]],

       [[255,  22,  96],
        [255,  22,  96],
        [255,  22,  96]],

       [[255,   0,   0],
        [255,   0,   0],
        [255,   0,   0]]], dtype=int32)

我的目标是为每个零点创建一个单通道图像 [255, 22, 96] 在 test_image 中,我想在新的 single_channel 图像中设置数字 100:

我尝试了以下内容:

test_image = np.array(test_image)
height, width, channels = test_image.shape
single_channel_img = np.zeros(test_image.shape, dtype=int)

msk = test_image ==  [255, 22, 96] # DOES NOT WORK AS EXPECTED
single_channel_img[msk] = 100

这不起作用,因为屏蔽的结果:

msk = test_image ==  [255, 22, 96]

回报:

array([[[ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True]],

       [[ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True]],

       [[ True, False, False],
        [ True, False, False],
        [ True, False, False]]])

为什么最后 3 个像素的掩码返回 True,我如何确保只有当所有 3 个值都相同时比较才返回 True。我的假设是,当所有 3 个 RGB 值都等于 [255、22、96] 时,我屏蔽的方式应该只返回 True。

【问题讨论】:

  • Numpy 不知道像素。它正在一个一个地比较数组元素。您可以使用 all 来减少它。我相信 msk.all(axis=2) 应该这样做。如果所有部分都为真,则返回真。

标签: python image numpy opencv rgb


【解决方案1】:

您可以使用数组广播将 msk 转换为 3-D 数组: https://numpy.org/doc/stable/user/basics.broadcasting.html

import  numpy as np

# Create 3x3x3 image
test_image = []
for i in range(9):
    if i < 6:
        test_image.append([255, 22, 96])
    else:
        test_image.append([255, 0, 0])

test_image         = np.array(test_image).reshape((3,3,3))
single_channel_img = np.zeros(test_image.shape, dtype=int)

msk = test_image == np.array([255,22,96]).reshape((1,1,3)) # DOES NOT WORK AS EXPECTED
single_channel_img[msk] = 100

print(single_channel_img)
# [[[100 100 100]
#   [100 100 100]
#   [100 100 100]]
# 
#  [[100 100 100]
#   [100 100 100]
#   [100 100 100]]
# 
#  [[100   0   0]
#   [100   0   0]
#   [100   0   0]]]

【讨论】:

    猜你喜欢
    • 2016-03-17
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 2014-02-07
    • 1970-01-01
    • 2016-05-24
    相关资源
    最近更新 更多