我正在尝试使用每个图像的 col 和 row wise 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))
我们会有)
最佳答案
为了提高效率,这里有一个 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]
sample 运行-
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)
sample 运行-
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]])
关于python - 有效地获取 3D 阵列中堆叠图像的图像边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54539327/