我有 2D numpy 数组,它是图像的掩码。每个单元格都有
0
或 1
值。所以我想在值为1的数组中找到top:left,right,bottom:left,right。
例如输入数组:
[00000]
[01110]
[01100]
[00000]
预期输出:
(1,1), (1,3), (2,1), (2,2)
使用
np.argwhere
和itertools.product
:
import numpy as np
from itertools import product
def corners(np_array):
ind = np.argwhere(np_array)
res = []
for f1, f2 in product([min,max], repeat=2):
res.append(f1(ind[ind[:, 0] == f2(ind[:, 0])], key=lambda x:x[1]))
return res
corners(arr)
输出:
[array([1, 1], dtype=int64),
array([2, 1], dtype=int64),
array([1, 3], dtype=int64),
array([2, 2], dtype=int64)]
您可以使用
numpy.amax
操作来查找多维数组中的最大值。如下
def corners_v2(np_array):
max_values = np.amax(np_array)
result = np.where(np_array == np.amax(np_array))
x1 = np.min(result[0])
x2 = np.max(result[0])
y1 = np.min(result[1])
y2 = np.max(result[1])
return x1, y1, x2, y2
xy=np.array([[0,0,0,0,0],[0,1,1,1,0],[0,1,1,0,0],[0,0,0,0,0]])
x,y=np.where(xy==1)
tl_i=np.argmin(x)
tl=[x[tl_i],y[tl_i]]
tr_i=np.argmax(y)
tr=[x[tr_i],y[tr_i]]
bl_i=np.argmax(x)
bl=[x[bl_i],y[bl_i]]
br_i=len(x)-1-np.argmax(np.flip(x))
br=[x[br_i],y[br_i]]
使用
transpose
中的 nonzero
和 numpy
,例如:
im=np.array([[0,0,0,0,0],
[0,1,1,1,0],
[0,1,1,0,0],
[0,0,0,0,0]])
print(np.transpose(np.nonzero(im)))
产量:
array([[1, 1],
[1, 2],
[1, 3],
[2, 1],
[2, 2]])
更新: 仍然不完美,但只要蒙版在其行内是连续,您就可以评估
np.diff()
以了解0->1
和1->0
过渡在哪里:
leftedge=np.transpose(np.nonzero(np.diff(im,prepend=0)==1))
rightedge=np.transpose(np.nonzero(np.diff(im,append=0)==-1))
top_left = leftedge[0]
bottom_left = leftedge[-1]
bottom_right = rightedge[-1]
top_right = rightedge[0]
pts=[list(x) for x in [top_left,top_right,bottom_left,bottom_right]]
产量:
[[1, 1], [1, 3], [2, 1], [2, 2]]
我建议使用克里斯的答案代替。
def get_corners(mask):
mask_ = mask.copy()
mask_[mask_!=0]=1
row_sumed = np.sum(mask_, axis=0)
col_sumed = np.sum(mask_, axis=1)
w_nonzeros_ids = np.where(row_sumed!=0)
h_nonzeros_ids = np.where(col_sumed!=0)
return w_nonzeros_ids[0][0], h_nonzeros_ids[0][0], w_nonzeros_ids[0][-1], h_nonzeros_ids[0][-1]