【问题标题】:Calculate mask from comparing values of two Numpy arrays that are different shapes通过比较两个不同形状的 Numpy 数组的值来计算掩码
【发布时间】:2019-06-04 15:54:56
【问题描述】:

给定这两个数组:

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]

【问题讨论】:

    标签: python numpy numpy-ndarray


    【解决方案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]]])
    

    【讨论】:

      猜你喜欢
      • 2018-03-30
      • 1970-01-01
      • 2019-11-11
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 2018-06-30
      • 1970-01-01
      • 2019-07-24
      相关资源
      最近更新 更多