我有一个 2D numpy 数组,它是一个图像的掩码。每个单元格都有0或1值。所以我想在值为 1 的数组中找到 top:left,right,bottom:left,right 。
例如输入数组:
[00000]
[01110]
[01100]
[00000]
Run Code Online (Sandbox Code Playgroud)
预期输出: (1,1), (1,3), (2,1), (2,2)
Using np.argwhere and 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)
Run Code Online (Sandbox Code Playgroud)
Output:
[array([1, 1], dtype=int64),
array([2, 1], dtype=int64),
array([1, 3], dtype=int64),
array([2, 2], dtype=int64)]
Run Code Online (Sandbox Code Playgroud)