【问题标题】:Get image boundaries across stacked images in 3D array efficiently有效获取 3D 阵列中堆叠图像的图像边界
【发布时间】:2019-06-29 13:29:36
【问题描述】:

我正在尝试使用每个图像的 col 和 row 明智的 min 和 max 非零值来装箱 MNIST 图像。我可以使用 for 循环来做到这一点,但我想知道它是否可以在没有循环的情况下完成。这是一些玩具数据

arr = np.array([[[0, 0, 0, 0, 0],
        [0, 1, 1, 1, 0],
        [0, 1, 0, 1, 0],
        [0, 1, 0, 0, 0],
        [0, 0, 0, 0, 0]],

        [[0, 0, 0, 0, 0],
        [0, 1, 1, 0, 0],
        [0, 1, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0]]])

例如。对于 arr[0] 我想检索非零图片边界为

row_min, row_max, col_min, col_max = [1, 3, 1, 3]

我正在使用 for 循环执行此操作,如下所示,它可以工作

for val in arr:
    row_max, col_max = np.apply_along_axis(max,1,np.nonzero(val))
    row_min, col_min = np.apply_along_axis(min,1,np.nonzero(val)) 
    val[row_min:row_max+1,[col_min,col_max]] = 1
    val[[row_min,row_max],col_min:col_max+1] = 1

但是,我想避免 for 循环(我目前将上述代码放在单独的函数中)并将此转换内联。

np.apply_over_axes 对我不起作用,因为 np.nonzero 不采用任何轴值。我不确定如何沿第一个轴拆分数组(然后继续为我们将拥有的每个二维数组应用 np.apply_along_axis(min,1,np.nonzero(val)))

【问题讨论】:

  • 如果图像全为零会怎样?
  • 有趣 - 我仔细想想,我拥有的图像数据不包含这种情况。对于全零图像,我当前编写的代码框在 [0,0] 处,因此它只是一个值为 1 的像素。我在后续步骤中将图像裁剪并缩放为 20x20 - 我想我会必须过滤掉这种情况

标签: python numpy vectorization


【解决方案1】:

这里有一个 argmax 以提高效率 -

def get3Dboundaries(arr):
    row_start = arr.any(2).argmax(1)
    row_end = arr.shape[1]-arr.any(2)[:,::-1].argmax(1)-1

    col_start = arr.any(1).argmax(1)
    col_end = arr.shape[2]-arr.any(1)[:,::-1].argmax(1)-1

    return np.c_[row_start,row_end,col_start,col_end]

示例运行 -

In [61]: arr
Out[61]: 
array([[[0, 0, 0, 0, 0],
        [0, 1, 1, 1, 0],
        [0, 1, 0, 1, 0],
        [0, 1, 0, 0, 0],
        [0, 0, 0, 0, 0]],

       [[0, 0, 0, 0, 0], # different second slice for variety
        [1, 1, 1, 1, 0],
        [0, 1, 0, 1, 0],
        [0, 0, 0, 1, 0],
        [0, 0, 0, 1, 0]]])

In [62]: get3Dboundaries(arr)
Out[62]: 
array([[1, 3, 1, 3],
       [1, 4, 0, 3]])

我们可以让它处理带有无效说明符的全零情况,比如-1,就像这样 -

def get3Dboundaries_v2(arr):
    row_start = arr.any(2).argmax(1)
    row_end = arr.shape[1]-arr.any(2)[:,::-1].argmax(1)-1

    col_start = arr.any(1).argmax(1)
    col_end = arr.shape[2]-arr.any(1)[:,::-1].argmax(1)-1

    out = np.c_[row_start,row_end,col_start,col_end]
    return np.where(arr.any((1,2))[:,None],out,-1)

示例运行 -

In [76]: arr
Out[76]: 
array([[[0, 0, 0, 0, 0],
        [0, 1, 1, 1, 0],
        [0, 1, 0, 1, 0],
        [0, 1, 0, 0, 0],
        [0, 0, 0, 0, 0]],

       [[0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0]]])

In [78]: get3Dboundaries_v2(arr)
Out[78]: 
array([[ 1,  3,  1,  3],
       [-1, -1, -1, -1]])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2019-07-28
    • 1970-01-01
    • 2021-08-21
    相关资源
    最近更新 更多