I have 2D numpy array which is a mask from an image. Each cell has 0
or 1
value. So I would like to find top:left,right, bottom:left,right in an array
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)
Output:
[array([1, 1], dtype=int64),
array([2, 1], dtype=int64),
array([1, 3], dtype=int64),
array([2, 2], dtype=int64)]