如何在单元格具有指定值的2d蒙版中查找top_left,top_right,bottom_left,right坐标? [英] How to find top_left, top_right, bottom_left, right coordinates in 2d mask where cell has specified value?
本文介绍了如何在单元格具有指定值的2d蒙版中查找top_left,top_right,bottom_left,right坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2D numpy数组,它是图像的蒙版.每个单元格都有0
或1
值.所以我想在值是1的数组中找到top:left,right,bottom:left,right.
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 where value is 1.
例如输入数组:
[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)]
这篇关于如何在单元格具有指定值的2d蒙版中查找top_left,top_right,bottom_left,right坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文