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

Calculate mask from comparing values of two Numpy arrays that are different shapes

给定这两个数组:

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)

我想在 0, 0 处叠加 ab,并输出表示 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]

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

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]]])