从比较两个不同形状的Numpy数组的值来计算掩码

3

考虑这两个数组:

a = np.array(
    [
        [
            [1, 102, 103, 255],
            [201, 2, 202, 255],
            [201, 202, 202, 255]
        ],
        [
            [11, 120, 0, 255],
            [0, 0, 0, 255],
            [1, 22, 142, 255]
        ],
    ])

b = np.array(
    [
        [
            [1, 102, 103, 255],
            [201, 2, 202, 255]
        ],
        [
            [11, 120, 0, 255],
            [221, 222, 13, 255]
        ],
        [
            [91, 52, 53, 255],
            [0, 0, 0, 255]
        ],
    ])

a.shape # => (2, 3, 4)
b.shape # => (3, 3, 4)

我希望将ab叠加在0, 0处,并输出一个掩码,表示当a的值等于b的值时。比较的值是完整的像素值,因此在这种情况下,[1, 102, 103, 255]是一个值。
像这样的输出掩码会很好:
result = np.array([
    [
        true,
        true,
        false
    ],
    [
        true,
        false,
        false
    ],
    [
        false,
        false,
        false
    ],
])

在我的情况下,完美的答案是匹配值变为[255, 0, 0, 255],不匹配的值变为[0, 0, 0, 0]
result = np.array([
    [
        [255, 0, 0, 255],
        [255, 0, 0, 255],
        [0, 0, 0, 0]
    ],
    [
        [255, 0, 0, 255],
        [0, 0, 0, 0],
        [0, 0, 0, 0]
    ],
    [
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0]
    ],
])

result.shape # => (3, 3, 4)

看起来是这样的:

[![a和b之间的差异][1]][1]

1个回答

3

以下是使用切片的一种可能性。

outer = np.maximum(a.shape, b.shape)
inner = *map(slice, np.minimum(a.shape, b.shape)),
out = np.zeros(outer, np.result_type(a, b))
out[inner][(a[inner]==b[inner]).all(2)] = 255,0,0,255

out
# array([[[255,   0,   0, 255],
#         [255,   0,   0, 255],
#         [  0,   0,   0,   0]],
#
#        [[255,   0,   0, 255],
#         [  0,   0,   0,   0],
#         [  0,   0,   0,   0]],
#
#        [[  0,   0,   0,   0],
#         [  0,   0,   0,   0],
#         [  0,   0,   0,   0]]])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接